Skip to content

Fix megatron_server returning the wrong request's log-probs after a worker retry - #2593

Open
Davids048 wants to merge 1 commit into
THUDM:mainfrom
Davids048:fix/megatron-server-batch-id-ledger
Open

Davids048 wants to merge 1 commit into
THUDM:mainfrom
Davids048:fix/megatron-server-batch-id-ledger

Conversation

@Davids048

Copy link
Copy Markdown

Summary

In the Megatron teacher server (slime/backends/megatron_utils/server/megatron_server.py), each DP rank runs a Ray
task (run_megatron_dp_models_loop_worker) that pulls batches from SampleManager and sends them to the Megatron
model actors. If that worker process dies while batches are in flight, Ray automatically retries the task on the same
rank. After the restart, every HTTP 200 /generate response on that rank silently returns another request's log-probs.

The dead worker's in-flight entries in SampleManager are never cleared until the server restarts. As a result, every
later response on that rank stays shifted, the last requests hang without an answer, and inflight_size never returns
to 0. Because inflight_size stays above 0, /update_weights_from_disk also waits until it times out.

This PR changes SampleManager to track in-flight batches in a dict keyed by batch_id instead of a FIFO deque. Each
worker run also registers a fresh attempt ID on startup via start_worker. Therefore, when a worker restarts,
SampleManager returns HTTP 500 for the lost in-flight requests instead of letting them hang, ignores late calls from
the dead worker, and returns each later request's own log-probs.

Root Cause

In slime/backends/megatron_utils/server/megatron_server.py:

  1. Matching results only by queue order: SampleManager.get_input_data(worker_id) appended each dispatched batch's
    metadata to a deque (self._inflight[worker_id]) and returned only data_refs, with no batch_id.
  2. A retried worker starts with an empty local queue: Each DP rank runs run_megatron_dp_models_loop_worker to
    pull batches from SampleManager, dispatch them to the Megatron model actors, and save back the log-probs. Because
    it is a @ray.remote(num_cpus=0) task, Ray retries it up to 3 times by default (max_retries=3) if its process
    dies unexpectedly (for example, from an OOM kill, preemption, or node loss). Suppose requests R0 and R1 are in
    flight when the worker dies. The retried worker starts with the same worker_id = f"rank_{dp_rank}" and an empty
    local futures_queue = deque(), while SampleManager still keeps R0 and R1 at the front of
    self._inflight[worker_id].
  3. popleft() saves every later result under the wrong request: Next, the retried worker pulls R2, so
    self._inflight["rank_0"] becomes [R0, R1, R2]. When it finishes R2 and calls
    save_log_probs("rank_0", outputs_of_R2), SampleManager calls popleft(), pops R0, and saves R2's log-probs
    as R0's answer. Every later popleft() stays off by the number of lost batches. In addition, calls that the dead
    worker sent before dying can still arrive after the new worker starts.

Fix

All production changes are in slime/backends/megatron_utils/server/megatron_server.py:

  1. Register each worker run with a unique attempt ID (SampleManager.start_worker):
    • On startup, run_megatron_dp_models_loop_worker creates a unique attempt = uuid.uuid4().hex and waits for
      ray.get(sample_manager.start_worker.remote(worker_id, attempt)) before pulling work.
    • SampleManager.start_worker(worker_id, attempt) records the active attempt in self._attempts[worker_id],
      removes all batches left in flight for that worker, and saves a clear restart error in self._failed[rid] for
      every real (non-dummy) request that was not canceled.
    • SampleManager.get_result(request_id) raises RuntimeError for entries in self._failed, so waiting /generate
      handlers return HTTP 500 instead of hanging forever. cancel_request also clears self._failed.
    • SampleManager.get_input_data(worker_id, attempt) checks self._attempts.get(worker_id) != attempt and returns
      None for older attempts. Therefore, a call already sent by the dead worker cannot take a new request.
  2. Track in-flight batches in a dict keyed by batch_id:
    • Change self._inflight from defaultdict(deque) to defaultdict(dict) mapping
      worker_id -> {batch_id: batch_info}, using an incrementing counter (self._next_batch_id). Update get_loads()
      to iterate over queue.values().
    • get_input_data(worker_id, attempt) now returns (batch_id, data_refs). run_megatron_dp_models_loop_worker
      stores (batch_id, logp_parts_refs) in futures_queue and passes batch_id to
      save_log_probs(worker_id, batch_id, outputs).
    • save_log_probs(worker_id, batch_id, outputs) pops that exact batch_id via
      self._inflight.get(worker_id, {}).pop(batch_id, None). If the batch is already gone (for example, from a late
      save_log_probs call sent by an older worker), it logs a message and returns [] without touching any other
      request.

