app icon indicating copy to clipboard operation
app copied to clipboard

macOS: embeddings always fail under the CoreML execution provider (rotary_emb/Mul_16)

Open arexyl opened this issue 1 month ago • 3 comments

Describe the bug

On macOS (Apple Silicon), every embedding call fails. Dynamic memory still extracts memories, but none of them get a vector, so retrieval always returns nothing and {{key_memories}} stays empty.

Every attempt logs:

Inference failed: Non-zero status code returned while running Mul node.
Name:'/backbone/encoder/layers.0/attn/rotary_emb/Mul_16'
Status Message: .../element_wise_ops.h:540 ... Attempting to broadcast an axis by a dimension other than 1. 2 by 64

All memory_embeddings rows end up with an empty embedding blob and embedding_dim = 0. In my logs there are thousands of failures and zero successful embeddings since install.

Root cause

create_runtime always registers the CoreML execution provider on macOS (MLProgram, CPUAndNeuralEngine, FastPrediction, static input shapes). Under that provider, ONNX Runtime 1.22.0 evaluates Gather(Shape(x), -1) inside the rotary embedding to 1 instead of the head dimension 64. rotate_half then splits the head dimension into [0:1] and [1:2], and Mul_16 fails.

Layer 0 tensors for an 8-token input:

tensor CPU EP CoreML EP
rotary_emb/Gather_15_output_0 (head dim) [64] [1]
rotary_emb/Slice_9_output_0 [1, 8, 12, 32] [1, 8, 12, 1]
rotary_emb/Concat_6_output_0 [1, 8, 12, 64] [1, 8, 12, 2]
rotary_emb/Reshape_3_output_0 [8, 1, 64] [8, 1, 64]

The model file is intact: its SHA-256 matches onnx/model.int8.onnx on Hugging Face. The same file runs correctly with the CPU provider only.

Both macOS builds are affected. ort is built with the coreml feature for every macOS target, and llama-gpu-metal does not change the embedding path.

To Reproduce

  1. Install the 2.2.5 desktop build for macOS arm64 and download the v4 embedding model.
  2. Enable dynamic memory for a character and chat until a memory cycle runs.
  3. See Inference failed in the log and empty embeddings in memory_embeddings.

Standalone reproduction with Python onnxruntime==1.22.0 and the downloaded v4-model.int8.onnx:

coreml = {
    "ModelFormat": "MLProgram",
    "MLComputeUnits": "CPUAndNeuralEngine",
    "SpecializationStrategy": "FastPrediction",
    "RequireStaticInputShapes": "1",
}
providers = [("CoreMLExecutionProvider", coreml), "CPUExecutionProvider"]
# Fails with the same Mul_16 error for any input.
# providers = ["CPUExecutionProvider"] succeeds.

Expected behavior

Embeddings are computed and stored, and retrieval returns relevant memories.

Verified workaround

Rewrite every Gather whose data input is a Shape output and whose index is negative to the equivalent positive index (rank - 1). The model has 24 such nodes, two per layer. The rewritten model runs under the exact CoreML options used by the app, and its output matches the original model on the CPU provider: cosine 1.000000 for inputs of 3, 14, 43, and 128 tokens.

Rewrite script (Python, onnx + numpy)
import sys

import numpy as np
import onnx
from onnx import numpy_helper, shape_inference

src_path, dst_path = sys.argv[1], sys.argv[2]
model = onnx.load(src_path)
inferred = shape_inference.infer_shapes(model)
ranks = {}
for vi in list(inferred.graph.value_info) + list(inferred.graph.input):
    if vi.type.tensor_type.HasField("shape"):
        ranks[vi.name] = len(vi.type.tensor_type.shape.dim)

graph = model.graph
producer = {out: node for node in graph.node for out in node.output}
inits = {i.name: i for i in graph.initializer}


def const_value(name):
    node = producer.get(name)
    if node is not None and node.op_type == "Constant":
        return numpy_helper.to_array(node.attribute[0].t)
    if name in inits:
        return numpy_helper.to_array(inits[name])
    return None


created = {}
for node in graph.node:
    if node.op_type != "Gather":
        continue
    shape_node = producer.get(node.input[0])
    if shape_node is None or shape_node.op_type != "Shape":
        continue
    index = const_value(node.input[1])
    if index is None or not np.any(index < 0):
        continue
    rank = ranks[shape_node.input[0]]
    fixed = np.where(index < 0, index + rank, index).astype(index.dtype)
    key = (fixed.tobytes(), fixed.shape, str(fixed.dtype))
    if key not in created:
        name = f"gather_fix_index_{len(created)}"
        graph.initializer.append(numpy_helper.from_array(fixed, name))
        created[key] = name
    node.input[1] = created[key]

onnx.checker.check_model(model)
onnx.save(model, dst_path)

After replacing the model, delete models/embedding/coreml-cache so CoreML compiles the new graph.

Possible fixes:

  1. Republish onnx/model.int8.onnx in Zeolit/lettuce-emb-768d-v4 with positive Gather indices. This keeps CoreML acceleration and needs no app change.
  2. In the app, rebuild the session on the CPU provider when a CoreML session fails at inference time. The app already falls back to CPU when CoreML registration fails, but not when inference fails.

Environment

  • LettuceAI 2.2.5 desktop, macos-arm64. The code path is unchanged on main at b9d1728.
  • macOS 27.2, Apple Silicon.
  • ONNX Runtime 1.22.0, the copy the app downloads at runtime.

arexyl avatar Oct 13 '26 09:10 arexyl

This issue is resolved in LettuceAl Next.

MegalithOfficial avatar Oct 13 '26 09:10 MegalithOfficial

Thanks for looking at this. I checked refactor/lettuceai-next at 5c7f6ef, and as far as I can tell the failure still applies there on macOS:

  • configure_execution_provider registers CoreML with the same options (MLProgram, CPUAndNeuralEngine, FastPrediction, static input shapes). It falls back to CPU only when registration fails, not when inference fails.

  • adopt_legacy_install keeps a device that never chose a model on v4. The published v4 onnx/model.int8.onnx is unchanged (SHA-256 dbeeaecd…ffce1b4), so migrated macOS users keep hitting the rotary_emb/Mul_16 error.

  • Eidos v5 (onnx/model_quantized.onnx, SHA-256 7a05962e…a5fb74) fails under the same CoreML options too, at a different node:

    Non-zero status code returned while running MatMulInteger node.
    Name:'/backbone/layers.0/mlp/Wo/MatMul_quant'
    Status Message: matmul_helper.h:61 Compute MatMul dimension mismatch
    

    I reproduced this with Python onnxruntime==1.22.0 and the provider options above, for inputs of 2, 7, 14, and 482 tokens. The CPU provider alone works.

The rewrite from the issue description fixes both models. Eidos has 12 Gather(Shape(x), negative index) nodes. After rewriting them to positive indices, the model runs under the Next CoreML options, and its embedding output matches the original model on the CPU provider with cosine 1.000000 for all four inputs.

Two ways to resolve it:

  1. Republish both ONNX files with positive Gather indices. CoreML acceleration stays, and no app change is needed.
  2. Rebuild the session on the CPU provider when a CoreML session fails at inference time.

Could you reopen this issue, or point me to what I missed if Next avoids this path some other way?

arexyl avatar Oct 13 '26 09:10 arexyl

I havent commited certain fixes. It would be better if you can join our discord server, there you can reach out to me faster.

MegalithOfficial avatar Oct 13 '26 09:10 MegalithOfficial