What you will create
Create a package undermstar/model/<name>/. Keep checkpoint configuration and weights, the model class, and the node submodules together. A legacy package can help you understand a checkpoint. Use the state contract for a new port.
Overview
A request takes a sequence of walks through a graph. A node runs a forward. A partition can make progress independently and exchanges streamed items with other partitions. See the runtime architecture.Before you start
Start with the reference checkpoint, a small input and its expected output. Match these before enabling capture or splitting the model across devices.Base classes
UseDeclaredDecoderModel for text and media prefill, EncoderDecoderNode for fixed encoder context, or DenoiseLoopSubmodule for a known number of denoise iterations.
Ported packages
Use packages on the state lint’sPORTED list as examples. Each declares persistent state with the state contract.
Worked examples
Register the model
Register the module and class name in MODEL_REGISTRY, the checkpoint in HF_MODELS and the deployment YAML in DEFAULT_CONFIGS.Implement the Model class
Implement the four abstract model hooks. See the model hook reference for arguments, results and call order.Per-request settings
Return resource-specific settings keyed by declaration name. Construct each sampler’s settings from the checkpoint defaults and request overrides.Declare state
Indeclare_state, name each resource and list all the nodes that share it. Orpheus’s LLM needs a KV cache and a sampler. Its SNAC decoder needs neither. Describe each step’s reads and writes in declare_step, then use the bound handles in the forward. Trace an array from declaration to forward.
Resource specs
A host-onlyValue stays on the host. A paged array uses its name for the KV pool and the read’s key for attention. The deployment override table lists the resource and YAML keys for each declaration. Each resource resolves one dtype at load, from its declaration or from the nodes that use it. See resource dtypes.
Layouts
A label names a logical cache stream. A span counts positions written or read in one step. At intake, describe each label’s prompt spans, decode growth and bounds in the request state layout. The engine uses that layout to size admission and index reusable prefixes. For attention, decide whether the context persists across steps, exists only within the forward, or has a bounded lifetime. For a port with block-causal masking, key padding, or a compaction step, see the legacy layout comparisons.Common needs
Connect the graph
Write down each node’s inputs, its outputs, and what ends a loop. Orpheus prefills its LLM with a voice and text, decodes audio tokens, and sends overlapping windows to a SNAC decoder. The decoder returns PCM audio. A streaming edge lets it decode one window while the LLM produces the next. Implementprocess_prompt, get_graph_walk_graphs, and walk_plan on your model or use a scaffold that supplies them. The conductor follows one plan per partition. Implement nodes and walks.
For example, the last node of an audio walk consumes codec tokens and emits audio. The edge name must match the key returned by its forward.
Advanced: async partitions and streaming
A producer and consumer in different partitions can advance independently. Connect them with a streaming edge and choose a chunk policy for the consumer.Streams from the client
Declare a topology connection withfrom_partition=CLIENT. Intake tensors under the edge name provide the initial items. For later appends, map each ClientChunk to tensor lists by edge name. The data worker handles appends automatically when every stream declares ClientAudio.
For OpenAI Realtime conversations, declare turn_tokens = (start_id, end_id) on the model subclass. These text token IDs open and close a reply. The Rust frontend refuses conversations when the model declares no turn tokens.
Implement the submodules
Load each node’s weights inget_submodule so a worker only allocates weights for its nodes. In the submodule, prepare the row’s input tensors and write the forward. Keep stop conditions and request bookkeeping outside the forward. First check a single row against the reference checkpoint. Then batch rows and declare capture shapes.
Declare a step
Return a step with the rows, segments, array growth and sampler operations in forward order. The engine admits it, plans its buffers and commits the updates after execution.Reaching your state
Implementbind_state on layers that use state. Look up handles by declaration name and call them for the current batch in the forward.
Node precision
Return each node’s policy fromget_node_precision(node_name). The engine reads it before the submodule exists, so get_submodule can build in it. A NodePrecision has three fields:
The default is
NodePrecision(torch.bfloat16). Set autocast=True only for a node whose reference numbers depend on autocast’s implicit fp32 ops and that has not been checked without them. Under autocast, rms_norm and RoPE run in the autocast dtype like other ops. With autocast off, the engine shuts out any enclosing autocast. Nodes that share a module must give its tensors the same dtypes, or loading fails. Orpheus runs its LLM in bf16 and its SNAC decoder in fp32:
Loading weights
get_submodule receives the node’s policy as precision: the model’s get_node_precision with the deployment’s nodes.<name>.precision block applied. Build the module on the meta device, then allocate it with materialize(module, precision, device) from mstar.engine.precision instead of to_empty(device). Each parameter then exists in its final dtype before the checkpoint loads, so it loads unrounded. When the module is only part of the node, pass its path in the node as at, for example at="model", because the policy’s globs name paths in the node. The engine applies the policy to the returned module and refuses a tensor that loaded narrower than the policy gives it, such as an fp32 island loaded in bf16. Pass the sharding groups from get_submodule through to the layers and weight loader.
Batch rows and capture forwards
Implement can_batch and forward_batched together. First verify row order and values eagerly, then return the supported capture shapes from get_accelerator_graph_configs.Combined walks
A node may return named sets of compatible walks. The worker can then batch rows from those walks together. The declaration and output routing still use each row’s real walk.Device loop back
For a one-token decode loop, declare the signal the sampler holds on device. The next iteration consumes the token from that slot.Piecewise CUDA graphs (capturing an inner loop)
Return one capture config per inner region. With lease_before_step, replay exactly when the region has a lease in engine_inputs.piecewise_leases. The region owns its own declaration, planning and commit. Exclude its resources from the outer declaration when leased. If can_lease refuses a batch, the outer step declares the eager work.Configure the deployment
Use the same model name in the registry, the YAML’smodel field, and the CLI’s DEFAULT_CONFIGS. Register the class as a module path and class name for lazy loading. Register its Hugging Face checkpoint in HF_MODELS if needed. Add the model name to the first column of a table in docs/models.rst, which the registration test reads. Add the deployment to the Mintlify model catalog in docs/mintlify/models.mdx too.
For a first deployment, follow the single-GPU Orpheus config. It places both nodes on rank 0.
Tuning resources per deployment
Set capacities underresources using the keys in the override table. Once a request works, see placement and parallelism to split the nodes across GPUs.
Tuning a node’s precision
A deployment can tighten a node’s policy undernodes.<name>.precision but cannot loosen it. The deployment guide lists the keys. Build in the precision that get_submodule receives. A block that asks for fp32 on a tensor the model already allocated in bf16 fails at load, because its weights would load rounded.
Routing across data-parallel replicas
A routing mirror estimates the admission cost on each replica, including any reusable prefix. Actual capacity is checked on the chosen worker.Preprocessing threads
For a model with stateless intake, setPREPROCESS_PARALLEL = True on the model class. Set preprocess_workers in the deployment for independent CPU work such as decoding uploads. The pool helps work that releases the GIL. Client-stream openings and appends must be processed in order.
Tensor parallelism
Set tp_size on the node group and name the sharded node in tp_enabled_nodes. The group’s declared ranks determine the process group passed to the layers.Guidance (CFG) parallelism
Declare eligible nodes in cfg_enabled_nodes. Set cfg_size on their node group and gather the branch results before combining guidance.Expert parallelism (MoE)
For a routed MoE, declare eligible nodes and pass the deployment’s moe_parallel argument to the MoE layers. All participants must use the same routing and collective order.Tuned kernel configs
Use the existing architecture and geometry tables for measured kernel choices. Keep deployment capacity settings under resources.Check the port
Add CPU tests for the prompt, walk choice, step declarations, and output edges. Add the package toPORTED in the state lint. From the repository root, check registration and the contract:
mstar serve <name> --gpus 0, wait for /health, and send your test prompt through the native API or SDK. Compare its result with the reference implementation and record the checkpoint, hardware, and outcome. For Orpheus, the stream test also checks that stitching chunks gives the same audio as decoding the complete sequence.
Lint rules
The state lint checks resource boundaries and the ported model list. New models declare state and join PORTED.Checklist
Verify a single row against the checkpoint, two unequal rows against single-row results, and eager execution against captured execution. Exercise the last chunk and request teardown.Model hook reference
Signatures omit the bound instance. The worker loads weights only for nodes assigned to it.Placement and graph construction
-
validate_config_yaml(config: dict, config_path: str) → None. Check a proposed deployment at load time. Return normally on success or raise ValueError with the incompatible setting. -
get_worker_graphs(config_path: str) → list[WorkerGraph]. Validate the placement, then split each walk by its applicablenode_groups. A worker can participate in several returned graphs. -
get_sharding_config(config_path: str) → ShardingConfig. Merge the deployment’s groups and shard dimensions with the model defaults. Return the resulting ShardingConfig. -
get_default_sharding_config() → ShardingConfig. Return the default tensor-parallel groups, eligible nodes and shard dimensions. The base configuration leaves weights unsharded. -
nodes → list[str]. Property listing the distinct node names in the model’s walks, sorted. -
get_graph_walk_graphs() → dict[str, GraphSection]. Return a mapping from each walk name to its GraphSection. Reuse a node name across walks to share the submodule. -
get_partition_topology(). Return the partitions and streaming connections the conductor needs to route this model. -
get_partitions() → list[PartitionDefinition]. Return the partition definitions for the model’s walks. -
get_walk_priorities() → list[WalkPriority]. Return WalkPriority entries for walks, nodes or node/walk pairs. Higher priorities run first. Unlisted entries have priority zero. -
get_combined_graph_walks() → dict[str, dict[str, set[str]]]. Return the constituent walk names grouped by node and combined walk. Each group can share a batch. -
combined_walk_of() → dict[tuple[str, str], str]. Return the validated mapping from each node and real walk to its combined walk. -
get_chunking_policies() → dict[str, tuple[ChunkingPolicy, ...]]. Return policies by node. Each policy names the walks, inputs and outputs to split or carry. -
chunking_policy_of() → dict[tuple[str, str], ChunkingPolicy]. Return the validated policy index keyed by node and walk. -
apply_chunking(walk_graphs: dict[str, GraphSection]) → dict[str, GraphSection]. Return walk graphs with chunkable nodes wrapped in loops. The base class applies this when building the graphs. -
get_submodule(node_name: str, device='cpu', tp_group=None, precision: NodePrecision=NodePrecision(None), moe_parallel: 'MoeParallelConfig | None'=None, cfg_group=None) → torch.nn.Module | None. On a worker, construct and load only the named node, using its device, precision policy and parallel groups. Return its module, or None in dummy mode. See Loading weights. -
get_node_precision(node_name: str) → NodePrecision. Return the node’s precision policy: parameter dtype, fp32 modules and autocast. The default is bf16 parameters without autocast. See Node precision.
Resource declarations and admission
-
declare_state() → list[Array | Sampler | SeqShard]. Return the model’s declared arrays, recurrent values, samplers and sequence shards. Each declaration names the nodes that share it. -
get_node_resources() → list[NodeResourceSpec]. Return the additional NodeResourceSpec objects the engine must build, including the nodes that use each one. Only the legacy packages onUNPORTEDdefine it; the state lint refuses it in a ported file. -
lora_roots() → tuple[LoraRoot, ...]. Return the weight roots per node eligible for adapter injection. An empty tuple disables model-specific targets. -
kernel_settings() → dict[str, dict[str, Any]]. Return default kernel and capacity overrides keyed by declaration, read or update name. -
checkpoint_path() → str | None. Return the on-disk checkpoint identity or None. Prefix reuse needs a stable identity. -
preprocess_fingerprint() → str. Return the preprocessing identity mixed into a cached prefix root. Change it when identical bytes would produce different inputs. -
kv_labels() → dict[str, dict[str, KVLabel]]. Return the writable KV labels per paged resource, including each label’s reads and keying policy. -
rebuild_policies() → dict[str, RebuildPolicy]. Return eviction recovery policies by node. Omitting a node forbids dropping its request state for later rebuild. -
get_request_resource_configs(input_modalities: list[str], output_modalities: list[str], model_kwargs: dict) → dict[str, ResourceReqConfig | SampleSettings]. At intake, return configuration by resource name for this request, including sampling settings and cache layout. -
get_sampling_config(node_name: str, model_kwargs: dict | None=None) → SamplingConfig | None. Resolve the node’s sampling settings for this request and return its SamplingConfig.
Request preparation, planning and output
-
request_kwargs() → frozenset[str] | None. Return the model-specific keys accepted at intake, or None to leave the set unspecified. Unknown keys are logged and ignored. -
load_image(filepath: str, device: str) → TensorAndMetadata. Decode an uploaded image into TensorAndMetadata for process_prompt. -
load_decoded_image(image: torch.Tensor, device: str) → TensorAndMetadata. Accept an already decoded RGB uint8 CHW tensor. Return the same model input representation as load_image. -
load_audio(filepath: str, device: str) → TensorAndMetadata. Decode an upload and return the waveform and metadata including sample rate and channel count. -
load_video(filepath: str, device: str). Decode the video and return its frame tensor and timing metadata. -
max_input_files() → dict[str, int]. Return a per-modality attachment cap. Unlisted modalities use the deployment-wide media cap. -
robot_io() → RobotIO | None. Return the robot observation and action shapes for the openpi bridge, or None. -
process_prompt(prompt: str | None, input_modalities: list[str], output_modalities: list[str], tensors: NameToTensorList | None=None, prompt_parts: list[PromptPart] | None=None, open_streams: frozenset[str]=frozenset(), **kwargs) → NameToTensorList | ProcessPromptOutput. After media decoding, return named tensor lists or ProcessPromptOutput with tensors, metadata, optional state layout and adapter selection. Raise ValueError to refuse the request. -
prompt_tokens(tensors: NameToTensorList, kv_layout: dict[str, dict[str, LabelLayout]]) → int. Return the number of prompt positions reported in usage, including media positions. -
prompt_lora_adapters() → frozenset[str]. Return the adapter names intake may select. Each must be configured at startup. -
walk_plan(partition_name: str, input_modalities: list[str], output_modalities: list[str], input_signals: dict[str, list[TensorPointerInfo]], model_kwargs: dict) → list[WalkStep]. At ingest, return ordered WalkStep objects for the named partition. An empty list skips this partition. ValueError refuses the request. -
get_max_output_tokens(**model_kwargs). Resolve the output-token budget from the request and model default. -
get_loop_caps(**model_kwargs) → dict[str, int]. Return the maximum iteration count for each bounded loop. A listed cap must be at least one. -
process_stream_chunk(chunk: ClientChunk) → NameToTensorList. On a client append, return named lists of tensors, one item per list entry for each declared client edge. All-ClientAudio models can use the built-in decoder. -
text_output() → TextOutput | None. Return the token-to-bytes policy, or None for a model that implements text encoding itself. -
postprocess(output: torch.Tensor, modality: str, request_kwargs: dict | None=None) → bytes. Encode a modality’s output tensor as bytes for the client. A model emitting another modality supplies the encoder for it. -
postprocess_inline(values: list[int], modality: str, request_kwargs: list[dict | None]) → list[bytes]. Encode a batch of scalar outputs and return one byte string per request in the same order. -
get_output_sample_rate(modality: str='audio') → int. Return the sample rate in Hz for an emitted audio modality. -
get_output_audio_channels(modality: str='audio') → int. Return the channel count for interleaved PCM. The default is mono. -
get_output_frame_rate(modality: str='video_frame', request_kwargs: dict | None=None) → float. Return the frame rate for raw video frames. A model that emits frames overrides this method. -
get_voices() → list[str] | None. Return available voice IDs or None for a model without a fixed voice list. -
get_default_voice() → str | None. Return the voice ID to use when the caller omits it, or None. -
warmup_preprocess() → None. Initialize host preprocessing once in the data worker before it accepts requests. Return no value.
NodeSubmodule hook reference
A row is one request’s contribution to a step. The worker selects the rows before the engine plans their reads and writes.Input preparation and batch selection
-
bind_node_resources(resources: dict[str, Any]) → None. Receive this node’s resources at load time and forward them to the layers that use them. Return no value. -
bind_node_state(handles: Mapping[str, Any]) → None. Bind the declared handles by name to the submodule and its layers. Return no value. -
request_state(request_id: str) → PerRequestState. Return the per-request record, creating it on first access. -
get_device(). Return the device of the node’s parameters. -
on_request_added(request_id: int, request_info: CurrentForwardPassInfo) → None. Initialize worker-local state before the request runs its first step. Return no value. -
prepare_inputs(graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs) → NodeInputs | None. Prepare NodeInputs for one ready row. None declines the row. Declining a final stream chunk completes the node. -
get_input_sequence_len(graph_walk: str, fwd_info: CurrentForwardPassInfo, inputs: NameToTensorList, **kwargs) → InputSeqLenInfo | None. Return the row’s length from its input shapes, or None. For a chunkable walk this must match the full prepared input length. -
split_inputs(graph_walk: str, fwd_info: 'CurrentForwardPassInfo', inputs: NodeInputs, start: int, end: int) → NodeInputs. Return the prepared inputs restricted to the half-open token interval. Keep the original row’s other settings. -
can_batch(batch: ExecutingBatch, model_inputs: list[NodeInputs]). Return True if these rows can run together. The base implementation returns False. -
max_batch_size(graph_walk: str). Return a cap for this walk or None for no model cap. -
batch_cap_varies(graph_walk: str) → bool. Return True when the cap must be reread during serving. The scheduler caches a fixed cap. -
max_rows_in_combined(graph_walk: str) → int | None. Return this walk’s row limit in a mixed step, or None. -
step_order(graph_walk: str) → StepOrder. Return the ordering for ready rows when the cap leaves a backlog. -
split_batches_by_capture_key(graph_walk: str) → bool. Return whether the scheduler should separate rows with different capture keys. -
cg_key_info(graph_walk: str, per_request_info: dict[str, CurrentForwardPassInfo], per_request_input_metadata: Mapping[str, InputMetadata] | None=None, **kwargs: Any) → Any. Return capture-key information for the proposed batch so the scheduler can select a bucket. -
uniform_row_inputs(graph_walk: str, has_loopback: bool=False) → NodeInputs | None. Return common inputs only when every row can use the same prepared values, otherwise None. -
speculative_input_seq_len(graph_walk: str, fwd_info: CurrentForwardPassInfo, prev_seq_len: int) → int | None. Estimate the next row’s token span before the in-flight step finishes. -
step_is_input_free(graph_walk: str) → bool. Return True only when a template row with the same span yields the identical declaration.
Step execution and capture
-
preprocess(graph_walk: str, engine_inputs: ModelInputsFromEngine, inputs: list[NodeInputs]) → dict[str, torch.Tensor | Any]. Collate the selected inputs into the keyword arguments consumed by the forward. -
declare_step(graph_walk: str, request_ids: list[str], inputs: list[NodeInputs], slot_lease: SlotLease | None=None, piecewise_leases: Mapping[str, SlotLease] | None=None, per_request_info: Mapping[int, CurrentForwardPassInfo] | None=None, **kwargs) → SubmoduleStep | None. Before execution, return the step’s reads, writes, spans and sampler work. Return None when the outer forward has no resource work. -
forward(graph_walk: str, engine_inputs: ModelInputsFromEngine, **kwargs) → NameToTensorList | BatchedModelOutput. Run one row and return its named output tensors or BatchedModelOutput. -
forward_batched(graph_walk: str, engine_inputs: ModelInputsFromEngine, **kwargs) → dict[str, NameToTensorList] | BatchedModelOutput. Run compatible rows and return their outputs by request or in a BatchedModelOutput. -
compile_regions() → Mapping[str, Sequence[tuple]]. Return the submodules to compile by name with example argument tuples for warmup. Disable whole-node compilation when declaring regions. -
get_accelerator_graph_configs(device: torch.device, tp_world_size: int=1) → list[AcceleratorGraphConfig]. Return the capture configurations for whole forwards on this device and TP size. An empty list requests none. -
get_piecewise_accelerator_graph_configs(device: torch.device, autocast_dtype: torch.dtype, tp_world_size: int=1) → dict[str, PiecewiseAcceleratorGraphConfig]. Return named configurations for independently captured inner calls. An empty mapping leaves all calls eager.autocast_dtypeis the dtype the node computes in, or float32 for a node that keeps its build dtypes without autocast. Allocate each static input buffer in the dtype the eager path passes the region. -
can_use_accelerator_graphs(batch: ExecutingBatch, model_inputs: list[NodeInputs]) → bool. Return True only when a captured forward supports this batch. -
warmup_compiles() → None. Compile remaining eager regions once after graph capture. Resources are bound, but the engine has admitted and planned nothing. The hook must neither read nor modify resource state. -
resident_walks() → frozenset[str]. Return walks eligible to plan a captured step from resident row tables. Other walks use ordinary planning. -
repeat_carry(graph_walk: str, signals: Collection[str]) → dict[str, str] | None. Return the mapping from loop-back output buffers to static inputs across replays, or None when repeats are unavailable. -
enable_repeats(walks: Collection[str]) → None. Record the walks the deployment requests to repeat, before capture. Return no value. -
device_loopback_signals(graph_walk: str) → frozenset[str]. Return input signal names the next iteration can read from the device without tensor routing. -
spanned_outputs(graph_walk: str) → frozenset[str]. Name the outputs whose rows need trimming. Inforward_batched, return a[batch, 2]device tensor of int64 start and exclusive end indices for each named output inBatchedModelOutput.output_spans. Engine postprocessing sees the full rows. After the completion event, the worker slices each row along its last dimension. If the worker could speculate into the consumer before that cut, setenable_async_scheduling=Falseon the producer or consumer. -
inline_signals(graph_walk: str) → dict[str, str]. Map scalar output signals to their row-addressed stop buffers so the worker can send the host value inline. -
unpack_packed_outputs(static_output: dict, request_ids: list[str], real_seq_lens: list[int], inputs: list[NodeInputs], per_request_info: dict[str, CurrentForwardPassInfo]) → dict[str, NameToTensorList]. Return the per-request slices of captured, packed outputs.
Completion and teardown
-
filter_batched_output(request_info: CurrentForwardPassInfo, outputs: dict[str, list[torch.Tensor]]) → dict[str, list[torch.Tensor]]. Return only the output keys that belong to this request after a fixed-shape captured forward. -
record_tokens(graph_walk: str, host_rows: 'HostRows', info_of: Callable[[int], CurrentForwardPassInfo]) → None. Record the landed host tokens for a node that keeps a token history. Return no value. -
check_stop(request_id: str, request_info: CurrentForwardPassInfo, outputs: Mapping[str, list[torch.Tensor]]) → set[str] | StopCheck. Return the names of the loops that finish for this row. END_PARTITION finishes the current partition. On an autoregressive node, setARNodeSubmodule.token_stopto aTokenStopwith the loop name, sampled-token buffer, stop IDs and sampler resource name. It supplies both the per-row and batched checks. A stop ID ends the loop unless that request setsignore_eos. The runtime enforces the token budget throughModel.get_loop_caps. -
get_stop_policies(graph_walk: str) → dict[str, StopPolicy] | None. Return static stop policies by loop name if the runtime can evaluate them, or None for the node’s stop check. -
check_stop_batched(request_ids: list[str], request_infos: dict[str, CurrentForwardPassInfo], host_rows: HostRows) → dict[str, set[str]] | BatchedStopCheck | None. Evaluate the host outputs for the whole batch and return the per-request stop decisions. -
postprocess(request_id: str, request_info: CurrentForwardPassInfo, outputs: dict[str, list[torch.Tensor]], inputs: NodeInputs | None=None, **kwargs). Modify the row’s output mapping in place on the GPU thread. Return no value. -
batch_postprocess(outputs: BatchedModelOutput, request_infos: dict[int, CurrentForwardPassInfo], inputs: list[NodeInputs], piecewise_runners: Mapping[str, PiecewiseAcceleratorGraphRunner] | None=None) → None. On a rows-only step, modify the batched rows in place. There are no per-request outputs. On other steps, the hook receives only requests whosepostprocesssucceeded, in input order. Raising here fails all those requests. -
cleanup_request(request_id: str). Release the request’s node-local state. Overrides call the base cleanup before the handle can be reused.