Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

Support GA Gradium Phonon checkpoints (#19227)

Daniel Hiltgen5e31438d5d22
diff --git a/create/inventory.go b/create/inventory.go
index 9f2f0ec57..19deb7354 100644
--- a/create/inventory.go
+++ b/create/inventory.go
@@ -128,6 +128,23 @@ func SafetensorsWeightFiles(dir string) ([]string, error) {
if err != nil {
return nil, err
}
+ if _, err := os.Stat(filepath.Join(dir, "config.json")); err == nil {
+ cfg, _, err := readSourceModelConfig(dir)
+ if err != nil {
+ return nil, err
+ }
+ if cfg.Architecture() == gradiumPhononArchitecture {
+ files, err = appendWeightSidecar(dir, files, "default-voice.safetensors", "Phonon")
+ if err != nil {
+ return nil, err
+ }
+ if !slices.Contains(files, "default-voice.safetensors") {
+ return nil, fmt.Errorf("Phonon checkpoint requires default-voice.safetensors")
+ }
+ }
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
if _, err := os.Stat(filepath.Join(dir, "readout.safetensors")); errors.Is(err, os.ErrNotExist) {
return files, nil
} else if err != nil {
diff --git a/create/metadata.go b/create/metadata.go
index 053968f92..a170ab650 100644
--- a/create/metadata.go
+++ b/create/metadata.go
@@ -79,7 +79,7 @@ func inferSafetensorsConfig(modelDir string, cfg sourceModelConfig, parserOverri
if decisionVision {
capabilities = append(capabilities, "vision")
}
- } else if cfg.Architecture() == "Phonon" {
+ } else if isPhononArchitecture(cfg.Architecture()) {
capabilities = []string{"speech"}
} else {
capabilities = inferCompletionCapabilitiesFromConfig(cfg, chatTemplate, parserName)
diff --git a/create/metadata_test.go b/create/metadata_test.go
index 31c8f786d..972248afe 100644
--- a/create/metadata_test.go
+++ b/create/metadata_test.go
@@ -239,7 +239,7 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
},
{
name: "phonon",
- config: `{"architectures":["Phonon"],"model_type":"phonon"}`,
+ config: `{"architectures":["GradiumPhononTTSForConditionalGeneration"],"model_type":"gradium_phonon_tts"}`,
wantCaps: []string{"speech"},
},
{
diff --git a/create/phonon.go b/create/phonon.go
new file mode 100644
index 000000000..ab18d0f14
--- /dev/null
+++ b/create/phonon.go
@@ -0,0 +1,47 @@
+package create
+
+import (
+ "fmt"
+ "path/filepath"
+ "slices"
+
+ "github.com/ollama/ollama/fs/safetensors"
+)
+
+const gradiumPhononArchitecture = "GradiumPhononTTSForConditionalGeneration"
+
+func isPhononArchitecture(architecture string) bool {
+ return architecture == gradiumPhononArchitecture
+}
+
+// The publisher keeps its default speaker latents beside the model weights.
+// Import them as a separate tensor so the runner can project them with the
+// checkpoint's own speaker projection at load time.
+func prepareGradiumPhononInventory(inv Inventory) (Inventory, error) {
+ const filename = "default-voice.safetensors"
+ reader, err := safetensors.OpenForExtraction(filepath.Join(inv.Dir, filename))
+ if err != nil {
+ return Inventory{}, fmt.Errorf("open Phonon default voice: %w", err)
+ }
+ defer reader.Close()
+ if names := reader.ListTensors(); !slices.Equal(names, []string{"speaker_wavs"}) {
+ return Inventory{}, fmt.Errorf("Phonon default voice must contain only speaker_wavs, got %v", names)
+ }
+ voice, err := reader.GetTensor("speaker_wavs")
+ if err != nil {
+ return Inventory{}, fmt.Errorf("read Phonon default voice: %w", err)
+ }
+ if voice.Dtype != "F32" || len(voice.Shape) != 3 || voice.Shape[0] != 1 || voice.Shape[1] != 512 || voice.Shape[2] <= 0 {
+ return Inventory{}, fmt.Errorf("unsupported Phonon default voice: %s %v", voice.Dtype, voice.Shape)
+ }
+ if !inv.Has("flow_lm.condition_provider.conditioners.speaker_wavs.output_proj.weight") {
+ return Inventory{}, fmt.Errorf("Phonon checkpoint has no speaker projection")
+ }
+ if inv.Has("voices.default") {
+ return Inventory{}, fmt.Errorf("Phonon checkpoint already defines voices.default")
+ }
+ inv.Tensors["voices.default"] = SourceTensor{
+ Name: "speaker_wavs", Dtype: voice.Dtype, Shape: voice.Shape, File: filename,
+ }
+ return inv, nil
+}
diff --git a/create/phonon_test.go b/create/phonon_test.go
new file mode 100644
index 000000000..cf17eb721
--- /dev/null
+++ b/create/phonon_test.go
@@ -0,0 +1,82 @@
+package create
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ st "github.com/ollama/ollama/fs/safetensors"
+)
+
+func writeGradiumPhononSource(t *testing.T, dir string, voiceShape []int32) {
+ t.Helper()
+ writeConfigJSON(t, dir, `{"architectures":["GradiumPhononTTSForConditionalGeneration"],"model_type":"gradium_phonon_tts"}`)
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("flow_lm.condition_provider.conditioners.speaker_wavs.output_proj.weight", "BF16", []int32{512, 512}, make([]byte, 512*512*2)),
+ })
+ voiceBytes := 4
+ for _, size := range voiceShape {
+ voiceBytes *= int(size)
+ }
+ createTestSafetensors(t, filepath.Join(dir, "default-voice.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("speaker_wavs", "F32", voiceShape, make([]byte, voiceBytes)),
+ })
+}
+
+func TestGradiumPhononImportsPublisherVoice(t *testing.T) {
+ dir := t.TempDir()
+ writeGradiumPhononSource(t, dir, []int32{1, 512, 2})
+ files, err := SafetensorsWeightFiles(dir)
+ if err != nil || !slices.Contains(files, "default-voice.safetensors") {
+ t.Fatalf("weight files = %v, %v", files, err)
+ }
+ store := newCaptureStore()
+ var got ManifestInfo
+ err = Create(t.Context(), "phonon-test", dir, testPipelineOptions(), store, func(_ context.Context, _ string, info ManifestInfo) error {
+ got = info
+ return nil
+ }, func(string) {})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(got.ModelConfig.Capabilities, []string{"speech"}) || got.ModelConfig.Requires != phononMinOllamaVersion {
+ t.Fatalf("model config = %+v", got.ModelConfig)
+ }
+ if store.blobs["voices.default"] == nil {
+ t.Fatalf("missing default voice blob: %v", store.names())
+ }
+}
+
+func TestGradiumPhononRejectsBadVoiceBeforeWriting(t *testing.T) {
+ dir := t.TempDir()
+ writeGradiumPhononSource(t, dir, []int32{1, 256, 2})
+ store := newCaptureStore()
+ err := Create(t.Context(), "phonon-test", dir, testPipelineOptions(), store,
+ func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
+ if err == nil || !strings.Contains(err.Error(), "unsupported Phonon default voice") || len(store.blobs) != 0 {
+ t.Fatalf("import error = %v; blobs = %v", err, store.names())
+ }
+ if err := os.Remove(filepath.Join(dir, "default-voice.safetensors")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SafetensorsWeightFiles(dir); err == nil || !strings.Contains(err.Error(), "requires default-voice.safetensors") {
+ t.Fatalf("missing voice transfer error = %v", err)
+ }
+}
+
+func TestPrereleasePhononImportRejected(t *testing.T) {
+ dir := t.TempDir()
+ writeConfigJSON(t, dir, `{"architectures":["Phonon"],"model_type":"phonon"}`)
+ createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
+ st.NewTensorDataFromBytes("flow_lm.bos_emb", "F32", []int32{4}, make([]byte, 16)),
+ })
+ store := newCaptureStore()
+ err := Create(t.Context(), "phonon-legacy", dir, PipelineOptions{}, store,
+ func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
+ if err == nil || !strings.Contains(err.Error(), "unsupported MLX architecture") || len(store.blobs) != 0 {
+ t.Fatalf("import error = %v; blobs = %v", err, store.names())
+ }
+}
diff --git a/create/pipeline.go b/create/pipeline.go
index af1ef6efe..638acd8d6 100644
--- a/create/pipeline.go
+++ b/create/pipeline.go
@@ -42,6 +42,12 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err != nil {
return fmt.Errorf("read model: %w", err)
}
+ if inv.Config.Architecture() == gradiumPhononArchitecture {
+ inv, err = prepareGradiumPhononInventory(inv)
+ if err != nil {
+ return err
+ }
+ }
if opts.Renderer == "clef" {
inv, err = prepareClefInventory(inv)
if err != nil {
@@ -73,7 +79,7 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
}
}
// Older releases can't run Phonon, whatever the Modelfile or client says.
- if inv.Config.Architecture() == "Phonon" && semver.Compare("v"+modelConfig.Requires, "v"+phononMinOllamaVersion) < 0 {
+ if isPhononArchitecture(inv.Config.Architecture()) && semver.Compare("v"+modelConfig.Requires, "v"+phononMinOllamaVersion) < 0 {
modelConfig.Requires = phononMinOllamaVersion
}
if err := validateMLXSource(inv.Config, false, opts.Validation); err != nil {
@@ -85,7 +91,7 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if inv.Config.Architecture() == "LayaForDecision" && opts.Quantize != "" {
return fmt.Errorf("Laya currently requires unquantized weights")
}
- if inv.Config.Architecture() == "Phonon" && opts.Quantize != "" {
+ if isPhononArchitecture(inv.Config.Architecture()) && opts.Quantize != "" {
return fmt.Errorf("Phonon currently requires unquantized weights")
}
class, err := Classify(inv, opts.Quantize)
diff --git a/create/pipeline_test.go b/create/pipeline_test.go
index 342c8b458..713c96cd9 100644
--- a/create/pipeline_test.go
+++ b/create/pipeline_test.go
@@ -77,10 +77,7 @@ func TestCreatePipeline(t *testing.T) {
func TestCreatePipelinePhononRequires(t *testing.T) {
dir := t.TempDir()
- writeConfigJSON(t, dir, `{"architectures":["Phonon"],"model_type":"phonon"}`)
- createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
- st.NewTensorDataFromBytes("flow_lm.bos_emb", "F32", []int32{4}, make([]byte, 4*4)),
- })
+ writeGradiumPhononSource(t, dir, []int32{1, 512, 2})
// Remote creates send the generic safetensors minimum; it must not win.
for requires, want := range map[string]string{"": phononMinOllamaVersion, "0.19.0": phononMinOllamaVersion, "0.41.0": "0.41.0"} {
var got string
diff --git a/docs/capabilities/speech.mdx b/docs/capabilities/speech.mdx
index 1323221bc..846d0ab89 100644
--- a/docs/capabilities/speech.mdx
+++ b/docs/capabilities/speech.mdx
@@ -7,13 +7,13 @@ Speech models read text aloud. Ollama streams the audio as it is generated, so p
## Setup
-Start [Ollama](/quickstart) v0.40.8 or later, then download [Phonon](https://ollama.com/library/phonon):
+Start [Ollama](/quickstart) v0.40.9 or later, then download [Phonon](https://ollama.com/library/phonon):
```shell setup.sh
ollama pull phonon
```
-Phonon speaks English with four voices: `Freya` (the default), `Harper`, `Sterling`, and `Toby`. Voice names are case-sensitive.
+The default Phonon model uses Gradium's 31M English checkpoint and its included voice. The voice name is `default`.
## Speak from the terminal
@@ -23,9 +23,6 @@ Phonon speaks English with four voices: `Freya` (the default), `Harper`, `Sterli
# Speak some text
ollama run phonon "Hello from Ollama."
-# Choose a voice
-ollama run phonon --voice Toby "Hi, this is Toby."
-
# Speak text from another program
echo "Text from another program works too." | ollama run phonon
@@ -65,7 +62,7 @@ Use the OpenAI-compatible `/v1/audio/speech` endpoint:
-d '{
"model": "phonon",
"input": "Hello from Ollama.",
- "voice": "Freya"
+ "voice": "default"
}' --output speech.wav
```
</Tab>
@@ -77,7 +74,7 @@ Use the OpenAI-compatible `/v1/audio/speech` endpoint:
with client.audio.speech.with_streaming_response.create(
model="phonon",
- voice="Freya",
+ voice="default",
input="Hello from Ollama.",
response_format="wav",
) as response:
@@ -93,7 +90,7 @@ Use the OpenAI-compatible `/v1/audio/speech` endpoint:
const response = await openai.audio.speech.create({
model: 'phonon',
- voice: 'Freya',
+ voice: 'default',
input: 'Hello from Ollama.',
response_format: 'wav',
})
diff --git a/docs/cli.mdx b/docs/cli.mdx
index e93d3e5e2..ad6c4e0d0 100644
--- a/docs/cli.mdx
+++ b/docs/cli.mdx
@@ -101,8 +101,6 @@ The state is piped in or given after the model name, as text or JSON. Each `--as
```
ollama run phonon "Hello from Ollama."
-ollama run phonon --voice Toby "Hi, this is Toby."
-
ollama run phonon "Save this to a file." > speech.wav
```
diff --git a/mlxrunner/model/phonon/conditions.go b/mlxrunner/model/phonon/conditions.go
new file mode 100644
index 000000000..4b1819061
--- /dev/null
+++ b/mlxrunner/model/phonon/conditions.go
@@ -0,0 +1,37 @@
+package phonon
+
+import (
+ "fmt"
+ "slices"
+
+ "github.com/ollama/ollama/mlx"
+ "github.com/ollama/ollama/mlxrunner/nn"
+)
+
+// The published checkpoints sum the default speaker count (one) and zero
+// duration adjustment into every generated frame. Their voice and text
+// prefixes are run through the transformer separately.
+func gradiumConditions(tensors map[string]*mlx.Array) (*mlx.Array, error) {
+ const prefix = "flow_lm.condition_provider.conditioners."
+ numEmb := tensors[prefix+"num_speakers.embed.weight"]
+ numProj := tensors[prefix+"num_speakers.output_proj.weight"]
+ durationProj := tensors[prefix+"duration_delta.output_proj.weight"]
+ if numEmb == nil || numProj == nil || durationProj == nil ||
+ !slices.Equal(numEmb.Dims(), []int{32, 16}) ||
+ !slices.Equal(numProj.Dims(), []int{512, 16}) ||
+ !slices.Equal(durationProj.Dims(), []int{512, 128}) {
+ return nil, fmt.Errorf("missing or invalid Gradium Phonon conditioners")
+ }
+ index := mlx.FromValues([]int32{1}, 1)
+ num := mlx.ExpandDims(mlx.Take(numEmb, index, 0), 1)
+ num = nn.NewLinear(numProj, nil).Forward(num)
+ // The duration delta defaults to zero. A sinusoidal embedding at zero has
+ // ones in its cosine half and zeros in its sine half.
+ duration := make([]float32, 128)
+ for i := range 64 {
+ duration[i] = 1
+ }
+ delta := mlx.FromValues(duration, 1, 1, len(duration)).AsType(durationProj.DType())
+ delta = nn.NewLinear(durationProj, nil).Forward(delta)
+ return mlx.Add(num, delta).AsType(mlx.DTypeBFloat16), nil
+}
diff --git a/mlxrunner/model/phonon/mimi.go b/mlxrunner/model/phonon/mimi.go
index 919ebb3bb..17868763b 100644
--- a/mlxrunner/model/phonon/mimi.go
+++ b/mlxrunner/model/phonon/mimi.go
@@ -56,7 +56,7 @@ func loadMimi(tensors map[string]*mlx.Array, cfg *config) (*Mimi, error) {
return nil, fmt.Errorf("missing mimi projection weights")
}
var err error
- if m.Transformer, err = loadTransformer(tensors, "mimi.decoder_transformer.transformer", t.NumLayers, t.NumHeads, t.MaxPeriod, cfg.gelu(t.GELU)); err != nil {
+ if m.Transformer, err = loadTransformer(tensors, "mimi.decoder_transformer.transformer", t.NumLayers, t.NumHeads, t.MaxPeriod, t.GELU); err != nil {
return nil, err
}
diff --git a/mlxrunner/model/phonon/model.go b/mlxrunner/model/phonon/model.go
index 020c1b91a..b2a7a1940 100644
--- a/mlxrunner/model/phonon/model.go
+++ b/mlxrunner/model/phonon/model.go
@@ -20,15 +20,14 @@ import (
"github.com/ollama/ollama/mlxrunner/tokenizer"
)
-func init() { model.Register("Phonon", newModel) }
+func init() {
+ model.Register("GradiumPhononTTSForConditionalGeneration", newModel)
+}
// config follows the upstream Phonon config.json.
type config struct {
- ModelID *struct {
- Sig string `json:"sig"`
- Epoch int `json:"epoch"`
- } `json:"model_id"`
FlowLM struct {
+ DModel int `json:"d_model"`
NumHeads int32 `json:"num_heads"`
NumLayers int32 `json:"num_layers"`
MaxPeriod float32 `json:"max_period"`
@@ -49,6 +48,20 @@ type config struct {
Temperature float32 `json:"temp"`
DecodeSteps int `json:"lsd_decode_steps"`
EOSThreshold float32 `json:"eos_threshold"`
+ Conditioners []struct {
+ Type string `json:"type"`
+ Name string `json:"name"`
+ LUT struct {
+ PossibleValues []string `json:"possible_values"`
+ } `json:"lut"`
+ Continuous struct {
+ Dim int `json:"dim"`
+ } `json:"continuous"`
+ } `json:"conditioners"`
+ Fuser struct {
+ Sum []string `json:"sum"`
+ Prepend []string `json:"prepend"`
+ } `json:"fuser"`
}
const (
@@ -61,7 +74,7 @@ type Model struct {
Embed *nn.Embedding
InputLinear *nn.Linear
BOS *mlx.Array
- NumSpeakers *mlx.Array
+ Conditions *mlx.Array
Flow *Transformer
OutNorm *nn.LayerNorm
EOS *nn.Linear
@@ -90,6 +103,15 @@ func newModel(root *model.Root) (model.Model, error) {
if err := root.Manifest.ReadConfigJSON("config.json", &cfg); err != nil {
return nil, fmt.Errorf("load config: %w", err)
}
+ var generation struct {
+ Temperature *float32 `json:"temperature"`
+ }
+ if err := root.Manifest.ReadConfigJSON("generation_config.json", &generation); err != nil {
+ return nil, fmt.Errorf("load generation config: %w", err)
+ }
+ if generation.Temperature != nil {
+ cfg.Temperature = *generation.Temperature
+ }
if err := cfg.validate(); err != nil {
return nil, err
}
@@ -104,24 +126,21 @@ func newModel(root *model.Root) (model.Model, error) {
return &Model{cfg: &cfg, tok: tok}, nil
}
-// gelu follows upstream's checkpoint defaults; an explicit activation wins.
-func (c *config) gelu(value string) string {
- if value != "" {
- return value
- }
- if c.ModelID != nil {
- return "erf"
- }
- return "tanh"
-}
-
func (c *config) validate() error {
+ if c.FlowLM.DModel != 512 || len(c.Conditioners) != 2 ||
+ c.Conditioners[0].Type != "lut" || c.Conditioners[0].Name != "num_speakers" ||
+ !slices.Equal(c.Conditioners[0].LUT.PossibleValues, []string{"0", "1", "2"}) ||
+ c.Conditioners[1].Type != "continuous" || c.Conditioners[1].Name != "duration_delta" || c.Conditioners[1].Continuous.Dim != 128 ||
+ !slices.Equal(c.Fuser.Sum, []string{"num_speakers", "duration_delta"}) ||
+ !slices.Equal(c.Fuser.Prepend, []string{"transcript_in_segment", "speaker_wavs"}) {
+ return fmt.Errorf("unsupported Gradium Phonon conditioning layout")
+ }
for _, value := range []string{c.FlowLM.GELU, c.Mimi.GELU} {
- if value != "" && value != "erf" && value != "tanh" {
+ if value != "erf" {
return fmt.Errorf("unsupported phonon GELU %q", value)
}
}
- if value := c.FlowLM.TimeRMSNorm; value != "" && value != "rms_var" && value != "rms" {
+ if value := c.FlowLM.TimeRMSNorm; value != "rms" {
return fmt.Errorf("unsupported phonon time norm %q", value)
}
if c.Mimi.SampleRate != sampleRate || c.Mimi.FrameRate != 12.5 {
@@ -149,8 +168,11 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
return fmt.Errorf("phonon requires unquantized floating-point weights: %s", name)
}
dtype := mlx.DTypeFloat32
- if strings.HasPrefix(name, "flow_lm.transformer.") || strings.HasPrefix(name, "voices.") ||
- name == "flow_lm.num_speakers" || name == "flow_lm.conditioner.embed.weight" || name == "flow_lm.input_linear.weight" {
+ if strings.HasPrefix(name, "flow_lm.transformer.") || name == "flow_lm.input_linear.weight" {
+ dtype = mlx.DTypeBFloat16
+ }
+ if strings.HasPrefix(name, "flow_lm.condition_provider.conditioners.") &&
+ name != "flow_lm.condition_provider.conditioners.speaker_wavs.output_proj.weight" {
dtype = mlx.DTypeBFloat16
}
if t.DType() != dtype {
@@ -159,7 +181,7 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
}
f := m.cfg.FlowLM
var err error
- if m.Flow, err = loadTransformer(tensors, "flow_lm.transformer", f.NumLayers, f.NumHeads, f.MaxPeriod, m.cfg.gelu(f.GELU)); err != nil {
+ if m.Flow, err = loadTransformer(tensors, "flow_lm.transformer", f.NumLayers, f.NumHeads, f.MaxPeriod, f.GELU); err != nil {
return err
}
if m.Head, err = loadFlowHead(tensors, "flow_lm.flow_net", f.FlowDepth, f.TimeRMSNorm); err != nil {
@@ -168,7 +190,7 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
if m.Mimi, err = loadMimi(tensors, m.cfg); err != nil {
return err
}
- if w := tensors["flow_lm.conditioner.embed.weight"]; w != nil {
+ if w := tensors["flow_lm.condition_provider.conditioners.transcript_in_segment.embed.weight"]; w != nil {
m.Embed = nn.NewEmbedding(w)
}
m.InputLinear = linear(tensors, "flow_lm.input_linear")
@@ -178,9 +200,12 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
if m.Embed == nil || m.InputLinear == nil || m.OutNorm == nil || m.EOS == nil || m.BOS == nil || m.EmbMean == nil || m.EmbStd == nil {
return fmt.Errorf("missing flow_lm weights")
}
- m.NumSpeakers = tensors["flow_lm.num_speakers"]
- if m.NumSpeakers == nil || !slices.Equal(m.NumSpeakers.Dims(), []int{1, 1, m.Embed.Weight.Dim(1)}) {
- return fmt.Errorf("missing or invalid num_speakers conditioning")
+ m.Conditions, err = gradiumConditions(tensors)
+ if err != nil {
+ return err
+ }
+ if m.Conditions == nil || !slices.Equal(m.Conditions.Dims(), []int{1, 1, m.Embed.Weight.Dim(1)}) {
+ return fmt.Errorf("missing or invalid speech conditioning")
}
m.BOS = mlx.Reshape(m.BOS, 1, 1, -1)
m.sample = mlx.Compile("phonon_sample", func(in ...*mlx.Array) []*mlx.Array {
@@ -198,6 +223,11 @@ func (m *Model) LoadWeights(tensors map[string]*mlx.Array) error {
if !ok {
continue
}
+ projection := tensors["flow_lm.condition_provider.conditioners.speaker_wavs.output_proj.weight"]
+ if projection == nil || t.NumDims() != 3 || t.Dim(0) != 1 || t.Dim(1) != projection.Dim(1) || t.Dim(2) == 0 {
+ return fmt.Errorf("voice %q has invalid raw speaker latents %v", voice, t.Dims())
+ }
+ t = nn.NewLinear(projection, nil).Forward(mlx.Transpose(t, 0, 2, 1)).AsType(mlx.DTypeBFloat16)
if voice == "" || t.NumDims() != 3 || t.Dim(0) != 1 || t.Dim(1) == 0 || t.Dim(2) != m.Embed.Weight.Dim(1) {
return fmt.Errorf("voice %q has shape %v", voice, t.Dims())
}
@@ -314,7 +344,7 @@ func (m *Model) speak(ctx context.Context, text string, voice *Voice, rng *rand.
noise[i] = float32(rng.NormFloat64() * std)
}
out := mlx.ScopedArrays(func() []*mlx.Array {
- input := mlx.Add(m.InputLinear.Forward(prev.AsType(mlx.DTypeBFloat16)), m.NumSpeakers)
+ input := mlx.Add(m.InputLinear.Forward(prev.AsType(mlx.DTypeBFloat16)), m.Conditions)
h := m.Flow.forward(input, offset+step, caches)
out := m.sample(h, mlx.FromValues(noise, 1, len(noise)))
prev.Set(out[0])
diff --git a/mlxrunner/model/phonon/model_test.go b/mlxrunner/model/phonon/model_test.go
index 9d42031b6..f85e72292 100644
--- a/mlxrunner/model/phonon/model_test.go
+++ b/mlxrunner/model/phonon/model_test.go
@@ -10,7 +10,7 @@ import (
)
func TestConfig(t *testing.T) {
- const checkpoint = `{"flow_lm":{"num_heads":12,"num_layers":6,"max_period":10000,"flow_depth":6},"mimi":{"sample_rate":24000,"frame_rate":12.5,"dilation_base":2,"transformer_num_heads":8,"transformer_num_layers":2,"transformer_context":250,"transformer_max_period":10000},"temp":0.8,"lsd_decode_steps":1,"eos_threshold":4.0}`
+ const checkpoint = `{"flow_lm":{"d_model":512,"num_heads":8,"num_layers":6,"max_period":10000,"flow_depth":6,"gelu":"erf","time_rms_norm":"rms"},"mimi":{"sample_rate":24000,"frame_rate":12.5,"dilation_base":2,"transformer_num_heads":8,"transformer_num_layers":2,"transformer_context":250,"transformer_max_period":10000,"gelu":"erf"},"conditioners":[{"type":"lut","name":"num_speakers","lut":{"possible_values":["0","1","2"]}},{"type":"continuous","name":"duration_delta","continuous":{"dim":128}}],"fuser":{"sum":["num_speakers","duration_delta"],"prepend":["transcript_in_segment","speaker_wavs"]},"temp":0.8,"lsd_decode_steps":1,"eos_threshold":4.0}`
var cfg config
if err := json.Unmarshal([]byte(checkpoint), &cfg); err != nil {
t.Fatal(err)
@@ -43,26 +43,13 @@ func TestConfig(t *testing.T) {
}
}
-func TestCheckpointDefaults(t *testing.T) {
- for _, tc := range []struct {
- json, gelu string
- temperature float32
- }{
- {`{}`, "tanh", .3},
- {`{"model_id":{"sig":"7e71a02d","epoch":200},"temp":0.8}`, "erf", .8},
- {`{"model_id":{"sig":"test","epoch":1},"flow_lm":{"gelu":"tanh"},"temp":0}`, "tanh", 0},
- {`{"flow_lm":{"gelu":"erf"}}`, "erf", .3},
- } {
- cfg := config{Temperature: .3}
- if err := json.Unmarshal([]byte(tc.json), &cfg); err != nil {
- t.Fatal(err)
- }
- if got := cfg.gelu(cfg.FlowLM.GELU); got != tc.gelu {
- t.Errorf("GELU = %q, want %q", got, tc.gelu)
- }
- if cfg.Temperature != tc.temperature {
- t.Errorf("temperature = %v, want %v", cfg.Temperature, tc.temperature)
- }
+func TestPrereleaseConfigRejected(t *testing.T) {
+ var cfg config
+ if err := json.Unmarshal([]byte(`{"flow_lm":{"num_heads":12,"num_layers":6,"max_period":10000,"flow_depth":6},"mimi":{"sample_rate":24000,"frame_rate":12.5}}`), &cfg); err != nil {
+ t.Fatal(err)
+ }
+ if cfg.validate() == nil {
+ t.Fatal("accepted prerelease Phonon configuration")
}
}
@@ -74,8 +61,6 @@ func TestTimeNorm(t *testing.T) {
norm string
denominator float64
}{
- {"", math.Sqrt(14.0/3 + 1e-5)},
- {"rms_var", math.Sqrt(14.0/3 + 1e-5)},
{"rms", math.Sqrt(12.5 + 1e-5)},
} {
out := timeNorm(x, alpha, tc.norm)