Repository navigation
refactor: one folder per model family, with a registry keyed by model_type - #2507
Merged
Merged
Conversation
This was referenced Oct 30, 2026
Merged
Merged
Merged
Merged
Open
…_type Landing commit: this PR's change on top of main, with conflicts with the PRs landed before it resolved as in the tested integration build. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
AlexCheema
force-pushed
the
refactor/model-families
branch
from
November 1, 2026 15:49
1956a75 to
063b731
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Adding a model architecture to exo touches 8-12 files across the master, the worker and the
API, and exo recognises a model in four different ways:
isinstanceon mlx-lm classes(tensor-parallel dispatch, pipeline fixups, output parsers), model-id substrings (EOS ids,
prompt encoders, the Kimi tokenizer),
base_modelprefixes on the card (placement), and awhitelist of Hugging Face
architectures(supports_tensorfor custom cards). Two model PRsalmost always conflict in
auto_parallel.py,utils_mlx.pyandplacement.py.This PR moves every model-specific piece into a folder per model family and replaces those
switches with a registry keyed by the
model_typein the checkpoint'sconfig.json. Itchanges no behaviour: the same strategy, fixups, parsers, encoders, EOS ids and placement
rules apply to every model as before, the logs are the same, and greedy outputs and
log-probabilities are bit-identical on real hardware.
After it, a model PR is a family folder, its cards and a typing stub.
Layout
Families:
deepseek_v3(V3, V3.1, V3.2),deepseek_v4,glm(GLM-4.5/4.7, 4.7-Flash, GLM-5/5.1),kimi,qwen3(Qwen3, Qwen3-Next, Qwen3-VL, Qwen3.5/3.6),nemotron_h,minimax,gpt_oss,gemma(Gemma 4),step(Step 3.5),llama(Llama 3.x, Llama-based Nemotron, Ministral 3).How the switches map
tensor_auto_parallel:isinstancechain over 19 mlx-lm classesregistry.architecture_for_model(model).tensor_parallel. Lookup walks the model class's MRO, so a subclass of a registered class is handled like it, asisinstancedidpipeline_auto_parallel: fourisinstance(inner_model, ...)fixupsfix_pipeline_shard, the old block verbatim (guard included), called for the model's architecture_set_layers:isinstancelists fornum_layers/num_hidden_layersArchitecture.pipeline_layer_countapply_all_parsers:issubclasson GptOss / DeepseekV32 / DeepseekV4 plus id checksArchitecture.output_parser(parser, whether the thinking parser runs first, which ids it applies to)render_chat_template:"deepseek-v3.2"/"deepseek-v4"/"gpt-oss"substringsPromptEncoder/TemplateMessagesHookload_tokenizer_for_model_id:"kimi-k2"substring and the TikToken loaderTokenizerLoaderget_eos_token_ids_for_model: substring chainEosRulesplacement.py:base_model.startswith("DeepSeek V4"),"Gemma 4", model idDeepSeek-V3.1-8bitPlacementRules, looked up by the card'smodel_typeConfigData.supports_tensor: list of HF architecturestensor_parallel_architecturesvision.py: Kimi mlx-vlm module aliasesvendor/deepseek_v4_encoding.py,vendor/dsml_encoding.pydeepseek_v4/encoding.py,deepseek_v3/dsml_encoding.py, with provenance headersload_modelnow getsget_model_classes=registry.get_model_classes: a family can ship its ownmodel classes (
ModelClasses, from itsmodel.py) for amodel_type; otherwise mlx-lm's_get_classesis used, as before. No family uses it yet.Rules that match on the model id (EOS ids, prompt encoders, the Kimi tokenizer) keep their
exact substrings, now inside the family, and families are tried in an order that keeps the
old precedence. Keying them on
model_typeinstead would change behaviour for some ids (forexample
deepseek-v4also matchesdeepseek-v4.1ids today, and a custom Gemma 3 or GLM-4card gets its EOS ids from the substring), so that is left to the model PRs that need it.
Provenance of the vendored encoders
deepseek_v4/encoding.py: DeepSeek's referenceencoding/encoding_dsv4.pyfrom thedeepseek-ai/DeepSeek-V4-FlashHugging Face repository, revisiona7aaed80(2026-04-24;the file is unchanged through the current revision and identical in DeepSeek-V4-Pro), MIT
licence (notice now included), vendored 2026-04-27 in Add DeepSeek V4 Flash/Pro #1978. Local changes are
formatting and lint fixes only, listed in the header.
deepseek_v3/dsml_encoding.py: exo's own code (first added in Add thinking in thinking blocks, and fix DeepSeek interleaved tool calls #1548), which importsmlx-lm's DeepSeek V3.2 encoder rather than copying it. The header now says so.
Small things that move with the code
model_typeis a new optional card field (Nonefor custom cards, which keep savingwithout it). Custom cards fetched from Hugging Face never had a
base_modeleither, sothey get no family placement rules, as before.
bench/exo_bench.pyimported the V4 encoder from a path that no longer existed (it raisedImportErrorwhen sizing prompts for DeepSeek V4); it now imports it from its new home.scripts/fetch_kv_heads.pynow finds cards in subfolders.Still shared
DeepseekV4Cacheremains in the cache type unions of the prefix cache and thedisaggregated adapter (
types.py,cache.py,disaggregated/adapter.py); its copy logic moved todeepseek_v4/cache.py. A family witha new cache class adds its copier in its folder and the type to those unions.
vision.pystill recognises Kimi-VL's mlx-vlm processor;generate.pyhandles Gemma 4'sper-layer embeddings by attribute. Neither dispatches on the model.
Commits
sharding: shared TP/PP building blocks out ofauto_parallel.py.cards: optionalmodel_typefield.folder with
model_type(llama, deepseek_v3, deepseek_v4, glm, kimi, minimax, qwen3,gpt_oss, nemotron_h, step, gemma). Call sites keep their switches and call the moved code.
spec.pyper family andspec_registry.py; placement,supports_tensor, EOS ids and vision aliases switch to it.family.pyper family andregistry.py; TP/PP dispatch, outputparsers, prompt encoders, the tokenizer loader and
get_model_classesswitch to it.Adding a model
A new checkpoint of a supported architecture is a card in
resources/inference_model_cards/<family>/withmodel_typeset. If its tokenizer configdoesn't list all of its EOS tokens, add an
EosRuleto the family'sspec.py.A new architecture or family is a folder,
src/exo/worker/engines/mlx/models/<family>/:__init__.pywith a docstring only.spec.py, no MLX imports:SPEC = FamilySpec(name=..., model_types=..., tensor_parallel_architectures=..., placement=PlacementRules(...), eos_rules=...).sharding.py: aTensorParallelShardingStrategysubclass built fromengines/mlx/sharding/,and
fix_pipeline_shardif the model needs adjusting once its layers are split.family.py:FAMILY = ModelFamily(spec=SPEC, architectures=(Architecture(model_type=..., model_class=..., tensor_parallel=..., fix_pipeline_shard=..., pipeline_layer_count=..., output_parser=...),), ...),plus a prompt encoder, chat-template hook or tokenizer loader if the model needs one.
prompt.py,parser.py,tokenizer.py,cache.py, andmodel.pywithModelClassesfor a model definition exo's mlx-lm doesn't have.SPECinspec_registry.FAMILY_SPECSandFAMILYinregistry.FAMILIES, at thesame position; add the cards and a
.typings/mlx_lm/models/<model_type>.pyistub.Copied code (a model definition, a reference encoder) starts with a provenance header:
source URL, revision, licence (with its notice where required), date and local changes.
The registry tests check that every card belongs to a family, that
model_types and classesline up, and that the master side imports without MLX. Put the family's own tests
(sharding equivalence, parser and encoder goldens) next to its code.
The same guide is in CONTRIBUTING.md.
Test Plan
Automated Testing
New tests copy the replaced code verbatim as the oracle and compare the registry against it:
models/tests/test_registry.py: for every model module in exo's mlx-lm (108), thetensor-parallel strategy, the pipeline layer counter and the output parser (for every
built-in card id and for ids built to hit two families' rules) equal what the old
isinstancechains picked; each pipeline fixup is attached to every model type that canbuild its inner model class; the model-id hooks (prompt encoders, template hook, Kimi
tokenizer) pick as before;
get_model_classesfalls back to mlx-lm's classes and returns afamily's own classes when it has some.
models/tests/test_spec_registry.py: for all 123 built-in cards, the placement rules equalthe old
base_model/model-id checks and each card sits in its family's folder;supports_tensorequals the old whitelist; EOS ids equal the old substring chain for everycard id and for ids mixing two families' substrings; the master side imports with MLX
blocked.
master/tests/test_placement_family_rules.py: placement end to end on the built-inDeepSeek V4, DeepSeek V3.1 and Gemma 4 cards.
Dropping one registry entry, one fixup, or swapping two families' order makes these tests
fail.
basedpyright (0 errors), ruff,
nix fmt(no changes) and pytest pass.Manual Testing
Hardware: two Mac minis (M4 Pro, 64 GB), MLX ring backend.
For each model, both trees loaded the checkpoint with their own
shard_and_load(which runsload_model, the tokenizer loader, andtensor_auto_parallelorpipeline_auto_parallel),rendered two chat prompts with
apply_chat_template, and greedy-decoded 48 tokens per prompton both ranks, recording token ids and the float32 top-5 log-probabilities at every step.
Identical means: the same prompt text and token ids, the same generated tokens and top-5 ids,
log-probability differences of exactly 0, the same EOS ids, and the same log messages (with
timestamps, source line numbers and timings removed).
Not caused by this PR, seen on both trees: with tensor parallelism, NVIDIA-Nemotron-Nano-9B-v2-4bits
generates " A A A ..." from the first token (pipeline parallelism on the same machines is
fine). Worth a look in the Nemotron model PR.
🤖 Generated with Claude Code