Migrates MAX models from V2 graph API (max.nn.legacy, TensorValue) to ModuleV3 (max.nn, Tensor, F.lazy() + compile()). Handles import rewrites, weight alignment, KV cache changes, and sharding porting.
Ships in max-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Input: the V2 model source to migrate ($ARGUMENTS).
ModuleV3 (max.nn) is the current MAX model API. A V2 model
builds an explicit Graph over TensorValue values with layers from
max.nn.legacy. A ModuleV3 model declares a forward() over Tensor values and
compiles with F.lazy() + compile(). Read
references/v2-v3-basics.md first. It covers
F.lazy(), compile(weights=...), dtype handling with auto_cast,
forward() vs __call__(), the distributed mapping, and the import
rules.
For architecture serving integration, read the
module registration compatibility reference.
Prefer supported ModuleV3 role registration without an architecture-specific
PipelineModel. The standalone compilation examples below explain the model
API; the registration runtime owns those steps for registered architectures.
Keep a custom pipeline for a documented unsupported task, backend or feature.
Draft/speculator module registration has not been added.
Classify by imports, and read the file when grep and the imports disagree.
V2 code imports its layers from max.nn.legacy and builds an explicit Graph
over TensorValue. ModuleV3 code imports max.nn and
subclasses its Module. Scoped greps shortcut the read:
grep -rn "max.experimental" <model-path>
grep -rEn "^\s*(from|import) max\.nn" <model-path>
Hits from the first mean the model is already (at least partly) V3 and
needs review, not migration. Hits from the second mean V2. Imports from
max.graph alone don't decide: V3 code keeps TensorType and
DeviceRef from max.graph for input specs. A file that hits both is
mixed. Read it before migrating anything.
Leave the V2 implementation untouched so it keeps working while the V3
variant is under construction. Put the V3 code alongside it: a
<name>_modulev3 directory when migrating a registered architecture, or a
new module file when the model lives in your own package. When migrating a
registered architecture, name the V3 variant with the _ModuleV3 suffix.
max serve --prefer-module-v3 selects it while the V2 name keeps serving
by default.
# REMOVE:
from max.graph import Graph, TensorValue, BufferValue, ops
from max.nn.legacy.layer import Module, LayerList
from max.nn.legacy.linear import Linear
from max.nn.legacy.norm.rms_norm import RMSNorm
# ADD:
from max import functional as F
from max.tensor import Tensor
from max.nn import Module
from max.nn.linear import Linear
from max.nn.norm import RMSNorm
from max.nn.sequential import ModuleList
# KEEP (TensorValue-free, shared with V2):
from max.nn.kv_cache import KVCacheParams, KVCacheParamInterface
from max.nn.attention_mask import MHAMaskVariant
TensorType and DeviceRef stay from max.graph. They define input
specs, not graph values.max.nn.legacy imports are fine when the imported class doesn't use
TensorValue.PagedCacheValues comes from
max.nn.common_layers.kv_cache for the V3 type. max.nn.legacy
exports a PagedCacheValues of its own, an alias for the V2 input type
without from_upstream(). Import from the max.experimental path to
get the V3 type.__call__() becomes forward().TensorValue and BufferValue become Tensor.Module takes the call signature:
class MyModel(Module[[Tensor, ...], tuple[Tensor, ...]]). Prefer
specific types, and use ... only when forward() has *args.dtype= and device=.
V3 uses default dtype and device contexts, and model.to(device) moves
the module to one device after construction.LayerList becomes ModuleList from max.nn.sequential.
ModuleList subclasses list, so it takes a single iterable:
ModuleList(layers). ModuleList(*layers) raises TypeError.Tensor objects. Create them with Tensor.zeros(),
max.functional.random.*, and similar factories.ops.* becomes F.* (ops.gather() → F.gather()). Most shape ops are
methods on Tensor: reshape(), transpose(), permute(), squeeze(),
unsqueeze(), split(), cast(). flatten() is the exception. It's
functional-only (F.flatten(tensor, start_dim)).
compile()V2:
nn_model = MyModel(config)
nn_model.load_state_dict(state_dict)
with Graph("my_model", input_types=input_types) as graph:
outputs = nn_model(*graph.inputs)
graph.output(*outputs)
model = session.load(graph, weights_registry=state_dict)
V3:
with F.lazy():
nn_model = MyModel(config)
nn_model.to(device)
model = nn_model.compile(*input_types, weights=state_dict)
F.lazy() wraps construction and records weight tensors symbolically.
The checkpoint passed to compile(weights=...) replaces them.KeyError and a mismatched one ValueError. An
entry that matches no parameter is left out without an error, so diff
the state-dict keys against parameters after migrating (step 7).auto_cast=True to permit safe dtype casts.model(tokens, ...)). Compiled outputs
are Tensor objects. Code that consumed Buffer outputs reads the
buffer via .driver_tensor.compile(weights=...) resolves names from the root compiled module's
attribute hierarchy. When migration introduces or renames wrapper
attributes, checkpoint key mappings must follow: a root module storing
self.language_model = ... needs every inner weight prefixed with
language_model.. After migrating, check that every state-dict key is a
valid attribute path from the root module.
Tied embeddings need explicit handling: conditionally create lm_head, and
multiply by embed_tokens.weight.T in forward() when
tie_word_embeddings is set. Keep one copy of the shared weight in the
state dict.
forward()The KV cache parameter types stay in max.nn.legacy. The values type has a V3
home in max.nn.common_layers.kv_cache. Use the methods on
kv_params plus PagedCacheValues.from_upstream():
def forward(self, tokens: Tensor, ..., *variadic_args: Tensor):
kv_inputs = iter(arg._graph_value for arg in variadic_args)
symbolic_inputs = self.kv_params.unflatten_kv_inputs(kv_inputs)
kv = PagedCacheValues.from_upstream(symbolic_inputs, tokens.mapping)
You need the ._graph_value extraction: variadic_args arrive as
Tensor objects while the unflatten methods expect raw graph values. For
sliding plus global attention, declare MultiKVCacheParams and use
unflatten_basic_kv_tree(), wrapping each tree with its own
PagedCacheValues.from_upstream().
V2 sharding sets a ShardingStrategy on each layer and calls
.shard(devices) to get a per-device module list. V3 puts a DeviceMesh on
the model and a placement mapping on each weight:
from max.nn.common_layers.linear import row_parallel
from max.tensor.sharding import DeviceMesh
model.mesh = DeviceMesh(devices, (n_devices,), ("tp",))
linear = row_parallel(Linear(in_dim, out_dim))
col_parallel() and row_parallel() set which mesh axis each weight
dimension shards over, and V3 has no per-device module list. The V2
distributed machinery maps onto V3 as follows:
Allreduce and Signals: the sharding solver reads the tensors'
placements and inserts the collective each op needs. For example, adding
a row-parallel output (a Partial sum) to a replicated residual
all-reduces it. Call
F.allreduce_sum(), F.reduce_scatter(), or F.allgather() where the
model controls the reduction. compile() adds the signal buffers the
collectives use as graph inputs and supplies them at run time..shard() and per-device lists: construct the model inside
default_device(mesh), and each weight is created on the mesh with the
placement it declares. Module.to() moves a module to one device only and
raises for a multi-device mesh. Per-device code runs through
F.functional(), or through t.local_shards and
Tensor.from_shard_values().EPBatchManager. Its
comm_buffers() returns the communication buffers as Tensor values,
and the MoE layer passes each device's shard to the dispatch calls as a
TensorValue. For registered ModuleV3 decoders, the shared runtime uses
DeploymentConfig / ExpertParallelDeploymentConfig to configure EP;
see the registration reference.
_init_distributed_runtime() is an existing custom-pipeline integration
pattern, not boilerplate to add to a registered architecture.gemma3_modulev3/ (TP) and deepseekV3_modulev3/ (TP, TP + EP, DP + EP)
show each pattern.
Run both implementations on the same inputs and compare greedy tokens
(and logits where convenient). Identical outputs confirm the migration.
Run mypy over the migrated module. V3 relies on the Module[[...], ...]
signatures, so type errors point to migration bugs.
The registered architectures ship as readable Python source in the
installed MAX package, under max/pipelines/architectures/. The V3
migrations to read:
olmo3/, gpt_oss_modulev3/, llama3_modulev3/kimik2_5_modulev3/, gemma3_modulev3/, deepseekV3_modulev3/nemotron_h_modulev3/gpt_oss/, llama3/Tensor equivalentEvery graph op and kernel is callable from V3: F.functional(fn) turns a
function over TensorValue into one over Tensor. The options, and the
wrapper pattern for bridging a per-device TensorValue helper into a
Tensor API, are in
references/v2-v3-basics.md.
The wrapper rules, which a reviewer enforces:
F.functional call. A body that calls
two ops hides its intermediate placements from the sharding rules, and one
unplaceable step silently turns the whole body into per-device code.TensorValue appears only in a wrapper's body. A helper that takes or
returns one for any other reason becomes a function of Tensors.F.call_on_mesh(fn, mesh, out_specs=...). For one raw graph op,
a rule-less F.functional(ops.x) is the shorthand; claim its Unknown
result with rebind_mapping(). An Unknown() operand needs a rule row
that names it.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
8 skills in this plugin
/benchmark-modelBenchmark a model served on MAX with the `max benchmark` command: measure throughput (tokens/sec), latency (TTFT, TPOT, inter-token latency), and GPU utilization by driving load against a running `max serve` endpoint. Use this whenever the user wants to benchmark, load-test, or measure the performance of a MAX model, get tokens-per-second / TTFT / TPOT numbers, run a concurrency or request-rate sweep, compare latency vs throughput, size a deployment, or produce benchmark JSON, even if they don't say "benchmark" by name. Also use when a `max benchmark` run fails to connect or reports zero/garbage numbers.
/debug-modelDebug a MAX model that loads, compiles, serves, and generates tokens but whose output disagrees with a reference implementation. Use whenever parity debugging stalls on scalar taps, the model returns gibberish or wrong greedy tokens, logit cosine is high but argmax differs, or generation is coherent then diverges. Applies during an architecture port, a quantization bring-up, a multi-GPU conversion, or after a MAX upgrade. Triggers on "parity failure", "silent corruption", "logits match but tokens diverge", "top-1 mismatch", "greedy divergence", and "model serves but generates garbage". Not for crashes on load or pre-serve scaffolding (use import-model). Mandates reference-vs-MAX tensor-dump comparators first, numerical verification of fixes before recompiling, and a serve-vs-pipeline bisect when dumps match but text diverges.
/eval-modelMeasures the task accuracy of text models served by MAX using standard benchmarks such as GSM8K, MMLU, HellaSwag, ARC, AIME, GPQA, TruthfulQA, WinoGrande, and BABILong. Use when benchmarking a served model, comparing it with model-card or reference scores, verifying that a new MAX model produces correct answers, or running repeatable dataset evaluations against a MAX OpenAI-compatible endpoint.
/import-modelUse when importing a new model architecture into MAX from a Hugging Face model ID. Triggers on: "import a model into MAX", "add model to MAX", "bring up <HF model> in MAX". Workflow: inspect the Hugging Face config and modeling code, then scaffold from a similar ModuleV3 architecture. Implement each layer as a max.nn Module that matches HF, serve, then verify against the Hugging Face reference. When the server runs but output is wrong (gibberish, greedy mismatch, coherent-then-diverges), load debug-model for the divergence hunt.
/new-modular-projectCreates a new Mojo or MAX project. Use when wanting to start a new Mojo or MAX project, initializing the `pixi` or `uv` environment to use Mojo or MAX, or when the user wants to begin a new Mojo or MAX project from scratch./profile-modelProfile a model running on MAX to find where it spends time and whether the GPU is saturated. Use when the user asks to "profile my model," "where is my model spending time," "why is inference slow," "is my GPU being utilized," "how much GPU am I using," "get a kernel breakdown," "capture an nsys/rocprof/ncu trace of max serve," or wants to measure MAX inference performance. Works for any model MAX can run — built-in architectures and custom ones loaded with --custom-architectures — from a pip or pixi install (max generate, max serve, or a Python script) on NVIDIA or AMD GPUs. Decide cheapest-first: a GPU utilization check, then a kernel breakdown, then a single-kernel deep dive only when one kernel dominates.
/max-skills:migrate-max-v2-to-v3from max-skills
npx claudepluginhub modular/skills --plugin max-skillsOther plugins' skills for the same job