Repository navigation
Conversation
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
In the Megatron teacher server (
slime/backends/megatron_utils/server/megatron_server.py), each DP rank runs a Raytask (
run_megatron_dp_models_loop_worker) that pulls batches fromSampleManagerand sends them to the Megatronmodel 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
/generateresponse on that rank silently returns another request's log-probs.The dead worker's in-flight entries in
SampleManagerare never cleared until the server restarts. As a result, everylater response on that rank stays shifted, the last requests hang without an answer, and
inflight_sizenever returnsto 0. Because
inflight_sizestays above 0,/update_weights_from_diskalso waits until it times out.This PR changes
SampleManagerto track in-flight batches in a dict keyed bybatch_idinstead of a FIFO deque. Eachworker run also registers a fresh
attemptID on startup viastart_worker. Therefore, when a worker restarts,SampleManagerreturns HTTP 500 for the lost in-flight requests instead of letting them hang, ignores late calls fromthe dead worker, and returns each later request's own log-probs.
Root Cause
In
slime/backends/megatron_utils/server/megatron_server.py:SampleManager.get_input_data(worker_id)appended each dispatched batch'smetadata to a deque (
self._inflight[worker_id]) and returned onlydata_refs, with nobatch_id.run_megatron_dp_models_loop_workertopull batches from
SampleManager, dispatch them to the Megatron model actors, and save back the log-probs. Becauseit is a
@ray.remote(num_cpus=0)task, Ray retries it up to 3 times by default (max_retries=3) if its processdies unexpectedly (for example, from an OOM kill, preemption, or node loss). Suppose requests
R0andR1are inflight when the worker dies. The retried worker starts with the same
worker_id = f"rank_{dp_rank}"and an emptylocal
futures_queue = deque(), whileSampleManagerstill keepsR0andR1at the front ofself._inflight[worker_id].popleft()saves every later result under the wrong request: Next, the retried worker pullsR2, soself._inflight["rank_0"]becomes[R0, R1, R2]. When it finishesR2and callssave_log_probs("rank_0", outputs_of_R2),SampleManagercallspopleft(), popsR0, and savesR2's log-probsas
R0's answer. Every laterpopleft()stays off by the number of lost batches. In addition, calls that the deadworker 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:attemptID (SampleManager.start_worker):run_megatron_dp_models_loop_workercreates a uniqueattempt = uuid.uuid4().hexand waits forray.get(sample_manager.start_worker.remote(worker_id, attempt))before pulling work.SampleManager.start_worker(worker_id, attempt)records the activeattemptinself._attempts[worker_id],removes all batches left in flight for that worker, and saves a clear restart error in
self._failed[rid]forevery real (non-dummy) request that was not canceled.
SampleManager.get_result(request_id)raisesRuntimeErrorfor entries inself._failed, so waiting/generatehandlers return HTTP 500 instead of hanging forever.
cancel_requestalso clearsself._failed.SampleManager.get_input_data(worker_id, attempt)checksself._attempts.get(worker_id) != attemptand returnsNonefor older attempts. Therefore, a call already sent by the dead worker cannot take a new request.batch_id:self._inflightfromdefaultdict(deque)todefaultdict(dict)mappingworker_id -> {batch_id: batch_info}, using an incrementing counter (self._next_batch_id). Updateget_loads()to iterate over
queue.values().get_input_data(worker_id, attempt)now returns(batch_id, data_refs).run_megatron_dp_models_loop_workerstores
(batch_id, logp_parts_refs)infutures_queueand passesbatch_idtosave_log_probs(worker_id, batch_id, outputs).save_log_probs(worker_id, batch_id, outputs)pops that exactbatch_idviaself._inflight.get(worker_id, {}).pop(batch_id, None). If the batch is already gone (for example, from a latesave_log_probscall sent by an older worker), it logs a message and returns[]without touching any otherrequest.
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-Instructon Ray. In each run, we sent12
/generaterequests. We ran 3 normal runs and 3 fault runs where we sentSIGKILLto the process runningrun_megatron_dp_models_loop_workerwhile 2 batches were in flight, causing Ray to retry it in a new process:inflight_sizeat endmainmainIn 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_sizereturned to 0.Tests and CI
tests/utils/test_megatron_server_ledger.py(NUM_GPUS = 0, CPU-only unit tests running the realSampleManagerandrun_megatron_dp_models_loop_workerwith 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 requestin flight, then starts attempt 2 to serve the next request. It checks that
get_loads()counts the in-flightrequest before the restart, that the next request gets the log-probs computed from its own input tokens, and that
the lost request raises a
RuntimeErrorcontaining"restarted". Afterward, it checks thatinflight_sizeandrunning_tokensboth return to 0.test_calls_from_a_replaced_loop_attempt_are_ignored: checks that lateget_input_dataandsave_log_probscallsfrom an older attempt return
None/[]without taking pending requests or corrupting the active attempt'sresults.
test_canceled_lost_request_clears_failure_state: checks thatcancel_requestclears the saved restart error bothwhen called before and after
start_worker.{'test_file': 'utils/test_megatron_server_ledger.py', 'num_gpus': 0}undercpu-unittestin.github/workflows/pr-test.yml.j2(next toutils/test_megatron_server_arguments.py), andregenerated
.github/workflows/pr-test.ymlwithpython .github/workflows/generate_github_workflows.py.Regression Protection
tests/utils/test_megatron_server_ledger.pyruns the realSampleManagerandrun_megatron_dp_models_loop_workerloop across a simulated worker death and Ray retry. As a result,
cpu-unittestwill catch regressions if futurechanges return to order-based matching, drop the attempt check in
get_input_data, stop failing lost batches instart_worker, or breakget_loads()orcancel_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.pyAll lint, formatting, workflow generation, YAML parsing, and unit-test checks passed (3/3 in
test_megatron_server_ledger.pyand 3/3 intest_megatron_server_arguments.py).