core.inference.data_parallel_inference_coordinator.coordinator#

Module Contents#

Classes#

DataParallelInferenceCoordinator

Coordinates inference requests between clients and distributed model engines.

Data#

API#

core.inference.data_parallel_inference_coordinator.coordinator._DEFAULT_MEDIA_CACHE_AFFINITY_MAX_ENTRIES#

65536

class core.inference.data_parallel_inference_coordinator.coordinator.DataParallelInferenceCoordinator(
pipe_connection: multiprocessing.connection.Connection,
data_parallel_size: int,
tokenizer,
max_requests,
inference_coordinator_port: int | None = None,
deterministic_mode: bool = False,
block_size_tokens: int | None = None,
enable_prefix_caching: bool = False,
prefix_caching_coordinator_policy: megatron.core.inference.config.PrefixCachingCoordinatorPolicy = PrefixCachingCoordinatorPolicy.LONGEST_PREFIX,
prefix_caching_routing_alpha: float = 1.0,
prefix_cache_ttl_seconds: float = 300.0,
media_cache_coordinator_policy: megatron.core.inference.config.MediaCacheCoordinatorPolicy = MediaCacheCoordinatorPolicy.AFFINITY,
media_cache_routing_weight: float = 1.0,
vision_embedding_cache_enabled: bool = False,
schedule_output_path: str | None = None,
hostname: str | None = None,
)#

Coordinates inference requests between clients and distributed model engines.

This class acts as a central server. It uses a ZMQ ROUTER socket to manage communication flows between multiple clients and multiple data parallel ranks.

The coordinator’s main responsibilities are:

  1. Worker Registration: It waits for a specified number of data parallel ranks (representing distributed model instances) to connect and register themselves.

  2. Client Connection: It accepts connections from external clients, like InferenceClient, and performs a simple handshake.

  3. Request Forwarding: It receives inference requests from clients, assigns a unique server-side request ID, tokenizes the prompt, and forwards the request to one of the available data parallel ranks using load-balanced (and, when prefix caching is enabled, prefix-affinity-aware) routing.

  4. Response Routing: It receives completed results from the data parallel ranks and routes them back to the original client that made the request.

  5. Control Signal Broadcasting: It relays control signals (e.g., PAUSE, STOP) from a client to all connected data parallel ranks.

Message handling is split out into handlers.py: the event loop in start() dispatches each message to the handler registered for its header, so supporting a new message type requires no changes here.

.. attribute:: router_socket

The central ZMQ ROUTER socket for all communication.

Type:

zmq.Socket

.. attribute:: data_parallel_size

The number of data parallel workers to expect.

Type:

int

.. attribute:: identities_of_data_parallel_ranks

A deque holding the ZMQ identities of connected data parallel instances, used for request routing.

Type:

deque

.. attribute:: request_id_to_client_id

Maps server-side request IDs to the ZMQ identity of the client that initiated the request.

Type:

dict

.. attribute:: request_id_to_client_request_id

Maps server-side request IDs to the original request ID provided by the client.

Type:

dict

.. attribute:: next_request_id

A counter for generating unique server-side request IDs.

Type:

int

Initialization

Initializes the inference coordinator.

This sets up the ZMQ context and a ROUTER socket, binding it to the given port. It then enters a blocking loop to wait for all expected data parallel ranks to connect before proceeding.

Parameters:
  • pipe_connection (Connection) – A connecting pipe to the parent process.

  • data_parallel_size (int) – The number of data parallel instances that are expected to connect.

  • tokenizer – The tokenizer to use for prompt tokenization and detokenization.

  • inference_coordinator_port (Optional[int]) – The TCP port number to bind the server to.

  • prefix_cache_ttl_seconds (float) – How long a routed block is assumed to still be held by the engine it was routed to.

  • prefix_caching_routing_alpha (float) – How hard to penalise load when routing on prefix affinity: score = cache_score - alpha * relative_load, measured against the fleet mean. Dimensionless and not capped at 1.

  • media_cache_coordinator_policy (MediaCacheCoordinatorPolicy) – Routing policy for media-cache affinity.

  • media_cache_routing_weight (float) – Estimated vision-encoder cost in units of one cached prompt block, used for multimodal routing.

  • vision_embedding_cache_enabled (bool) – Whether engines retain reusable projected media embeddings.

  • max_requests (int) – Max concurrent requests per rank, used to cap load balancing and to gate media affinity on spare capacity.

