ATOM Distributed Inference Guide#
ATOM (AiTer Optimized Model) supports three parallelism strategies for distributed LLM inference on AMD ROCm/HIP GPUs: Tensor Parallelism (TP), Data Parallelism (DP), and Expert Parallelism (EP). These can be combined to scale across multiple GPUs for large model serving.
Quick Reference#
Parallelism |
CLI Flag |
Purpose |
Communication |
|---|---|---|---|
Tensor Parallel (TP) |
|
Shard weights across GPUs |
NCCL AllReduce |
Data Parallel (DP) |
|
Replicate model, split requests |
Gloo AllReduce (CPU) |
Sequence Parallel (SP) |
|
Split each batch’s tokens across GPUs (Ulysses; |
NCCL All-to-All, AllGather/ReduceScatter |
Expert Parallel (EP) |
|
Distribute MoE experts across GPUs |
MORI All-to-All |
DP Attention |
|
Flatten DP into TP for MoE layers |
NCCL AllGather/ReduceScatter |
Common configurations:
Model Type |
Configuration |
Example |
|---|---|---|
Dense (Llama, Qwen3) |
TP only |
|
MoE (Qwen3-235B) |
TP + EP |
|
MoE throughput scaling |
TP + DP + EP |
|
Dense throughput scaling |
TP + DP |
|
Tensor Parallelism (TP)#
Tensor Parallelism shards model weights across GPUs so each GPU holds a slice of every layer. ATOM uses AITER’s init_dist_env() to initialize NCCL process groups.
Weight Sharding#
ATOM provides parallel linear layer classes in atom/model_ops/linear.py:
ColumnParallelLinear— splits the output dimension (dim 0) across TP ranks. Each GPU computes a shard of the output independently.RowParallelLinear— splits the input dimension (dim 1) across TP ranks. After the local matmul, an AllReduce across the TP group aggregates partial results.QKVParallelLinear— extendsColumnParallelLinearfor attention Q/K/V projections. Partitions heads across TP ranks, replicating KV heads whennum_kv_heads < tp_size.MergedColumnParallelLinear— merges multiple column-parallel outputs (e.g., gate and up projections) into a single weight tensor, sharded along dim 0.ReplicatedLinear— no sharding; weight is replicated on every rank.
Process Group Initialization#
In init_model_env() (atom/model_engine/model_setup.py, called from ModelRunner.__init__()), the distributed environment is set up via AITER:
from aiter import init_dist_env
from aiter.dist.parallel_state import get_tp_group, get_dp_group, get_pp_group
init_dist_env(
config.tensor_parallel_size,
rankID=rank,
backend="nccl",
distributed_init_method=distributed_init_method,
data_parallel_size=config.parallel_config.data_parallel_size,
data_parallel_rank=config.parallel_config.data_parallel_rank,
)
After initialization, get_tp_group(), get_dp_group(), and get_pp_group() provide the respective process groups for collective operations.
AllReduce#
The AllReduce happens inside LinearBase.forward() when tp_dim == 1 (row-parallel):
if self.tp_dim == 1 and self.tp_size > 1 and self.reduce_results:
y = get_tp_group().all_reduce(y, ca_fp8_quant=False)
Configuration#
Config.tensor_parallel_size(int, default1): Number of TP ranks. Must satisfy1 <= tensor_parallel_size <= 8.CLI:
--tensor-parallel-size Nor-tp N
Data Parallelism (DP)#
Data Parallelism runs multiple independent engine replicas, each handling a subset of incoming requests. DP is coordinated at the scheduling level rather than the model level — each DP rank has its own EngineCore, scheduler, and model runner.
Architecture#
When data_parallel_size > 1, EngineCore.run_engine() instantiates a DPEngineCoreProc instead of a plain EngineCore:
# atom/model_engine/engine_core.py
@staticmethod
def run_engine(config, input_address, output_address):
if config.parallel_config.data_parallel_size > 1:
engine = DPEngineCoreProc(config, input_address, output_address)
else:
engine = EngineCore(config, input_address, output_address)
engine.busy_loop()
DP Process Group Initialization#
DPEngineCoreProc._init_data_parallel() creates a Gloo-based process group for CPU-side coordination:
def _init_data_parallel(self, config):
dp_rank = config.parallel_config.data_parallel_rank
dp_size = config.parallel_config.data_parallel_size
local_dp_rank = config.parallel_config.data_parallel_rank_local
assert dp_size > 1
assert local_dp_rank is not None
self.dp_rank = dp_rank
self.dp_group = config.parallel_config.stateless_init_dp_group()
The stateless_init_dp_group() method (in ParallelConfig) calls stateless_init_torch_distributed_process_group() with the gloo backend, creating an isolated process group that does not interfere with the NCCL TP group.
Synchronized busy loop#
The DP busy loop overrides the base EngineCore.busy_loop() to synchronize state across DP ranks before each step. The _sync_dp_state() method packs four signals into an int64 tensor and performs a single AllReduce(MAX):
# State synced: [is_prefill, num_tokens, has_unfinished, shutdown]
state_tensor = torch.tensor(
[
1 if local_is_prefill else 0,
local_num_tokens,
1 if local_has_unfinished else 0,
1 if local_shutdown else 0,
],
dtype=torch.int64, device="cpu",
)
torch.distributed.all_reduce(
state_tensor, op=torch.distributed.ReduceOp.MAX, group=self.dp_group
)
This ensures:
All ranks agree on the batch type (prefill vs. decode). Since MORI requires all DP ranks to execute the same phase, a rank that has no prefill work must run a dummy prefill when any other rank does prefill.
Graceful shutdown: all ranks must agree before exiting.
Token count alignment: the maximum token count across ranks is used for padding.
Dummy batch execution#
When a DP rank has no real work but other ranks do, it executes dummy batches to participate in collective operations:
_execute_dummy_batch()— runsModelRunner.dummy_execution, a batch with no request, through the model, triggering AllReduce and MORI collectives so other ranks are not blocked.ForwardMode.decidegives it the group’s phase (prefill when any peer prefills) and its width: the group’srunning_bs/running_tokenson a decode or a token-graph prefill, one running token on a ragged step (two under TBO, so it splits). Its rows have batch id -1, slot -1 and position 0. It runs everything its peers run, the LM head included (its collective under the DP-sharded head), and samples nothing:postprocesscuts the logits to its zero scheduled rows. A pass where no rank has a request runs nothing: the busy loop skips it. A step that reaches the runner with no rank scheduling a request (requests exist but none could be scheduled) runs the same way on every rank, at the smallest capturedrunning_bs(one request with none captured).Yielding a decode — when prefill token graphs are recorded, a peer prefills and the group’s prefill delayer (not a rank-local one) lets it, a decoding rank skips its own decode and runs the dummy too (
Scheduler._schedule, on_group_prefill_tick). Its dummy brings back the tokens its last decode sampled (deferred output), which_execute_dummy_batchpostprocesses like any step’s whenever the rank has running requests.ForwardMode._pad_to_token_graphraises every rank to the bucket the step replays, since ranks replaying different buckets hang the group.
Device assignment#
When DP is enabled on a single node, each DP rank uses a different set of GPUs. init_model_env() (atom/model_engine/model_setup.py) takes the device from local_device_index() (atom/config.py):
local_device_rank = local_device_index(config, rank)
device = torch.device(f"cuda:{local_device_rank}")
With DP and TP only, that is dp_rank_local * tensor_parallel_size + rank. For example, with DP=2 and TP=4:
DP rank 0: GPUs 0, 1, 2, 3
DP rank 1: GPUs 4, 5, 6, 7
DPMetadata#
The DPMetadata dataclass (in atom/utils/forward_context.py) tracks token distribution across DP ranks for padding and collective operations:
@dataclass(frozen=True)
class DPMetadata:
running_tokens_per_dp_rank: np.ndarray # [dp_size] int32: the rows each rank's forward runs
# max_tokens_across_dp / get_sizes_across_dp() are read off it
set_forward_context takes running_tokens_per_dp_rank as a required argument, wraps it in DPMetadata when DP is on, and mirrors it onto context.running_tokens_across_dp as Python ints. The engine’s table is one [dp_size] numpy buffer the runner owns: ForwardMode.decide settles it in place each step from the scheduled tokens exchanged in the step’s one DP sync (a padding prefill rank raised to its token-graph bucket, every rank set to the group height on a unified step), and the capture loops fill the same buffer. A caller that knows only its own count uses DPMetadata.gather_running_tokens(parallel_config, running_tokens), one AllReduce on the DP CPU group (skipped for a group of one):
table = np.zeros(dp_size, dtype=np.int32)
table[dp_rank] = running_tokens
dist.all_reduce(torch.from_numpy(table), group=get_dp_group().cpu_group)
CoreManager (DP orchestration)#
CoreManager (in atom/model_engine/engine_core_mgr.py) manages multiple DP engine processes:
For each DP rank, it creates a
Configcopy with the appropriatedata_parallel_rankanddata_parallel_rank_local.Launches each
EngineCorein a separatemultiprocessing.Process.Uses ZMQ (ROUTER/DEALER) sockets for input distribution and ZMQ (PUSH/PULL) for output collection.
Distributes incoming requests across DP ranks via a configurable load-balancing strategy (see DP request load balancing).
Waits for READY signals from all ranks before accepting requests.
When enable_dp_attention is set, CoreManager flattens TP into DP:
if config.enable_dp_attention:
self.local_engine_count = config.tensor_parallel_size * config.parallel_config.data_parallel_size
config.parallel_config.data_parallel_size = self.local_engine_count
config.tensor_parallel_size = 1
DP request load balancing#
Because the DP busy loop is lockstep (all ranks AllReduce has_unfinished
each step, and an idle rank runs _execute_dummy_batch() when any other rank is
busy), an unbalanced request distribution directly wastes GPU: the step time is
bounded by the busiest rank while lighter ranks burn cycles on dummy batches.
CoreManager therefore routes each request to the least-loaded rank rather
than blindly rotating.
The strategy is selected with --dp-load-balance (Config.dp_load_balance):
Strategy |
Signal |
Selection |
|---|---|---|
|
none |
Load-agnostic rotation ( |
|
in-flight request count, then prompt-token load |
|
|
combined token load per rank |
|
|
prefill each rank reports it has left, plus this request’s own work |
|
|
prompt-prefix location, queued prefill per rank |
Keep a request on the rank holding its prefix unless that rank has over |
least_requests (the default) keeps the number of in-flight requests even
across ranks — the dominant lever for DP-lockstep efficiency (equal request
counts keep ranks in prefill/decode phase). When ranks are tied on request
count (the common case under saturation), it breaks the tie by the lighter
in-flight prompt-token load, so pending prefill work is packed evenly across the
equal-request ranks. least_tokens
additionally weights by prompt-token load across all ranks, mirroring production guidance from the
DeepSeek-V3/R1 inference system
(prefill balances on input-token count, decode balances on request count) the ATOM_DP_LB_REQ_EQUIV request-equivalent term captures
decode-slot pressure. It helps most with heterogeneous prompt lengths under
moderate load; with uniform-length requests it degenerates to least_requests.
All strategies break ties with a round-robin cursor.
share_cache is for deployments whose offload tier is shared by every DP
rank (one Mooncake Store, one LMCache MP server). Any rank can then load a
prefix another rank computed, so a request’s prefill work does not depend on
where it lands and the router balances purely by work:
Request cost: the common compressed prefix index in
atom/model_engine/dp_routing/prefix_spread.pyretains exact complete-block matches and producer ownership for bothprefix_spreadandshare_cache.share_cacheadds its work score through a placement adapter; it does not maintain a second sampled index. A rank receives credit for its local prefix and for the completed remote prefix that the shared offload tier can load, using the same chunk alignment andOFFLOAD_MIN_LOAD_TOKENScontract asprefix_spread. An in-flight producer only credits its own rank. The history is a hint rather than proof of a completed publication or current residency. Admission reports actual reuse. A smaller hit invalidates the target’s stale suffix and its remote-tier hint, while preserving other ranks’ confirmed local prefixes and active producers. The request that recomputes the suffix becomes its producer, andatom:dp_share_cache_stalecounts the correction.Rank backlog: each DP engine core reports
(requests ingested, prefill tokens left)when it changed, at most every 10 ms (EngineCoreRequestType.PREFILL_BACKLOG). The reuse reports above go on their own (DP_REUSE), queued ahead of the request’s first output. A started request countsprompt - num_cached_tokens, so HBM hits and finished chunks shrink it as they happen. A tier load is credited at its planned boundary as soon as the request parks, while the load is still in flight; if the load fails, the credit reverts to the HBM hit. A request not yet allocated counts the router’s estimate. The CoreManager adds the charges of requests sent after the rank’s last report.
With a Mooncake Store, share_cache likewise refuses distinct per-NIC
mooncake_store.pools pairs (see the prefix_spread section below); aliases
that all name one master/metadata pair are accepted.
It needs --enable_prefix_caching and ATOM_FRONTEND_PREFIX_HASH=1, and is
mutually exclusive with ATOM_DP_SESSION_AFFINITY=1. With a Mooncake Store
OFFLOAD_MIN_LOAD_TOKENS defaults to 512. With lmcache_mp set
OFFLOAD_MIN_LOAD_TOKENS and OFFLOAD_MIN_SAVE_TOKENS low yourself (e.g.
256-1024), so the tier holds what HBM holds.
prefix_spread. The router remembers which ranks ran each prompt prefix (every complete block in the frontend prompt block-hash chain) and keeps a request on its prefix’s rank, unless another rank has under ATOM_DP_PREFIX_IDLE_TOKENS queued prefill and a free request slot (about to idle) while the prefix’s rank has over twice that, or has every request slot taken. Then the request goes to an idle rank, chosen by queued prefill – with more than two ranks, among those within ATOM_DP_PREFIX_IDLE_TOKENS / 2 of the least queued, the one holding the most of its prefix – and loads the prefix from the offload tier. While both ranks have queued prefill a move adds no capacity under lockstep DP, so the request stays. New prefixes go to the lightest rank (least_tokens score). A request whose prefix source is still prefilling stays on the prefix’s rank to reuse it from HBM unless that rank is backlogged and another is idle; then it moves and is credited what the target holds plus the longest part of the prefix some request already finished prefilling on any rank (which the tier can load); the rest of its prompt is charged as prefill. If the source leaves before finishing its prefill, the parts it was computing go to the earliest request still waiting on them on that rank, which is charged for recomputing them; with no such request they are forgotten. Another rank’s part of the prefix counts as a local hit only once its source finished prefilling it. A load threshold applies to the missing transferable prefix beyond the target’s local hit, after chunk alignment, rather than to the prompt length or prefix indexing. If that difference is below OFFLOAD_MIN_LOAD_TOKENS, the request still goes to the selected idle rank, reuses its local prefix and recomputes the remainder. Prompts shorter than 4096 tokens participate in prefix routing whenever they contain complete hash blocks. The index stores compressed intervals of consecutive chained hashes, retaining exact complete-block prefix lengths without one dictionary entry per block. Its unique-edge token budget is PrefixSpreadRouter.CAP tokens (a class attribute); active producer intervals are pinned and can exceed this history budget until their requests finish. Past the budget, finished history is shed oldest interval first. An overage of at most an eighth of that interval (at least one block) is cut from its tail, so a long session keeps its head and its rank, and the interval then queues behind the others; a larger overage, or one that covers the whole interval (a one-block interval is always dropped, never shortened), drops the interval whole, so one placement never takes more eviction passes than whole-interval eviction would. Eviction is therefore only approximately least-recently-used: a hot interval can lose part of its tail while an older one is still held. When a request finishes its prefill, the intervals along its chain that are finished, held by the same ranks in the same recency order and have no other child are merged back; so a session that keeps extending its own history stays a few intervals rather than one more per turn. Intervals that were split by a request ending mid-interval are merged back only by a later completion along the same chain, not eagerly, and divergent branches stay separate. Active requests keep one continuous prefix dependency record, so history eviction cannot hide a still-prefilling producer from new followers. A moved request is credited its prefix only if an offload tier shared by the DP ranks (lmcache_mp, mooncake_store; not the per-rank lmcache_offload), with a role that both saves and loads (offload, kv_both), can load it (at least OFFLOAD_MIN_LOAD_TOKENS); otherwise only its local part. Needs --enable_prefix_caching and ATOM_FRONTEND_PREFIX_HASH=1, and excludes ATOM_DP_SESSION_AFFINITY (startup fails otherwise); bypasses the offline backpressure dispatch. Tuning: ATOM_DP_PREFIX_IDLE_TOKENS (default 32768).
The compressed prefix index stores consecutive chained-hash intervals, retaining exact complete-block matches without a dictionary entry for every hash block. Its history budget counts unique indexed tokens, independent of hash-block granularity; it is not a limit on all router memory. Active producer intervals are pinned so history eviction cannot hide them from new followers. Active request hash chains and dependencies remain until completion, cancellation or reset releases them, and may exceed the history budget.
Index budget trade-off and how to see it. The index is bounded (PrefixSpreadRouter.CAP tokens of unique intervals; how many hash blocks that is depends on the hash block size, which is block_size times the DCP size), and over that budget the router sheds finished history oldest interval first, shortening an interval from its tail when the overage is small. To see whether it runs, read atom:dp_prefix_index_events_total (or the Python dict LLMEngine.get_metrics_statistics()["dp_router"]["prefix_index"]; there is no HTTP JSON endpoint for it): tail_trim and leaf_evict both 0 and atom:dp_prefix_index_tokens well under CAP mean the trade-off never applied. Nonzero counters mean old history was shed, not that hot prefixes were lost – cold one-shot history is shed the same way; a rising tail_trim / leaf_evict rate together with a falling atom:dp_prefix_route_total{decision="owner"} share and atom:dp_prefix_moved_tokens_total is the pattern to look into. blocked rising means the index is still over budget after eviction ran out of evictable history: what is left is still-prefilling history and the finished ancestors of it, which cannot be shed while they have children. If it matters, raise PrefixSpreadRouter.CAP (there is no environment variable).
With one routable engine, pipeline parallelism or RapidServe, prefix_spread and share_cache have no effect and their routing requirements are not enforced. LMCache MP requires the configured chunk to match the server when this router is active; PAGE-only single-engine runs use the server’s chunk. Native-state transfers retain their own chunk-matching requirement.
When prefix_spread or share_cache is active, Mooncake Store must expose one shared (master, metadata) pair to all DP ranks. Per-NIC aliases in mooncake_store.pools are accepted only when every alias names that same pair. Distinct per-NIC pools are rejected at router startup because a worker can load only from its selected NIC’s pool; a scheduler lookup across pools does not make those prefixes transferable. Distinct pools remain available with other routing policies, or when neither router is active.
Choose OFFLOAD_MIN_LOAD_TOKENS for the model and backend. It measures the aligned missing prefix, so an owner with 16384 tokens and an idle target with 13312 tokens still sends the request to the target when the 3072-token difference is below the minimum; the target recomputes that difference. A warmed Qwen3-0.6B DP2/TP1 LMCache MP probe on MI355X, with a 512-token chunk and 13312 local tokens, favored recomputation at an 8192-token difference (median TTFT 102.2 ms versus 134.7 ms with loading), was near break-even at 12288, and favored loading at 16384 (150.6 ms versus 198.2 ms). Each arm used four samples. For that configuration, 16384 is a conservative minimum; it is not a measured default for other models, backends or decode load. Include restoration, replay and prefill scheduling in the comparison, rather than timing the copy alone.
For Mooncake Store, routing and the connector share mooncake_store.chunk_tokens: only complete chunks beyond the local prefix are credited, and the minimum load applies to that aligned remainder. An unaligned head and tail remain prefill work. The index records execution history, not current HBM residency or completed Store publication. Admission performs an authoritative lookup and falls back to recomputation on a miss; placement estimates and dp_prefix_moved_tokens can still overestimate cache reuse after eviction or while a save is pending.
For V4.1, use the native Mooncake Store recipe to recover shared PAGEs without LMCache MP. Local HBM hits remain local. V4.1 needs bounded replay on the Store (the default; refused at startup without it); this does not enable other hybrid models that require an independent state tier. The final recipe uses a configurable 4096-token minimum, an unmeasured policy cutoff rather than a measured optimum. It permits the 6144-token load that was slower than recomputation in the measured idle case; use 8192 if prioritizing that measured idle-case latency. The recipe bounds both waiting-queue coalescing and running partial-prefill coalescing. A queue-age bound alone does not limit a partial request already in the running list. Its measured latency results and configuration limits are recorded in the recipe.
When ATOM_DP_SESSION_AFFINITY=1, session routing adds a cache-locality layer
above the configured fallback strategy. A new correlation/session ID is placed
on the rank minimizing
estimated_uncached_prefill_tokens + ATOM_DP_LB_REQ_EQUIV * in_flight_requests;
rendezvous hashing only breaks exact ties. That owner is then immutable for the
life of the process, so a busy owner never causes a later turn to lose its
prefix-cache locality. Child correlation IDs are independent sessions and do
not inherit the parent’s rank. For an established session, load accounting
charges only positive prompt-length growth rather than repeatedly charging the
complete cached conversation.
The OpenAI server reads the session ID from X-Dynamo-Session-ID, falling back
to X-Correlation-ID; X-Dynamo-Parent-Session-ID is retained for routing
observability. For AIPerf agentic workloads, the normal correlation header is
therefore sufficient. AIPERF_HTTP_X_DYNAMO_SESSION_ID_FROM_CORRELATION_ID=1
can also be used when parent-session telemetry is desired.
Bookkeeping is maintained entirely inside CoreManager (no engine-core protocol
change): for the load-aware strategies, load is charged on dispatch and released
when a sequence finishes (STREAM finished / offline ADD output) or is aborted
— all idempotent under _lb_lock, since dispatch runs on the request thread and
release on the per-rank output threads. Explicit data_parallel_rank hints are
validated up front (a bad hint rejects the whole batch before any charge, so no
partial load leaks) and, when valid, take priority but are still charged so they
participate in balancing. round_robin skips this bookkeeping unless session
affinity is enabled, because new-session placement still needs the token-load
counters. An invalid dp_load_balance value fails fast at CoreManager
construction rather than silently defaulting. reset_dp_router() (called at
the start of an offline generate() batch) assumes the previous batch has
drained and warns if it is invoked while requests are still charged.
Configuration#
ParallelConfig.data_parallel_size(int, default1): Number of DP replicas.ParallelConfig.data_parallel_rank(int, default0): This rank’s DP index.ParallelConfig.data_parallel_rank_local(int, defaultNone): Local DP rank on this node.Config.dp_load_balance(str, default"least_requests"): DP routing strategy.CLI:
--data-parallel-size Nor-dp N;--dp-load-balance {round_robin,least_requests,least_tokens,prefix_spread,share_cache}Env:
ATOM_DP_LB_REQ_EQUIV(int, default512): token-equivalent cost of one in-flight request forleast_tokens.Env:
ATOM_DP_DISPATCH_DEPTH(int, default0): per-rank in-flight cap for lazy dispatch of an offline batch (LLMEngine.generate/generate_multimodal). Online API admission is unchanged. While it is positive, that offline routing balances on in-flight request count and ignoresround_robinandleast_tokens; init warns whendp_load_balanceis notleast_requests. Underprefix_spreadandshare_cachethe depth is ignored (init warns). A failed send returns the requests to the pending pool.abort_requestremoves a request that has not been sent yet.Env:
ATOM_DP_SESSION_AFFINITY(bool, default0): load-place each new session once, then keep all later turns on its cache owner without spill.
Expert Parallelism (EP)#
Expert Parallelism distributes MoE experts across GPUs so that each GPU owns a subset of experts. Tokens are routed to the correct GPU via all-to-all communication.
FusedMoEParallelConfig#
The FusedMoEParallelConfig dataclass (in atom/model_ops/moe.py) determines how MoE layers are parallelized:
@dataclass
class FusedMoEParallelConfig:
tp_size: int # Tensor parallel size (1 when EP is active)
dp_size: int # Data parallel size
ep_size: int # Expert parallel size
tp_rank: int
dp_rank: int
ep_rank: int
use_ep: bool # Whether EP is enabled
local_ep_size: int # Number of EP ranks on this node
Key properties:
use_all2all_kernels: returnsTruewhendp_size > 1 and use_ep and mori is available. This activates the MORI all-to-all dispatch/combine kernels.When EP is enabled,
tp_sizeis set to 1 andep_size = dp_size * tp_size(the original TP size). Each device fully owns its assigned experts.
The FusedMoEParallelConfig.make() static method constructs the config:
use_ep = dp_size_ * tp_size_ > 1 and parallel_config.enable_expert_parallel
if enable_dp_attention:
# Flatten DP into TP: effective tp_size = dp_size * tp_size
tp_size, tp_rank = flatten_tp_across_dp(dp_rank)
if use_ep:
ep_size = tp_size
ep_rank = tp_rank
# Each device owns experts fully -- no intra-expert tensor parallelism
return FusedMoEParallelConfig(tp_size=1, tp_rank=0, ep_size=ep_size, ...)
Expert distribution#
In FusedMoE.__init__(), when EP is active, the global experts are partitioned:
if self.use_ep:
self.local_num_experts, self.expert_map = determine_expert_map(
ep_size=self.ep_size,
ep_rank=self.ep_rank,
global_num_experts=self.global_num_experts,
)
else:
self.local_num_experts = self.global_num_experts
self.expert_map = None
Each GPU only loads weights for its assigned experts, reducing per-GPU memory usage proportionally.
MORI communication#
When use_all2all_kernels is True, the MoriPrepareAndFinalize class (in atom/model_ops/fused_moe/mori_prepare_finalize.py) handles token routing:
Dispatch phase (prepare()):
Receives input activations, top-k weights, and top-k expert IDs.
Calls
self.mori_op.dispatch()to send each token to the GPU that owns its selected expert.Returns dispatched activations, scales, expert IDs, weights, and per-expert token counts.
(dispatch_a1, dispatch_weights, dispatch_scale, dispatch_ids, dispatch_recv_token_num
) = self.mori_op.dispatch(a1, topk_weights, scale, topk_ids, block_num, warp_per_block)
Combine phase (finalize()):
After expert computation, calls
self.mori_op.combine()to route results back to the originating GPU.Copies the combined result into the output tensor.
result = self.mori_op.combine(fused_expert_output, None, topk_ids, block_num, warp_per_block)[0]
output.copy_(result[:num_token])
The block configuration adapts to the batch type: prefill uses block_num=128, warp_per_block=16, while decode uses block_num=64, warp_per_block=4.
Configuration#
Config.enable_expert_parallel(bool, defaultFalse): Activates EP for MoE layers.Config.enable_dp_attention(bool, defaultFalse): Flattens DP ranks into the TP/EP dimension for MoE, while using per-rank attention for non-MoE layers.CLI:
--enable-expert-parallel,--enable-dp-attention
Environment variables#
Variable |
Type |
Default |
Description |
|---|---|---|---|
|
int |
|
Data parallel rank index |
|
int |
|
Local data parallel rank on this node |
|
int |
|
Total number of data parallel replicas |
|
str |
|
IP address for DP Gloo rendezvous |
|
int |
|
Port for DP Gloo rendezvous |
|
int |
|
Token-equivalent cost of one in-flight request for the |
|
bool |
|
Load-place a new session, then keep later turns on its immutable prefix-cache owner |
~~ |
Removed. Use CLI flag |
||
|
bool |
|
Fuse QK-norm + RoPE + cache quant for Qwen3 dense and MoE models |
Environment variables in atom/utils/envs.py are evaluated lazily via __getattr__. If ATOM_DP_SIZE, ATOM_DP_RANK, or ATOM_DP_RANK_LOCAL are set in the environment, they override programmatic ParallelConfig defaults in ParallelConfig.__post_init__().
AITER environment variable (not in envs.py):
Variable |
Type |
Default |
Description |
|---|---|---|---|
|
str |
– |
Set to |
Multi-GPU deployment examples#
DeepSeek-R1 on 8 GPUs (TP8)#
From the project README — a dense MLA model deployed with pure tensor parallelism:
python -m atom.entrypoints.openai_server \
--kv_cache_dtype fp8 \
-tp 8 \
--model deepseek-ai/DeepSeek-R1
Qwen3-235B-A22B on 8 GPUs (TP8 + EP)#
From recipes/Qwen3-235b.md — a MoE model with 128 experts, deployed with tensor parallelism and expert parallelism:
export AITER_QUICK_REDUCE_QUANTIZATION=INT4
export ATOM_ENABLE_QK_NORM_ROPE_CACHE_QUANT_FUSION=1
python -m atom.entrypoints.openai_server \
--model Qwen/Qwen3-235B-A22B-Instruct-2507-FP8 \
-tp 8 \
--kv_cache_dtype fp8 \
--enable-expert-parallel \
--max-model-len 16384 \
--max-num-batched-tokens 20000
Tips from the recipe:
Use FP8 KV cache (
--kv_cache_dtype fp8) for memory efficiency.Quick AllReduce with INT4 quantization reduces prefill TTFT.
QK-norm + RoPE + cache quant fusion improves Qwen3-MoE kernel performance.
Kimi-K2-Thinking on 4 GPUs (TP4)#
From recipes/Kimi-K2-Thinking.md — an MXFP4 MoE model:
export HIP_VISIBLE_DEVICES=0,1,2,3
python -m atom.entrypoints.openai_server \
--model amd/Kimi-K2-Thinking-MXFP4 \
--trust-remote-code \
-tp 4 \
--kv_cache_dtype fp8
Combined parallelism strategies#
TP only (dense models)#
For dense models like Llama and Qwen3 (non-MoE), use pure tensor parallelism:
python -m atom.entrypoints.openai_server --model meta-llama/Meta-Llama-3-8B -tp 8
All weights are sharded across GPUs. AllReduce collectives synchronize after each RowParallelLinear.
TP + EP (MoE models)#
For MoE models, enable expert parallelism so each GPU holds a subset of experts:
python -m atom.entrypoints.openai_server --model Qwen/Qwen3-235B-A22B-Instruct-2507-FP8 -tp 8 --enable-expert-parallel
Dense layers (attention, norms) remain tensor-parallel. MoE layers distribute experts across the ep_size = tp_size GPUs. MORI all-to-all routes tokens to the correct expert owner.
TP + DP (dense throughput)#
For throughput scaling with dense models, run multiple DP replicas:
# On a node with 8 GPUs: 2 replicas, each using 4 GPUs
python -m atom.entrypoints.openai_server --model meta-llama/Meta-Llama-3-8B -tp 4 -dp 2
Each DP replica independently processes a subset of requests. The CoreManager distributes requests via a configurable load-balancing strategy (least_requests by default; see DP Request Load Balancing). Device mapping:
DP rank 0, TP ranks 0-3 –> GPUs 0-3
DP rank 1, TP ranks 0-3 –> GPUs 4-7
Formula: local_device_rank = dp_rank_local * tp_size + tp_rank
TP + DP + EP (MoE throughput)#
For MoE models with DP + EP, the expert parallel dimension spans all tp_size * dp_size devices:
python -m atom.entrypoints.openai_server \
--model Qwen/Qwen3-235B-A22B-Instruct-2507-FP8 \
-tp 4 -dp 2 \
--enable-expert-parallel
In this configuration:
Dense layers: each DP replica has TP=4 for sharding.
MoE layers: EP size =
dp_size * tp_size = 8, spreading experts across all 8 GPUs.MORI all-to-all crosses DP boundaries to route tokens to the correct expert owner.
DP attention mode#
When --enable-dp-attention is set, CoreManager flattens the TP dimension into DP:
local_engine_count = tensor_parallel_size * data_parallel_size
data_parallel_size = local_engine_count
tensor_parallel_size = 1
This means each GPU runs an independent attention computation (no TP AllReduce for attention), while MoE layers still use the full EP group across all GPUs. This can reduce communication overhead for attention-heavy workloads.
Source files#
File |
Description |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Pipeline-parallel stage loops (head / downstream) |
|
What crosses a PP stage boundary: |
|
|
8. Multi-node data parallelism#
Global DP ranks may span nodes. The node holding global DP rank 0 is the coordinator: it runs the API server and routes requests to every rank in the group, so the load balancer stays a single global scheduler rather than one independent balancer per node. Every other node hosts only its own engines and connects back.
Multi-node is inferred from the topology — data_parallel_size_local < data_parallel_size, or data_parallel_rank > 0 (ParallelConfig.is_multinode_dp).
There is no enable flag.
Flags#
Flag |
Meaning |
|---|---|
|
Global DP ranks across all nodes |
|
DP ranks on this node (default: the global size) |
|
First global rank this node owns |
|
Coordinator IP |
|
DP rendezvous port |
|
Model-runner rendezvous port |
Each has an ATOM_DP_* environment equivalent (ATOM_DP_SIZE_LOCAL,
ATOM_DP_RANK, …) for launch scripts; explicit flags win.
Set the same nonzero --data-parallel-base-port on every node. The coordinator
binds and holds the model-runner TCPStore before spawning workers; all model
runners connect as clients. On a single node, the default 0 lets the OS
allocate the port when the store starts, so there is no probe-and-release gap.
Example — 2 nodes, 4 DP ranks each, TP2#
# Node 0 (coordinator, 10.0.0.1) — serves the API
python -m atom.entrypoints.openai_server --model <model> -tp 2 \
--data-parallel-size 8 --data-parallel-size-local 4 --data-parallel-rank 0 \
--data-parallel-master-ip 10.0.0.1 --data-parallel-master-port 29500 \
--data-parallel-base-port 29501
# Node 1 — engines only, no API server
python -m atom.entrypoints.openai_server --model <model> -tp 2 \
--data-parallel-size 8 --data-parallel-size-local 4 --data-parallel-rank 4 \
--data-parallel-master-ip 10.0.0.1 --data-parallel-master-port 29500 \
--data-parallel-base-port 29501
Node 0 owns global DP ranks 0-3, node 1 owns 4-7. Each node’s local ranks
start at 0 and index its own GPUs; the global rank identifies the engine within
the whole group. Conflating the two is the classic multi-node bug — global ranks
drive process groups and expert sharding, local ranks drive GPU index, NUMA
binding, and MoRI’s gpu_per_node.
Ports#
Engine sockets are derived from the DP master port; both ends compute them
independently and must agree. With base = master_port + 100, DP rank r uses:
Port |
Purpose |
|---|---|
|
requests (ROUTER/DEALER) |
|
outputs (PULL/PUSH) |
|
control — utility commands, abort, shutdown |
All must be reachable from every node, plus the master and base rendezvous
ports. The coordinator binds 0.0.0.0 without authentication — run it only
on a trusted cluster fabric.
Mismatched --data-parallel-master-port between nodes yields disjoint port
plans and a startup that hangs rather than errors: the coordinator waits
indefinitely for an identity handshake that never arrives.
Restrictions#
Multi-node DP + pipeline parallel is rejected with a
ValueError. The engine-index space folds PP stages into DP ranks and the two mappings are not reconciled across nodes.PP + DP is separately unsupported (single-node assertion, pre-existing).
9. Wide expert parallelism (multi-node EP)#
EP spans dp_size * tp_size ranks globally, so a multi-node DP run produces a
multi-node EP group automatically. Requirements:
Set
--data-parallel-size-localcorrectly. It reaches MoRI asgpu_per_nodeviaFusedMoEParallelConfig.local_ep_size. A wrong value describes the wrong node topology to the all-to-all kernels.Use the mori all2all backend. The FlyDSL backend raises on internode.
Kernel selection follows aiter’s shared-memory topology probe (
all2all_manager.internode):IntraNodewithin a node,InterNodeV1with RDMA across nodes. Both the synchronous prefill handle and the TBO decode path read the same probe — previously the TBO path inferred it fromworld_size <= 8, which reads 2 nodes × 4 GPUs as intra-node and would run IntraNode kernels across a boundary with no P2P mapping.
Status and validation#
Multi-node DP and wide EP are implemented but have NOT been validated on real multi-node hardware. The
InterNodeV1MoRI path and RDMA behavior are unverified. Validate in your cluster before production use.
What is verified: single-node behavior is unchanged (global == local, IPC sockets, coordinator path), and the rank arithmetic, port planning, routing, and shutdown paths are covered by CPU tests.
atom/benchmarks/internode_dp_ep_smoke.py checks that a cross-node DP/EP
process group forms and all-reduces. It does not exercise MoRI kernels:
# On each node, with matching global parameters
python atom/benchmarks/internode_dp_ep_smoke.py \
--data-parallel-size 2 --data-parallel-size-local 1 \
--data-parallel-rank <0 or 1> --tensor-parallel-size 1 \
--data-parallel-master-ip <coordinator-ip>
Expect both nodes to report an EP group spanning all global ranks and an
ep_all_reduce_sum equal to the sum of those ranks.
10. Tensor parallelism across nodes#
One TP group may span nodes, for a model too large for one node’s GPUs at the
TP size it needs. The node that runs TP rank 0 runs the engine, the API server
and its own ranks’ workers; every other node runs only its workers
(atom/model_engine/tp_multinode.py). The engine reaches them through the same
broadcast queue and reply channels as local ranks, over TCP, and finds them
through the model-runner TCPStore on --data-parallel-master-ip /
--data-parallel-base-port.
Flags#
Flag |
Meaning |
|---|---|
|
TP ranks on this node (default: |
|
First TP rank this node owns; a multiple of the local size |
|
Address of the node that runs TP rank 0 |
|
Model-runner rendezvous port, the same nonzero value on every node |
Example — TP8 over 2 nodes of 4 GPUs#
# Node 0 (10.0.0.1): engine, API server, TP ranks 0-3
python -m atom.entrypoints.openai_server --model <model> -tp 8 \
--tensor-parallel-size-local 4 --tensor-parallel-rank 0 \
--data-parallel-master-ip 10.0.0.1 --data-parallel-base-port 29501
# Node 1: TP ranks 4-7 only
python -m atom.entrypoints.openai_server --model <model> -tp 8 \
--tensor-parallel-size-local 4 --tensor-parallel-rank 4 \
--data-parallel-master-ip 10.0.0.1 --data-parallel-base-port 29501
Start the nodes in either order. Every node must set AITER_MLA_DECODE_PS1_FLYDSL
alike; a worker node refuses a mismatch. A failed worker on either side stops
the whole group.
Timeouts#
ATOM_MULTINODE_TP_TIMEOUT_S(1800): startup waits, e.g. a worker node for the engine’s endpoints and the engine for every remote rank to subscribe.ATOM_MULTINODE_PG_TIMEOUT_S(7200): floor for the process groups’ gloo and NCCL timeouts, so a slow node’s weight load does not time them out.
Restrictions#
Rejected with a
ValueError: DP,--enable-dp-attention, PP, prefill context parallelism,--fake-eplb, RapidServe.Mono decode is refused (its peer memory is HIP IPC, which cannot reach another node), and so are barrier RPCs (the TP barrier is a local multiprocessing one).
The custom all-reduce is node-local, so collectives between nodes go through RCCL. On gfx950 also set
ATOM_USE_CUSTOM_ALL_GATHER=0.