Skip to content

refactor: one folder per model family, with a registry keyed by model_type - #2507

Merged
AlexCheema merged 1 commit into
mainfrom
refactor/model-families
Nov 1, 2026
Merged

AlexCheema merged 1 commit into
mainfrom
refactor/model-families

Conversation

@AlexCheema

Copy link
Copy Markdown
Contributor

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: isinstance on mlx-lm classes
(tensor-parallel dispatch, pipeline fixups, output parsers), model-id substrings (EOS ids,
prompt encoders, the Kimi tokenizer), base_model prefixes on the card (placement), and a
whitelist of Hugging Face architectures (supports_tensor for custom cards). Two model PRs
almost always conflict in auto_parallel.py, utils_mlx.py and placement.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_type in the checkpoint's config.json. It
changes 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

src/exo/worker/engines/mlx/
  sharding/                 shared TP/PP building blocks; names no model
    blocks.py               LayerCallable, CustomMlxLayer, ShardedMoE
    pipeline.py             PipelineFirstLayer/LastLayer, queued prefill sends, get_inner_model,
                            patch_pipeline_model, the hybrid-cache make_mask helper,
                            the PipelineShardFixup protocol
    tensor.py               TensorParallelShardingStrategy, patch_tensor_model
  auto_parallel.py          tensor_auto_parallel / pipeline_auto_parallel (same names and
                            signatures), now asking the registry instead of isinstance chains
  cache_copy.py             leak-free array and rotating-cache copies (moved out of cache.py)
  models/
    spec.py                 FamilySpec, PlacementRules, EosRule (pure Python)
    spec_registry.py        master side: families by model_type, importable without MLX
    family.py               ModelFamily, Architecture, OutputParser, PromptEncoder,
                            TemplateMessagesHook, TokenizerLoader, ModelClasses
    registry.py             worker side: architecture lookup, get_model_classes hook,
                            prompt encoders, tokenizer loaders
    <family>/
      __init__.py           docstring only (MLX-free, so the master can import spec.py)
      spec.py               model_types, tensor-parallel HF architectures, placement rules,
                            EOS rules (no MLX)
      family.py             FAMILY: architectures (mlx-lm class -> strategy, pipeline fixup,
                            layer counter, output parser) and model-id hooks
      sharding.py           the family's TensorParallelShardingStrategy and fix_pipeline_shard
      prompt.py, parser.py, tokenizer.py, cache.py, encoding.py   when the family needs them
      model.py              room for a model definition exo's mlx-lm lacks (none yet)
    tests/                  registry equivalence tests
