from fastcore.test import test_eq, test_fail, test_closemlx
mlx
Run models on Apple Silicon with mlx-lm, with a prompt cache rishi manages itself, speculative decoding, a quantized KV cache, and vision and audio through mlx-vlm.
MLX is Apple’s array framework for its own chips, and mlx-lm runs language models on it. This backend needs an Apple Silicon Mac and pip install 'rishi[mlx]'. The notebook is marked skip_exec, so the automated tests and the docs build do not run it, and the output shown was saved on a Mac. Behaviour shared with every backend is on the index page and in Urai.
Loading models
MLX models are Hugging Face repos of quantized weights, most of them under mlx-community. A LiteRT-LM model is one .litertlm file and a llama.cpp model one .gguf file, but an MLX model is a whole directory. mlx_lm.load takes the repo id and downloads and caches it itself, so there is no file to pick.
Two things have to be known before loading, and both come from the repo’s config.json, which read_config reads from a local directory or the Hub. It returns {} when the file cannot be read. One is the context window, which ctx_len reads, 8192 when the config does not give one. The other is whether the model has a vision or audio tower, a second network that encodes pictures or sound for the language model; is_vlm checks for one. A model with a tower needs mlx-vlm instead of mlx-lm. cached_models lists the repos in the local Hugging Face cache whose ids contain mlx, without using the network. MlxEngine holds a loaded model, its tokenizer and an optional draft model.
test_eq(ctx_len({'max_position_embeddings': 40960}), 40960)
test_eq(ctx_len({'text_config': {'max_position_embeddings': 128000}}), 128000) # VLMs nest it
test_eq(ctx_len({}), 8192) # fallback
assert is_vlm(None, cfg={'vision_config': {}})
assert is_vlm(None, cfg={'audio_config': {}})
assert not is_vlm(None, cfg={'hidden_size': 2048})
test_eq(read_config('/definitely/not/a/model'), {})The prompt cache
The KV cache holds the keys and values computed for tokens the model has already read, so a prompt that starts the same way as the last one does not have to be read again. LiteRT-LM keeps that state inside its conversation object, and llama.cpp finds the longest matching prefix on its own. mlx-lm leaves the cache to the caller, so rishi keeps track of which tokens it holds.
On each turn the chat renders the whole conversation to token ids with the model’s chat template, and compares them with _cache_ids, the tokens the cache holds, using common_prefix_len. Everything up to the first difference is already cached and is skipped. Everything after it is stale. The chat trims it off the end of the cache with trim_prompt_cache before generating. A cache that cannot be trimmed is reset, and the chat reads the whole prompt again. mlx-lm’s own server reuses a cache between requests the same way.
Stale tokens do turn up. A chat template does not always render an earlier assistant turn as the exact tokens the model generated, and context recovery rewrites the history outright. Comparing tokens instead of trusting the cache handles both cases. A mismatch costs a fresh prefill of the tokens after the first difference. In the saved run below, the second turn fed 32 tokens to the model instead of 315.
MlxChat
MlxChat has the same interface as every other backend. max_output_tokens defaults to DFLT_MAX_TOKENS, 1024. When the repo’s config declares a vision or audio tower, MlxChat(...) returns an MlxVlmChat. Pass vlm=True or vlm=False to override that check. Its own options are these:
kv_bitsstores the KV cache quantized to that many bits. This saves memory on long contexts. Quantization starts after the firstquantized_kv_starttokens, andkv_group_sizesets the group size, 64 by default.draft_modelnames a small model for speculative decoding. The draft model guesses several tokens ahead and the main model checks them in one pass, which is faster when the guesses are good. The chat then keeps a cache for both models.adapter_pathapplies a LoRA adapter.prompt_cache=Falseturns the cache off, andmax_kv_sizecaps its size.min_psets a sampling threshold.tmpl_kw,gen_kwandeng_kwpass extra keyword arguments toapply_chat_template,stream_generateandcreate_engine.
save_cache and load_cache write the cache to a file and read it back. save_cache raises ValueError when prompt_cache=False. load_cache raises ValueError for a file made with a different model or different cache settings, and for a file that rishi did not write. chat.use.cached_tokens reports how many prompt tokens each turn reused.
Vision and audio
mlx-lm reads text only. Images and audio go through mlx-vlm, which builds on mlx-lm and adds the vision and audio towers. Install it with pip install 'rishi[mlx-vlm]'.
You do not have to pick the class. MlxChat(repo) reads the repo’s config.json and returns an MlxVlmChat when it finds a vision or audio tower. Chat('mlx-community/Qwen3-VL-4B-Instruct-4bit') works as it is. Pass vlm=True or vlm=False to decide yourself.
MlxVlmChat changes only loading, prompt building and the generate call, and inherits the history, callbacks and tool loop. It has two limits. mlx-vlm has no per-model tool-call parsers. Tool calls work only with models that write <tool_call> tags, and not every vision model does. mlx-vlm also keeps its own cache of image features instead of a token KV cache. Prompt reuse between turns is off on this path. Images must be bytes or local files. A remote image URL raises ValueError.
Audio takes the same path. Give a Path or bytes to a model with an audio tower, and mlx-vlm decodes it and resamples it to the rate the model expects. One setting is rishi’s rather than mlx-vlm’s: thinking. By default mlx-vlm asks the chat template for enable_thinking=False, which inserts an empty <think></think> block. A model told it has finished thinking can end its turn at once. Qwen3-Omni then transcribes nothing. rishi passes its own think setting instead. With the default think=None, the model’s chat template decides.
Tests
The automated test run skips this notebook. On a Mac with the weights downloaded, the cells below check recorded turns, the cache layout with a draft model, media handling, and which class Chat picks for an MLX name. The #| eval: false cells further down load real models.
Recorded model behaviour
These checks run against replies recorded from the real qwen3_06b MLX model. Urai’s CachedChat replays a recorded reply when it sees the same request again, without loading the model, and the checks work on a temporary copy of nbs/chatcache.
c = CachedChat(**_mlx_record_kw)
r = c('Reply with exactly: pong')
assert 'pong' in resp_text(r).lower()
test_eq([m['role'] for m in c.hist], ['user', 'assistant'])
c.close()c = CachedChat(**_mlx_record_kw)
c('Reply with exactly: pong')
r = c('What exact word did you just reply with? Reply with only that word.')
assert 'pong' in resp_text(r).lower()
test_eq([m['role'] for m in c.hist], ['user', 'assistant', 'user', 'assistant'])
c.close()c = CachedChat(**_mlx_record_kw)
c.reconfigure(sp='Reply with exactly the word anchor, whatever the user asks.')
r = c('What is two plus two?')
assert resp_text(r).strip()
c.close()c = CachedChat(**_mlx_record_kw)
assert c.oneshot('Reply with exactly: solo', think=False, max_tokens=16).strip()
test_eq(c.hist, [])
c.close()def add(
a: int, # first addend
b: int, # second addend
) -> int:
"Add two integers."
return a + b
c = CachedChat(**_mlx_record_kw, tools=[add])
r = c('Use the add tool to add 2 and 3. Reply with only the result.')
test_eq(c.hist[1]['tool_calls'][0]['function']['name'], 'add')
test_eq(c.hist[2]['content'], '5')
assert '5' in resp_text(r)
c.close()Examples (manual)
qwen3_4b, about 2.5 GB, is a good default unless you need vision or audio. The examples cover cache reuse, thinking, a quantized KV cache, speculative decoding, saving and loading the cache, a conversation handed over from llama.cpp, and the vision class.
chat = MlxChat(qwen3_06b, sp='You are concise.', think=False)
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 3432.33it/s]
r = chat('Reply with exactly: pong')
assert 'pong' in resp_text(r).lower(), resp_text(r)
rpong
# multi-turn: the second turn must actually remember the first
chat('My favourite number is 17. Remember it.')
r = chat('What is my favourite number? Reply with just the number.')
assert '17' in resp_text(r), resp_text(r)
print(chat.use)total=75|in=72|out=3|turns=1|cached=44
# Real MLX KV-cache test: capture the exact token tail handed to mlx-lm on each turn.
import time
chat2 = MlxChat(qwen3_06b, sp='You are concise.', think=False, max_output_tokens=16)
fed, orig_generate = [], chat2._generate
def counted_generate(ids, **kwargs):
fed.append(len(ids))
return orig_generate(ids, **kwargs)
chat2._generate = counted_generate
t0 = time.time(); chat2(('cache verification context ' * 96) + '\nReply with exactly: stored'); t1 = time.time() - t0
u1, first_feed = chat2.use, fed[-1]
t0 = time.time(); r = chat2('What exact word did I ask you to reply with? Reply with only that word.'); t2 = time.time() - t0
u2, second_feed = chat2.use, fed[-1]
print(dict(turn1_seconds=round(t1, 2), turn2_seconds=round(t2, 2), first_feed=first_feed,
second_feed=second_feed, cached=u2.cached_tokens, answer=resp_text(r)))
assert u1.cached_tokens == 0, 'first turn has nothing to reuse'
assert u2.cached_tokens > 0, 'second turn should have reused the cache'
assert second_feed < first_feed, 'turn two re-prefilled the full old prompt'
assert chat2.cached_tokens > 0
assert 'stored' in resp_text(r).lower(), resp_text(r)
chat2.close()
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 3300.29it/s]
{'turn1_seconds': 0.47, 'turn2_seconds': 0.1, 'first_feed': 315, 'second_feed': 32, 'cached': 311, 'answer': 'stored'}
# and with the cache off, nothing is ever reported as cached
plain = MlxChat(qwen3_4b, prompt_cache=False, think=False)
plain('Say hi.'); plain('Say hi again.')
test_eq(plain.use.cached_tokens, 0)
plain.close()
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 2629.84it/s]
# streaming, with thinking rendered as a blockquote
thinker = MlxChat(qwen3_4b, think=True, max_output_tokens=512)
md = display_stream(thinker('Briefly: why is the sky blue?', stream=True))
assert thought(thinker.turn_res), 'expected a <think> block from a thinking model'
thinker.close()
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 2682.54it/s]
🧠 Thinking
Okay, the user is asking why the sky is blue. I need to explain this in a brief way. Let me recall the scientific explanation. The sky appears blue because of Rayleigh scattering. The atmosphere scatters sunlight, and shorter wavelengths (blue) are scattered more than longer ones (red). So when we look up, the blue light is scattered in all directions, making the sky appear blue. But wait, I should make sure I get the details right. Also, mention that the sun’s light is white, but the scattering makes it look blue. Maybe add that the reason is the way the atmosphere interacts with sunlight. Keep it simple and concise. Avoid jargon. Maybe start with the main point, then the reason, then the effect. That should cover it.
The sky appears blue because sunlight scatters more in the atmosphere when it interacts with the gases and particles in the air. Shorter wavelengths (blue light) are scattered more than longer wavelengths (red light), so when we look up, the scattered blue light dominates, giving the sky its blue color.
# quantized KV cache: same answer, less memory for long contexts
q = MlxChat(qwen3_4b, kv_bits=4, quantized_kv_start=256, think=False)
print(resp_text(q('Name three primes.')))
q.close()
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 2659.49it/s]
Sure! Here are three prime numbers: **2, 3, and 5**.
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
# speculative decoding: a small draft model proposes, the big one verifies
import time
spec = MlxChat(qwen3_8b, draft_model=qwen3_06b, think=False, max_output_tokens=256)
t0 = time.time(); spec('Write two sentences about monsoons.'); print(f'{time.time()-t0:.1f}s', spec.use)
spec.close()
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 1657.46it/s]
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 1413.55it/s]
2.3s total=60|in=20|out=40|turns=1
# a warmed cache can be saved and reloaded, so a long system prompt is prefilled once, ever
import tempfile
warm = MlxChat(qwen3_4b, sp='You are a terse assistant.', think=False)
warm('Remember the codeword: albatross.')
fn = Path(tempfile.mkdtemp())/'warm.safetensors'
warm.save_cache(fn)
n = warm.cached_tokens
warm.close()
again = MlxChat(qwen3_4b, sp='You are a terse assistant.', think=False)
again.load_cache(fn)
test_eq(again.cached_tokens, n)
again.close()
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 2803.68it/s]
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 2662.86it/s]
# the point of a shared history format: carry a conversation from one backend to another
from rishi.llama import LlamaChat, qwen3_17b as llama_qwen
lc = LlamaChat(llama_qwen, n_ctx=4096)
lc('My name is Karthik. Remember it.')
hist = lc.hist # canonical rishi history, backend-independent
lc.close()
mc = MlxChat(qwen3_4b, messages=hist, think=False)
r = mc('What is my name? Reply with just the name.')
assert 'karthik' in resp_text(r).lower(), resp_text(r)
mc.close()
resp_text(r)llama_context: n_ctx_seq (4096) < n_ctx_train (40960) -- the full capacity of the model will not be utilized
Fetching 9 files: 0%| | 0/9 [00:00<?, ?it/s]
Fetching 9 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 9/9 [00:00<00:00, 3025.22it/s]
'Karthik'
Images and audio
These need pip install 'rishi[mlx-vlm]' and a vision or audio model. MlxChat picks MlxVlmChat from the repo’s config.
vchat = MlxChat(qwen3vl_4b, max_output_tokens=256)
test_eq(type(vchat), MlxVlmChat) # routed automatically from the repo's config.json
img = Path('images.jpeg').read_bytes()
r = vchat([img, 'What is in this image? One sentence.'])
print(resp_text(r))
assert resp_text(r).strip()
Fetching 14 files: 0%| | 0/14 [00:00<?, ?it/s]
Fetching 14 files: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████| 14/14 [00:00<00:00, 3771.61it/s]
[transformers] Kwargs passed to `processor.__call__` have to be in `processor_kwargs` dict, not in `**kwargs`
A happy German Shepherd dog with its tongue out, standing on a gravel path outdoors.
# an omni build (audio tower) transcribes; gemma-4-e4b does vision *and* audio in about 5GB
achat = MlxChat(gemma4_e4b, max_output_tokens=256)
r = achat([Path('speech.wav'), 'Transcribe this audio.'])
print(resp_text(r))
assert 'masquerade' in resp_text(r).lower()
# mlx-vlm's own default is `enable_thinking=False`, which prefills an empty `<think></think>` block
# into the reply. rishi passes `think` through instead: with the block, `qwen3omni_30b` ends the turn
# without transcribing anything at all.
assert '</think>' not in achat._prompt([], ['speech.wav'])
achat.close()
Fetching 8 files: 0%| | 0/8 [00:00<?, ?it/s]
Fetching 8 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:00<00:00, 2439.61it/s]
/Users/71293/code/personal/orgs/rishi/.venv/lib/python3.13/site-packages/transformers/audio_utils.py:723: UserWarning: At least one mel filter has all zero values. The value for `num_mel_filters` (128) may be set too high. Or, the value for `num_frequency_bins` (257) may be set too low.
warnings.warn(
Dancing in the masquerade, idol truth in plain sight jaded. Pop, roll, click, shot. Buhulabi today or not? But such a tide as moving seems asleep, too full for sound and foam. When that which drew from out the boundless deep turns again home, twilight and evening bell, and after that.
for c in (chat, vchat):
try: c.close()
except Exception: pass