CoordinatorState#

None

get_least_loaded_data_parallel_rank()#

Selects the data parallel rank with the fewest in-flight requests.

Ties are broken by lowest rank index for deterministic behavior.

Returns:

The ZMQ identity of the least-loaded data parallel rank.

Return type:

bytes

_update_media_affinity(media_cache_key: str, identity: bytes) → None#

Record the rank most recently assigned a generated media key.

_register_rank_identity(identity)#

Register a new rank identity in the scoring data structures.

Called when a rank dynamically connects to a running coordinator (e.g. in tests that spawn the coordinator with data_parallel_size=0 and let engines register after the fact).

_remove_engine(identity)#

Remove a disconnected engine from all routing bookkeeping. Called both during shutdown and when an engine becomes unreachable mid-operation (e.g. zmq.EHOSTUNREACH in _send_to_engine). The O(n) index-shifting and hash-table rebuild are acceptable because the number of connected engines is small; optimize only if dynamic registration/deregistration at high engine counts becomes a use case.

_send_to_engine(identity, frames)#

Send a message to an engine, removing it from the pool if unreachable.

Parameters:
  • identity – ZMQ identity of the target engine.

  • frames (list) – Raw frames to send, metadata frame first.

Returns:

True if the send succeeded, False if the engine was unreachable and removed.

_broadcast_to_engines(payload)#

Send a deserialized payload to every connected data parallel rank.

compute_request_hashes(prompt, cache_salt: str | None = None)#

Compute compact-prompt affinity hashes on CPU.

For text requests these equal the engine’s KV block hashes. For multimodal requests they are routing proxies: the coordinator does not preprocess media or expand placeholders, so the engine independently computes authoritative KV hashes from its post-expansion tokens. With a common media salt, compact-prefix matches remain a useful affinity signal because equal media have equal expansion behavior.

Callers decide whether hashes are wanted at all: computing them requires the decoded prompt, and decoding it is the cost the caller is usually trying to avoid. See handle_submit_request.

Parameters:
  • prompt – Either a string (to be tokenized) or a list of token IDs.

  • cache_salt – Optional media identity mixed into the prompt hash chain for multimodal affinity.

Returns:

List of integer routing hashes, one per complete block in the prompt.

get_best_data_parallel_rank(
request_hashes,
media_cache_key: str | None = None,
)#

Select the best DP rank based on media affinity, prefix affinity, and load.

Uses score = cache_score - alpha * relative_load, where cache_score combines reusable prefix blocks with a weighted media-cache hit, and relative_load is the rank’s in-flight count measured against the fleet mean. Both terms are normalized, so alpha is dimensionless.

Parameters:
  • request_hashes – List of block hashes for the request.

  • media_cache_key – Internally generated content key for request media.

Returns:

The ZMQ identity of the selected data parallel rank.

Return type:

bytes

_update_rank_hashes(rank_identity, request_hashes)#

Record that a rank owns the given hashes.

Parameters:
  • rank_identity – ZMQ identity of the target rank.

  • request_hashes – List of block hashes assigned to this rank.

_expire_rank_hashes(now)#

Drop hash entries no request has touched for the TTL.

The coordinator’s table is a guess about what each engine still holds: it sees blocks being routed, never blocks being evicted. Left alone the guess only gets staler, and the coordinator keeps sending requests to a rank for a prefix it dropped long ago, paying a cold prefill and passing up a rank that could have served it.