resources/inference_model_cards/<family>/*.toml    each card gains `model_type`

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

before after
tensor_auto_parallel: isinstance chain over 19 mlx-lm classes registry.architecture_for_model(model).tensor_parallel. Lookup walks the model class's MRO, so a subclass of a registered class is handled like it, as isinstance did
pipeline_auto_parallel: four isinstance(inner_model, ...) fixups each family's fix_pipeline_shard, the old block verbatim (guard included), called for the model's architecture
_set_layers: isinstance lists for num_layers / num_hidden_layers Architecture.pipeline_layer_count
apply_all_parsers: issubclass on GptOss / DeepseekV32 / DeepseekV4 plus id checks Architecture.output_parser (parser, whether the thinking parser runs first, which ids it applies to)
render_chat_template: "deepseek-v3.2" / "deepseek-v4" / "gpt-oss" substrings the families' PromptEncoder / TemplateMessagesHook
load_tokenizer_for_model_id: "kimi-k2" substring and the TikToken loader the kimi family's TokenizerLoader
get_eos_token_ids_for_model: substring chain the families' EosRules
placement.py: base_model.startswith("DeepSeek V4"), "Gemma 4", model id DeepSeek-V3.1-8bit PlacementRules, looked up by the card's model_type
ConfigData.supports_tensor: list of HF architectures union of the families' tensor_parallel_architectures
vision.py: Kimi mlx-vlm module aliases the kimi spec
vendor/deepseek_v4_encoding.py, vendor/dsml_encoding.py deepseek_v4/encoding.py, deepseek_v3/dsml_encoding.py, with provenance headers

load_model now gets get_model_classes=registry.get_model_classes: a family can ship its own
model classes (ModelClasses, from its model.py) for a model_type; otherwise mlx-lm's
_get_classes is 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_type instead would change behaviour for some ids (for
example deepseek-v4 also matches deepseek-v4.1 ids today, and a custom Gemma 3 or GLM-4
card 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 reference encoding/encoding_dsv4.py from the
    deepseek-ai/DeepSeek-V4-Flash Hugging Face repository, revision a7aaed80 (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 imports
    mlx-lm's DeepSeek V3.2 encoder rather than copying it. The header now says so.

Small things that move with the code

  • model_type is a new optional card field (None for custom cards, which keep saving
    without it). Custom cards fetched from Hugging Face never had a base_model either, so
    they get no family placement rules, as before.
  • bench/exo_bench.py imported the V4 encoder from a path that no longer existed (it raised
    ImportError when sizing prompts for DeepSeek V4); it now imports it from its new home.
  • scripts/fetch_kv_heads.py now finds cards in subfolders.

Still shared

  • DeepseekV4Cache remains in the cache type unions of the prefix cache and the
    disaggregated adapter (types.py, cache.py, disaggregated/adapter.py); its copy logic moved to deepseek_v4/cache.py. A family with
    a new cache class adds its copier in its folder and the type to those unions.
  • vision.py still recognises Kimi-VL's mlx-vlm processor; generate.py handles Gemma 4's
    per-layer embeddings by attribute. Neither dispatches on the model.

Commits

  1. sharding: shared TP/PP building blocks out of auto_parallel.py.
  2. cards: optional model_type field.
  3. One commit per family: code moved verbatim into its folder, its cards moved into its card
    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.
  4. Registry, master side: spec.py per family and spec_registry.py; placement,
    supports_tensor, EOS ids and vision aliases switch to it.
  5. Registry, worker side: family.py per family and registry.py; TP/PP dispatch, output
    parsers, prompt encoders, the tokenizer loader and get_model_classes switch to it.
  6. Docs: "Adding a Model" in CONTRIBUTING.md.

Adding a model

A new checkpoint of a supported architecture is a card in
resources/inference_model_cards/<family>/ with model_type set. If its tokenizer config
doesn't list all of its EOS tokens, add an EosRule to the family's spec.py.

A new architecture or family is a folder, src/exo/worker/engines/mlx/models/<family>/:

  1. __init__.py with a docstring only.
  2. spec.py, no MLX imports: SPEC = FamilySpec(name=..., model_types=..., tensor_parallel_architectures=..., placement=PlacementRules(...), eos_rules=...).
  3. sharding.py: a TensorParallelShardingStrategy subclass built from engines/mlx/sharding/,
    and fix_pipeline_shard if the model needs adjusting once its layers are split.
  4. 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.
  5. Optional: prompt.py, parser.py, tokenizer.py, cache.py, and model.py with
    ModelClasses for a model definition exo's mlx-lm doesn't have.
  6. Register SPEC in spec_registry.FAMILY_SPECS and FAMILY in registry.FAMILIES, at the
    same position; add the cards and a .typings/mlx_lm/models/<model_type>.pyi stub.

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 classes
line 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), the
    tensor-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
    isinstance chains picked; each pipeline fixup is attached to every model type that can
    build its inner model class; the model-id hooks (prompt encoders, template hook, Kimi
    tokenizer) pick as before; get_model_classes falls back to mlx-lm's classes and returns a
    family's own classes when it has some.
  • models/tests/test_spec_registry.py: for all 123 built-in cards, the placement rules equal
    the old base_model/model-id checks and each card sits in its family's folder;
    supports_tensor equals the old whitelist; EOS ids equal the old substring chain for every
    card 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-in
    DeepSeek 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 runs
load_model, the tokenizer loader, and tensor_auto_parallel or pipeline_auto_parallel),
rendered two chat prompts with apply_chat_template, and greedy-decoded 48 tokens per prompt
on both ranks, recording token ids and the float32 top-5 log-probabilities at every step.

family model tensor parallel (2 nodes) pipeline parallel (2 nodes)
llama Llama-3.2-1B-Instruct-4bit identical identical
qwen3 (dense) Qwen3-8B-4bit identical identical
qwen3 (Qwen3.5 hybrid) Qwen3.5-2B-MLX-8bit identical identical
nemotron_h NVIDIA-Nemotron-Nano-9B-v2-4bits identical (see below) identical
gpt_oss gpt-oss-20b-MXFP4-Q8 identical identical
glm (GLM-4.7-Flash, MLA) GLM-4.7-Flash-4bit identical identical
deepseek_v3 (MLA + MoE) Moonlight-16B-A3B-Instruct-4-bit identical identical
gemma gemma-4-e4b-it-4bit identical not placeable (Gemma 4 has no multi-node pipeline)

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

…_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
AlexCheema force-pushed the refactor/model-families branch from 1956a75 to 063b731 Compare November 1, 2026 15:49
@AlexCheema
AlexCheema merged commit e506e85 into main Nov 1, 2026
6 checks passed
@AlexCheema
AlexCheema deleted the refactor/model-families branch November 1, 2026 15:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant