Class MiniMax
java.lang.Object
smile.llm.model.minimax.MiniMax
- All Implemented Interfaces:
AutoCloseable, ModelExecutor, LanguageModel
MiniMax-M3 language model: loads a BF16 checkpoint and serves requests through the
ModelExecutor step API (bind, prefill, decode, finish).
This is the single-device reference path: dense attention (no block selection yet), host-routed MoE, no CUDA graphs, no speculation. Quantized (MXFP8) checkpoints and chat templating are added in later phases.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordPlacement of this process's ranks in a multi-node model. -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionMiniMax(String name, MiniMaxModel[] models, TensorParallelGroup group, MiniMaxTokenizer tokenizer, MiniMaxModelArgs params) Expert-parallel constructor.MiniMax(String name, MiniMaxModel model, MiniMaxTokenizer tokenizer, MiniMaxModelArgs params) Constructor. -
Method Summary
Modifier and TypeMethodDescriptionvoidattachCluster(ClusterLeader leader) Makes this process the leader of a cluster: from now on bind, prefill, decode, finish, evict and the prefix-reuse switch are mirrored to the followers, whose copies of the model execute them in lockstep.intbind(int[] prompt, int totalCapacity) Binds one request into the KV pool (multi-request safe).static MiniMaxbuild(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize) Builds a model from a HuggingFace BF16 checkpoint directory, sharding the routed experts of every MoE layer acrossdevices(expert parallelism with an all-reduce; attention, dense FFNs, router and shared expert are replicated on every rank).static MiniMaxbuild(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize, String weightMode) Builds a model, choosing how MXFP8 weights are stored and multiplied.static MiniMaxbuild(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize, String weightMode, MiniMax.ClusterSpec cluster) Builds this process's part of a model whose expert-parallel ranks span several processes (and nodes).static MiniMaxbuild(String checkpointDir, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, int pageSize) Builds a model from a HuggingFace BF16 checkpoint directory on a single device.static MiniMaxbuildLeader(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize, String weightMode, int port, int followers, long timeoutMs) Builds the leader of a multi-node model: waits forfollowersfollower processes (MiniMaxFollower) to connect, builds this process's ranks together with theirs, and mirrors every state change to them from then on.chat(Message[] dialog, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates an assistant reply for a dialog.voidclose()decode(int[] tokens) Decodes token ids to UTF-8 text.decodeStep(int[] requestIds, int[] lastTokens, int[] positions) One decode step for an active set (same or mixed positions; engine may cohort by position).int[]Encodes plain text (no chat template, no BOS/EOS).int[]encodeChat(Message... dialog) Encodes a dialog with the model chat template, leaving the assistant turn open for completion.int[]encodeChat(Message[] dialog, ChatOptions options) Encodes a dialog with optional tool-calling options.voidevict(int requestId) Instant Eviction without radix insert.family()Returns the architecture family label.voidfinish(int requestId, int[] sequenceTokens) Inserts into the radix tree (when enabled) and unbinds the request.generate(int[] prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates a completion from an already-tokenized prompt.booleanReturns whether images and videos can be processed (the checkpoint shipped vision weights and they loaded).Primary KV cache pool (rank 0 for TP).intReturns the configured maximum sequence length (max-model-len/ context length).model()Returns the underlying language-model façade.name()Returns the model instance / checkpoint name.network()Returns the network of rank 0.networks()Returns the network of every expert-parallel rank.intpadToken()Returns the pad token id.params()Returns the hyperparameters.prefill(int requestId, int[] prompt, int prefixLen) Prefills the unbound suffix of a prompt (activates this request alone).prefillChunk(int requestId, int[] prompt, int from, int to) Prefillsprompt[from, to)(chunked Continuous Batching).prefillMultimodal(int requestId, MultimodalPrompt prompt, int from, int to) Prefills a multimodal prompt using vision embeds + interleaved mRoPE.intprefixLen(int requestId) Page-aligned matched prefix length for a bound request.processMultimodal(Message[] dialog, ChatOptions options) Applies the chat template to a dialog with images and videos, preprocesses the media, and expands every placeholder to one token per vision patch group exactly as the reference processor does: an image becomesstart, image * n, end; a video becomes, per two-frame group, a timestamp text,start, video * n, end.voidserveCluster(ClusterFollower link) Follower main loop: executes the leader's mirrored calls on this process's ranks until the leader shuts the cluster down.voidsetPrefixReuseEnabled(boolean enabled) Enables or disables radix KV prefix reuse on every rank.int[]Returns stop / EOS token ids.toString()tryDecode(int[] tokens, boolean skipSpecial) Attempts a streaming decode; returns empty on incomplete UTF-8.Returns how linear weights are stored and multiplied.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface LanguageModel
chat, generateMethods inherited from interface ModelExecutor
idleDecodeGraphPrefetch, speculateStep, speculateStep, supportsStepApi, warmPrefix
-
Field Details
-
family
-
-
Constructor Details
-
MiniMax
public MiniMax(String name, MiniMaxModel model, MiniMaxTokenizer tokenizer, MiniMaxModelArgs params) Constructor.- Parameters:
name- model name.model- the network (weights loaded, KV pool installed).tokenizer- the tokenizer.params- hyperparameters.
-
MiniMax
public MiniMax(String name, MiniMaxModel[] models, TensorParallelGroup group, MiniMaxTokenizer tokenizer, MiniMaxModelArgs params) Expert-parallel constructor.- Parameters:
name- model name.models- one replica per rank (weights loaded, KV pools installed), in rank order.group- all-reduce group over the ranks' devices, ornullfor a single rank.tokenizer- the tokenizer.params- hyperparameters.
-
-
Method Details
-
attachCluster
Makes this process the leader of a cluster: from now on bind, prefill, decode, finish, evict and the prefix-reuse switch are mirrored to the followers, whose copies of the model execute them in lockstep.- Parameters:
leader- the connected cluster.
-
params
-
network
-
networks
Returns the network of every expert-parallel rank.- Returns:
- one replica per rank.
-
close
public void close()- Specified by:
closein interfaceAutoCloseable
-
toString
-
family
Description copied from interface:LanguageModelReturns the architecture family label.Examples:
meta/llama3,alibaba/qwen3.5. This is not necessarily the public API model id used by serve.- Specified by:
familyin interfaceLanguageModel- Returns:
- the family label string.
-
name
Description copied from interface:LanguageModelReturns the model instance / checkpoint name.- Specified by:
namein interfaceLanguageModel- Returns:
- the instance name (e.g. directory or HF repo leaf name).
-
maxSeqLen
public int maxSeqLen()Description copied from interface:LanguageModelReturns the configured maximum sequence length (max-model-len/ context length).- Specified by:
maxSeqLenin interfaceLanguageModel- Specified by:
maxSeqLenin interfaceModelExecutor- Returns:
- the maximum number of tokens allowed for prompt plus completion.
-
isMultimodal
public boolean isMultimodal()Returns whether images and videos can be processed (the checkpoint shipped vision weights and they loaded).- Returns:
truewhenprocessMultimodal(Message[], ChatOptions)may be called.
-
processMultimodal
public MiniMaxMultimodal processMultimodal(Message[] dialog, ChatOptions options) throws IOException Applies the chat template to a dialog with images and videos, preprocesses the media, and expands every placeholder to one token per vision patch group exactly as the reference processor does: an image becomesstart, image * n, end; a video becomes, per two-frame group, a timestamp text,start, video * n, end.- Parameters:
dialog- the messages; media parts are image or video URLs (data, http(s) or file).options- chat options.- Returns:
- the expanded token ids and the patches to encode during prefill.
- Throws:
IOException- if media cannot be read or decoded.IllegalArgumentException- if the request is malformed (no vision weights, audio, a media marker typed into text, an extreme aspect ratio, ...).
-
prefillMultimodal
Description copied from interface:ModelExecutorPrefills a multimodal prompt using vision embeds + interleaved mRoPE. Default throws; Qwen and MiniMax override.- Specified by:
prefillMultimodalin interfaceModelExecutor- Parameters:
requestId- request id.prompt- preprocess result.from- inclusive start (normally 0; prefix reuse disabled for VL).to- exclusive end.- Returns:
- logits when
to == inputIds.length, else null.
-
encodeChat
Description copied from interface:LanguageModelEncodes a dialog with the model chat template, leaving the assistant turn open for completion.- Specified by:
encodeChatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns (system/user/assistant).- Returns:
- prompt token ids ready for
LanguageModel.generate(int[], int, double, double, boolean, long, GenerationListener).
-
encodeChat
Description copied from interface:LanguageModelEncodes a dialog with optional tool-calling options.Default ignores
optionsand delegates toLanguageModel.encodeChat(Message...).- Specified by:
encodeChatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns.options- chat options; may benull.- Returns:
- prompt token ids.
-
encode
Encodes plain text (no chat template, no BOS/EOS).- Parameters:
text- the text.- Returns:
- token ids.
-
weightMode
Returns how linear weights are stored and multiplied.- Returns:
- the weight mode.
-
setPrefixReuseEnabled
public void setPrefixReuseEnabled(boolean enabled) Enables or disables radix KV prefix reuse on every rank. The MSA index keys live in side caches addressed by the same slots, so shared prefixes reuse them too.- Parameters:
enabled-trueto reuse cached prefixes.
-
model
Description copied from interface:ModelExecutorReturns the underlying language-model façade.- Specified by:
modelin interfaceModelExecutor- Returns:
- language model.
-
kvCachePool
Description copied from interface:ModelExecutorPrimary KV cache pool (rank 0 for TP). May benullonly for models without full-attention layers.- Specified by:
kvCachePoolin interfaceModelExecutor- Returns:
- KV cache pool, or
null.
-
padToken
public int padToken()Description copied from interface:ModelExecutorReturns the pad token id.- Specified by:
padTokenin interfaceModelExecutor- Returns:
- pad token id.
-
stopTokens
public int[] stopTokens()Description copied from interface:ModelExecutorReturns stop / EOS token ids.- Specified by:
stopTokensin interfaceModelExecutor- Returns:
- stop token ids.
-
decode
Description copied from interface:ModelExecutorDecodes token ids to UTF-8 text.- Specified by:
decodein interfaceModelExecutor- Parameters:
tokens- token ids.- Returns:
- decoded text.
-
tryDecode
Description copied from interface:ModelExecutorAttempts a streaming decode; returns empty on incomplete UTF-8.- Specified by:
tryDecodein interfaceModelExecutor- Parameters:
tokens- token ids.skipSpecial- whether to skip special tokens.- Returns:
- decoded text, or empty on incomplete UTF-8.
- Throws:
CharacterCodingException- when the sequence is incomplete.
-
bind
public int bind(int[] prompt, int totalCapacity) Description copied from interface:ModelExecutorBinds one request into the KV pool (multi-request safe).- Specified by:
bindin interfaceModelExecutor- Parameters:
prompt- prompt token ids.totalCapacity- desired slots (prompt + generation).- Returns:
- request id (
> 0).
-
prefixLen
public int prefixLen(int requestId) Description copied from interface:ModelExecutorPage-aligned matched prefix length for a bound request.- Specified by:
prefixLenin interfaceModelExecutor- Parameters:
requestId- id fromModelExecutor.bind(int[], int).- Returns:
- prefix length (
>= 0).
-
prefill
Description copied from interface:ModelExecutorPrefills the unbound suffix of a prompt (activates this request alone).- Specified by:
prefillin interfaceModelExecutor- Parameters:
requestId- request id.prompt- full prompt tokens.prefixLen- cached prefix to skip (fromModelExecutor.prefixLen(int)).- Returns:
- last-position logits shaped
[1, vocab](caller owns).
-
prefillChunk
Description copied from interface:ModelExecutorPrefillsprompt[from, to)(chunked Continuous Batching). Returns last-token logits only whento == prompt.length.- Specified by:
prefillChunkin interfaceModelExecutor- Parameters:
requestId- request id.prompt- full prompt tokens.from- inclusive start position in the prompt.to- exclusive end position.- Returns:
- logits
[1, vocab]when the prompt is fully prefilled; otherwisenull.
-
decodeStep
Description copied from interface:ModelExecutorOne decode step for an active set (same or mixed positions; engine may cohort by position). Tokens are[B]last tokens; positions are the write index for each row.- Specified by:
decodeStepin interfaceModelExecutor- Parameters:
requestIds- active KV request ids (order = batch).lastTokens- token id per request.positions- absolute position per request.- Returns:
- logits
[B, vocab](caller owns).
-
finish
public void finish(int requestId, int[] sequenceTokens) Description copied from interface:ModelExecutorInserts into the radix tree (when enabled) and unbinds the request.- Specified by:
finishin interfaceModelExecutor- Parameters:
requestId- request id.sequenceTokens- prompt + completion (no pad).
-
evict
public void evict(int requestId) Description copied from interface:ModelExecutorInstant Eviction without radix insert.- Specified by:
evictin interfaceModelExecutor- Parameters:
requestId- request id.
-
generate
public ChatCompletion generate(int[] prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Description copied from interface:LanguageModelGenerates a completion from an already-tokenized prompt.- Specified by:
generatein interfaceLanguageModel- Parameters:
prompt- prompt token id sequence.maxGenLen- maximum number of new tokens to generate (not including the prompt itself).temperature- sampling temperature; higher values increase randomness.topp- nucleus-sampling top-p threshold in(0, 1].logprobs-trueto include per-token log-probabilities in the result.seed- optional RNG seed for deterministic sampling;0means non-deterministic.listener- optional progress callback; may benull.cancelRequested- when non-null and returnstrue, generation stops between decode steps withCancellationException.- Returns:
- the completion for
prompt.
-
serveCluster
Follower main loop: executes the leader's mirrored calls on this process's ranks until the leader shuts the cluster down. Results (logits) are discarded: only the leader samples.- Parameters:
link- the connection to the leader.- Throws:
Exception- the first failing call (already reported to the leader).
-
chat
public ChatCompletion chat(Message[] dialog, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Description copied from interface:LanguageModelGenerates an assistant reply for a dialog.Equivalent to
LanguageModel.encodeChat(Message...)followed byLanguageModel.generate(int[], int, double, double, boolean, long, GenerationListener).- Specified by:
chatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns.maxGenLen- maximum number of new tokens to generate.temperature- sampling temperature; higher values increase randomness.topp- nucleus-sampling top-p threshold in(0, 1].logprobs-trueto include per-token log-probabilities in the result.seed- optional RNG seed for deterministic sampling;0means non-deterministic.listener- optional progress callback; may benull.cancelRequested- cooperative cancel flag; may benull.- Returns:
- the completion for
dialog.
-
build
public static MiniMax build(String checkpointDir, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, int pageSize) throws IOException Builds a model from a HuggingFace BF16 checkpoint directory on a single device.- Parameters:
checkpointDir- directory withconfig.json,tokenizer.jsonand safetensors.maxBatchSize- maximum concurrent requests.maxSeqLen- maximum context length;<= 0usesmax_position_embeddings.deviceId- CUDA device index, or a negative value for CPU.memFractionStatic- fraction of device memory for weights + KV;<= 0sizes the pool for tests.pageSize- KV page size in tokens.- Returns:
- the loaded model.
- Throws:
IOException- if the checkpoint is missing, quantized or incomplete.
-
build
public static MiniMax build(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize) throws IOException Builds a model from a HuggingFace BF16 checkpoint directory, sharding the routed experts of every MoE layer acrossdevices(expert parallelism with an all-reduce; attention, dense FFNs, router and shared expert are replicated on every rank).- Parameters:
checkpointDir- directory withconfig.json,tokenizer.jsonand safetensors.maxBatchSize- maximum concurrent requests.maxSeqLen- maximum context length;<= 0usesmax_position_embeddings.devices- CUDA device indices, one rank each, ornullfor a single CPU rank.memFractionStatic- fraction of device memory for weights + KV;<= 0sizes the pool for tests.pageSize- KV page size in tokens.- Returns:
- the loaded model.
- Throws:
IOException- if the checkpoint is missing, quantized or incomplete.
-
build
public static MiniMax build(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize, String weightMode) throws IOException Builds a model, choosing how MXFP8 weights are stored and multiplied.- Parameters:
checkpointDir- directory withconfig.json,tokenizer.jsonand safetensors.maxBatchSize- maximum concurrent requests.maxSeqLen- maximum context length;<= 0usesmax_position_embeddings.devices- CUDA device indices, one expert-parallel rank each, ornullfor one CPU rank.memFractionStatic- fraction of device memory for weights + KV;<= 0sizes the pool for tests.pageSize- KV page size in tokens.weightMode-auto,marlin,fp8,fp8emuordequant;nullreadsSMILE_MINIMAX_MXFP8(defaultauto).- Returns:
- the loaded model.
- Throws:
IOException- if the checkpoint is missing, unsupported or incomplete.
-
build
public static MiniMax build(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize, String weightMode, MiniMax.ClusterSpec cluster) throws IOException Builds this process's part of a model whose expert-parallel ranks span several processes (and nodes).devicesare the GPUs of this process; its ranks arecluster.rankOffset() ..ofcluster.worldSize(), and every process must call this at the same time (the NCCL communicator is created first and returns when all ranks have joined). With anullclusterthis is the single-process build.- Parameters:
checkpointDir- directory withconfig.json,tokenizer.jsonand safetensors.maxBatchSize- maximum concurrent requests.maxSeqLen- maximum context length;<= 0usesmax_position_embeddings.devices- CUDA device indices of this process, one expert-parallel rank each.memFractionStatic- fraction of device memory for weights + KV.pageSize- KV page size in tokens.weightMode- seebuild(String, int, int, byte[], double, int, String).cluster- this process's place in the cluster, ornull.- Returns:
- the loaded model.
- Throws:
IOException- if the checkpoint is missing, unsupported or incomplete.
-
buildLeader
public static MiniMax buildLeader(String checkpointDir, int maxBatchSize, int maxSeqLen, byte[] devices, double memFractionStatic, int pageSize, String weightMode, int port, int followers, long timeoutMs) throws IOException Builds the leader of a multi-node model: waits forfollowersfollower processes (MiniMaxFollower) to connect, builds this process's ranks together with theirs, and mirrors every state change to them from then on. The leader owns world ranks0 .. devices.length - 1.- Parameters:
checkpointDir- checkpoint directory on this node.maxBatchSize- maximum concurrent requests.maxSeqLen- maximum context length;<= 0usesmax_position_embeddings.devices- CUDA device indices of this process.memFractionStatic- fraction of device memory for weights + KV (the followers use the same).pageSize- KV page size in tokens.weightMode- seebuild(String, int, int, byte[], double, int, String);nullfor auto.port- TCP port the followers connect to.followers- number of follower processes.timeoutMs- how long to wait for the followers.- Returns:
- the leader model.
- Throws:
IOException- if the followers do not connect or the checkpoint cannot be loaded.
-