The queue is insertion-ordered, so expired entries form a prefix of it and the sweep stops at the first live one – the cost is what it evicts, not the size of the table. An entry re-routed since it was queued carries a newer timestamp than the queue entry and is left alone, which is what makes a stale duplicate harmless.

_prefix_depth_vector(hashes)#

Return each rank’s contiguous prefix depth, in blocks.

Prefix cache reuse requires an unbroken chain from the first block – each block hash chains the previous one’s digest – so a rank only benefits up to its first miss. Walking forward and dropping ranks as they miss gives each rank its true depth, and the loop exits as soon as no rank is left.

Counting forward also refuses to credit a rank for a deep block whose prefix has been evicted: that KV cannot be reused, because reaching it requires the blocks before it.

start()#

Starts the main event loop for the coordinator.

This method runs an infinite loop, continuously listening for incoming messages on the ZMQ ROUTER socket. It reads the message header and dispatches to the handler registered for it (see handlers.py). A handler that returns a truthy value stops the loop.

_handle_rank_registration(sender_identity)#

Register a data parallel rank that connected to a running coordinator.

finalize_text(finished_request: dict) → None#

Populate generated_text by detokenizing a finished request’s tokens.

The coordinator does this only when detokenize_generations is enabled. The /v1/chat/completions and /v1/completions handlers disable it, so their reply bodies pass through unchanged and the frontend detokenizes the generated token IDs while formatting the response.

Parameters:

finished_request (dict) – The serialized merged request containing the generated tokens to be detokenized. It is modified in place.

classmethod entrypoint(
pipe_connection: multiprocessing.connection.Connection,
ready_event: multiprocessing.Event,
data_parallel_size: int,
tokenizer,
max_requests,
inference_coordinator_port: int | None = None,
deterministic_mode: bool = False,
block_size_tokens: int | None = None,
enable_prefix_caching: bool = False,
prefix_caching_coordinator_policy: megatron.core.inference.config.PrefixCachingCoordinatorPolicy = PrefixCachingCoordinatorPolicy.LONGEST_PREFIX,
prefix_caching_routing_alpha: float = 1.0,
prefix_cache_ttl_seconds: float = 300.0,
media_cache_coordinator_policy: megatron.core.inference.config.MediaCacheCoordinatorPolicy = MediaCacheCoordinatorPolicy.AFFINITY,
media_cache_routing_weight: float = 1.0,
vision_embedding_cache_enabled: bool = False,
schedule_output_path: str | None = None,
hostname: str | None = None,
)#

Class method to instantiate and run the coordinator, for use in a separate process.

This method initializes the coordinator, signals a ready_event to indicate that it is fully initialized and listening, and then starts the main event loop.

Parameters:
  • pipe_connection (Connection) – A connecting pipe to the parent process.

  • ready_event (Event) – A threading or multiprocessing event object that is set() once the coordinator is ready to accept connections.

  • inference_coordinator_port (int) – The port to bind to.

  • data_parallel_size (int) – The number of expected data parallel instances.

  • deterministic_mode (bool) – Whether to enable deterministic scheduling.

  • block_size_tokens (Optional[int]) – Token block size for prefix caching hashing.

  • enable_prefix_caching (bool) – Whether prefix caching is enabled.

  • prefix_caching_coordinator_policy (PrefixCachingCoordinatorPolicy) – Routing policy.

  • schedule_output_path (Optional[str]) – Path to write scheduling decisions JSON.

  • prefix_caching_routing_alpha (float) – Weight for prefix-aware routing score.

  • media_cache_coordinator_policy (MediaCacheCoordinatorPolicy) – Routing policy for media-cache affinity.

  • media_cache_routing_weight (float) – Vision reuse cost in equivalent cached prompt blocks.

  • vision_embedding_cache_enabled (bool) – Whether engines retain reusable projected media embeddings.

  • max_requests (int) – Max concurrent requests per rank.

stop()#

Stops the inference coordinator, performing any necessary cleanup operations.