We fail those lost in-flight requests with HTTP 500 instead of re-queuing them automatically. We do this because one of
those requests may have caused the crash (for example, an oversized input that triggered an OOM kill). Callers can
safely retry the request if needed.

1-GPU Verification

We verified the fix on a 1-GPU Megatron teacher server running Qwen2.5-0.5B-Instruct on Ray. In each run, we sent
12 /generate requests. We ran 3 normal runs and 3 fault runs where we sent SIGKILL to the process running
run_megatron_dp_models_loop_worker while 2 batches were in flight, causing Ray to retry it in a new process:

Build Scenario HTTP 200 answers Mismatched answers (another request's log-probs) Lost requests inflight_size at end
Unpatched main Worker killed mid-flight 10 6 to 7 of 10 per run (all responses after retry) 2 hung forever Stuck at 2
Unpatched main Normal run 12 0 0 0
Patched (this PR) Worker killed mid-flight 10 0 (every HTTP 200 answer matches its own input) 2 failed cleanly with HTTP 500 0
Patched (this PR) Normal run 12 0 0 0

In the unpatched fault runs, 3 to 4 requests finished before the kill and 2 were in flight when the worker died. After
the retry, every single one of the 6 to 7 remaining responses was shifted by 2 spots. Each mismatched HTTP 200 response
differed from its own expected log-probs by about 2.5 to 3.0 per token on average, while matching the request 2 spots
later within about 0.04 to 0.06 (normal GPU variance). With this fix, every HTTP 200 response matched its own input
with 0 mismatches, the 2 lost requests returned HTTP 500 instead of hanging, and inflight_size returned to 0.

Tests and CI

  • Added: tests/utils/test_megatron_server_ledger.py (NUM_GPUS = 0, CPU-only unit tests running the real
    SampleManager and run_megatron_dp_models_loop_worker with a fake Ray handle that runs calls synchronously):
    • test_retried_loop_answers_each_request_with_its_own_log_probs: simulates worker attempt 1 dying with one request
      in flight, then starts attempt 2 to serve the next request. It checks that get_loads() counts the in-flight
      request before the restart, that the next request gets the log-probs computed from its own input tokens, and that
      the lost request raises a RuntimeError containing "restarted". Afterward, it checks that inflight_size and
      running_tokens both return to 0.
    • test_calls_from_a_replaced_loop_attempt_are_ignored: checks that late get_input_data and save_log_probs calls
      from an older attempt return None / [] without taking pending requests or corrupting the active attempt's
      results.
    • test_canceled_lost_request_clears_failure_state: checks that cancel_request clears the saved restart error both
      when called before and after start_worker.
  • CI Registration: Added {'test_file': 'utils/test_megatron_server_ledger.py', 'num_gpus': 0} under
    cpu-unittest in .github/workflows/pr-test.yml.j2 (next to utils/test_megatron_server_arguments.py), and
    regenerated .github/workflows/pr-test.yml with python .github/workflows/generate_github_workflows.py.

Regression Protection

tests/utils/test_megatron_server_ledger.py runs the real SampleManager and run_megatron_dp_models_loop_worker
loop across a simulated worker death and Ray retry. As a result, cpu-unittest will catch regressions if future
changes return to order-based matching, drop the attempt check in get_input_data, stop failing lost batches in
start_worker, or break get_loads() or cancel_request().

Local Validation Commands

Run from the repository root with PYTHONPATH=.:

python .github/workflows/generate_github_workflows.py
python -c "import yaml; yaml.safe_load(open('.github/workflows/pr-test.yml'))"

uvx ruff==0.14.7 check slime/backends/megatron_utils/server/megatron_server.py tests/utils/test_megatron_server_ledger.py
uvx autoflake==2.0.2 --check --remove-all-unused-imports slime/backends/megatron_utils/server/megatron_server.py tests/utils/test_megatron_server_ledger.py
uvx isort==5.13.2 --check --profile=black --line-length 119 --py 310 slime/backends/megatron_utils/server/megatron_server.py tests/utils/test_megatron_server_ledger.py
uvx black==24.3.0 --check --line-length 119 slime/backends/megatron_utils/server/megatron_server.py tests/utils/test_megatron_server_ledger.py

PYTHONPATH=. python tests/utils/test_megatron_server_ledger.py
PYTHONPATH=. python -m pytest -v tests/utils/test_megatron_server_ledger.py
PYTHONPATH=. python tests/utils/test_megatron_server_arguments.py
PYTHONPATH=. python -m pytest -v tests/utils/test_megatron_server_arguments.py

All lint, formatting, workflow generation, YAML parsing, and unit-test checks passed (3/3 in
test_megatron_server_ledger.py and 3/3 in test_megatron_server_arguments.py).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant