Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ea35a07
refactor(worker): post-boundary page-table check takes explicit params
Andrewxu313 Dec 2, 2026
1a610e5
Merge remote-tracking branch 'origin/main' into tairan/decode-boundar…
Andrewxu313 Dec 2, 2026
6a596a5
refactor(worker): post-boundary decisions take explicit params
Andrewxu313 Dec 2, 2026
a3d0d42
chore(worker): merge main after the page-table check landed
Andrewxu313 Dec 2, 2026
f085afe
style(worker): drop placeholder-less f-string in decode_engine
Andrewxu313 Dec 3, 2026
37add4c
test(decode): match boundary-decisions fixture to F541 lint fix
Andrewxu313 Dec 3, 2026
da3db21
refactor(decode): extract step forward prep helpers with explicit params
Andrewxu313 Dec 3, 2026
b47b7e3
Merge remote-tracking branch 'origin/tairan/decode-boundary-decisions…
Andrewxu313 Dec 3, 2026
5439d9b
refactor(decode): extract forward, sampling, and KV staging helper
Andrewxu313 Dec 3, 2026
a6f0a75
refactor(decode): extract step readback and writeback helper
Andrewxu313 Dec 3, 2026
5853863
test(decode): remove unused pytest import in readback test
Andrewxu313 Dec 3, 2026
43d12d0
test(decode): re-anchor abandoned-exit AST assertions to readback helper
Andrewxu313 Dec 3, 2026
49afb28
refactor(worker): extract decode wave helpers with explicit params
Andrewxu313 Dec 3, 2026
5938d86
Merge remote-tracking branch 'origin/tairan/decode-readback-params' i…
Andrewxu313 Dec 3, 2026
fb870f4
test(decode): update closure allowlist and drain check
Andrewxu313 Dec 3, 2026
f6ffedf
Merge remote-tracking branch 'origin/main' into tairan/decode-boundar…
Andrewxu313 Dec 4, 2026
dfb33c0
Merge branch 'tairan/decode-boundary-decisions-params' into tairan/de…
Andrewxu313 Dec 4, 2026
e6d6ced
Merge branch 'tairan/decode-forward-prep-params' into tairan/decode-f…
Andrewxu313 Dec 4, 2026
51490be
Merge branch 'tairan/decode-forward-sample-params' into tairan/decode…
Andrewxu313 Dec 4, 2026
d0b64ba
Merge branch 'tairan/decode-readback-params' into tairan/decode-wave-…
Andrewxu313 Dec 4, 2026
43057a0
Merge remote-tracking branch 'origin/main' into tairan/decode-boundar…
Andrewxu313 Dec 4, 2026
4f5e219
Merge branch 'tairan/decode-boundary-decisions-params' into tairan/de…
Andrewxu313 Dec 4, 2026
fb15d3c
Merge branch 'tairan/decode-forward-prep-params' into tairan/decode-f…
Andrewxu313 Dec 4, 2026
c10f2e9
Merge branch 'tairan/decode-forward-sample-params' into tairan/decode…
Andrewxu313 Dec 4, 2026
e19cb13
Merge branch 'tairan/decode-readback-params' into tairan/decode-wave-…
Andrewxu313 Dec 4, 2026
9ebfb2f
test(worker): shrink decode_engine model-branch span budget to 334
Andrewxu313 Dec 4, 2026
999cee5
Merge branch 'tairan/decode-forward-prep-params' into tairan/decode-f…
Andrewxu313 Dec 4, 2026
e0d4e43
test(worker): shrink decode_engine model-branch span budget to 107
Andrewxu313 Dec 4, 2026
1f765a6
Merge branch 'tairan/decode-forward-sample-params' into tairan/decode…
Andrewxu313 Dec 4, 2026
59ac300
Merge branch 'tairan/decode-readback-params' into tairan/decode-wave-…
Andrewxu313 Dec 4, 2026
d1e3f31
Merge remote-tracking branch 'origin/main' into tairan/decode-wave-he…
Andrewxu313 Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
316 changes: 76 additions & 240 deletions batchgen/batchgen_worker.py

Large diffs are not rendered by default.

243 changes: 243 additions & 0 deletions batchgen/worker/decode_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -1821,6 +1821,249 @@ def complete_decode_step_readback(
)


def prepare_decode_wave_model_and_kv(
*,
rank: int,
local_rank: int,
comm: Any,
max_decode_rank_bsz: Callable[[], int],
load_decode_model: Callable[[Any], None],
init_gpu_kv_with_actual_size: Callable[[], None],
) -> None:
"""Slot 13: load decode model, log HBM footprint, and initialize GPU KV pool."""
logging.info(
f"[DECODE] Rank {rank}: entering decode configure "
f"(decode_width={max_decode_rank_bsz()})"
)
load_decode_model(comm)

if torch.cuda.is_available():
free_mem, _total_mem = torch.cuda.mem_get_info(local_rank)
allocated = torch.cuda.memory_allocated(local_rank) / 1e9
logging.info(
f"[HBM] Rank {rank} AFTER decode model: "
f"free={free_mem/1e9:.2f}GB alloc={allocated:.2f}GB"
)

init_gpu_kv_with_actual_size()


def select_and_sync_decode_wave_batch(
*,
rank: int,
global_batch: Any,
uuid_to_local_map: Mapping[str, int],
sequences_with_gpu_kv: GpuResidencySet,
prepare_decode_batch: Callable[[], List[str]],
sync_decode_uuids_tensor: Callable[[List[str]], List[str]],
sync_completion_status_tensor: Callable[[List[str]], tuple[set[str], List[str]]],
sync_sequence_metadata: Callable[[List[str]], None],
gather_completed_tokens: Callable[[List[str]], Mapping[str, Any]],
get_local_indices_for_uuids: Callable[[List[str]], List[int]],
release_gpu_kv_pages: Callable[[List[int]], None],
release_host_kv_pages_for_batch: Callable[..., None],
report_completion: Callable[..., None],
) -> List[str]:
"""Slot 14: select decode candidates, sync completions, release KV, and deliver."""
decode_uuids = prepare_decode_batch()

current_decoding = global_batch.get_sequences_by_status(SequenceStatus.IN_DECODE)
seen = set(decode_uuids)
for uuid in current_decoding:
if uuid not in seen:
decode_uuids.append(uuid)
seen.add(uuid)

decode_uuids.sort(key=lambda u: global_batch.get_sequence(u).global_idx)
decode_uuids = sync_decode_uuids_tensor(decode_uuids)
global_completed, decode_uuids = sync_completion_status_tensor(decode_uuids)

if global_completed:
sync_sequence_metadata(list(global_completed))
gathered_texts = gather_completed_tokens(list(global_completed))
completed_list = list(global_completed)
my_completed = [u for u in completed_list if u in uuid_to_local_map]
if my_completed:
gpu_allocated = [u for u in my_completed if u in sequences_with_gpu_kv]
if gpu_allocated:
release_gpu_kv_pages(get_local_indices_for_uuids(gpu_allocated))
release_host_kv_pages_for_batch(
my_completed,
remaining_decode_uuids=[
u for u in current_decoding
if u not in global_completed
],
)
for uuid in completed_list:
seq = global_batch.get_sequence(uuid)
if seq is not None:
seq.finish_and_release()
sequences_with_gpu_kv.drop(uuid)
for uuid in completed_list:
seq = global_batch.get_sequence(uuid)
if seq is not None and seq.status == SequenceStatus.COMPLETED:
report_completion(uuid, gathered_text=gathered_texts.get(uuid))
elif seq is not None:
logging.warning(
f"Rank {rank}: Skipping _report_completion for {uuid[:8]} "
f"(status={seq.status.name}, expected COMPLETED). "
"Likely stale eos_reached from pre-eviction cycle."
)

if not decode_uuids:
return []

for uuid in decode_uuids:
seq = global_batch.get_sequence(uuid)
prev_status = "ON_HOLD" if seq.had_initial_gpu_reservation else "PREFILLED"
seq.log_event(SeqEvent.DECODE_START, rank, f"from={prev_status}")

return decode_uuids


@dataclass(frozen=True, slots=True)
class DecodeWaveConfigOutcome:
local_decode_indices: List[int]
config_elapsed_s: float


def configure_decode_wave_local_rows_and_graphs(
*,
rank: int,
decode_uuids: List[str],
global_batch: Any,
decode_entry_edge: Any,
attn_wrapper_base: Any,
bind_phase_debug: Callable[..., None],
sync_sequence_metadata: Callable[[List[str]], None],
assign_decode_dp_groups: Callable[[List[str]], None],
check_local_binding_matches_group: Callable[[List[str], str], None],
restore_kda_states_for_decode: Callable[[List[str]], None],
get_local_indices_for_uuids: Callable[[List[str]], List[int]],
debug_sequences_for_decode_uuids: Callable[[List[str]], list],
adopt_debug_state: Callable[[str], None],
debug_values: Callable[[], Any],
configure_dispatch_trace: Callable[[list], None],
config_decoding_for_batch: Callable[[List[str], List[int]], None],
sync_decode_moe_rank_counts: Callable[..., Any],
bind_decode_attention_metadata_for_graph_config: Callable[[List[int]], None],
update_batch_status: Callable[[List[str], Any, Any], None],
prewarm_decode_jit: Callable[[], None],
configure_criticality_probe: Callable[[Any], None],
decode_graph_capture_needed_at_configure: Callable[[bool], bool],
warmup_cuda_graphs: Callable[[], None],
) -> DecodeWaveConfigOutcome:
"""Slot 15: bind local decode rows, configure decode metadata, and warm graphs."""
if decode_uuids:
sync_sequence_metadata(decode_uuids)

assign_decode_dp_groups(decode_uuids)
check_local_binding_matches_group(decode_uuids, "decode entry")
restore_kda_states_for_decode(decode_uuids)
local_decode_indices = get_local_indices_for_uuids(decode_uuids)
global_decode_sequences = debug_sequences_for_decode_uuids(decode_uuids)
adopt_debug_state("decode")
bind_phase_debug(
attn_wrapper_base,
batchgen_debug=debug_values(),
)
configure_dispatch_trace(global_decode_sequences)

config_start = time.perf_counter()
config_decoding_for_batch(decode_uuids, local_decode_indices)
sync_decode_moe_rank_counts(
local_decode_indices,
reason="pre_decode_warmup",
)
bind_decode_attention_metadata_for_graph_config(local_decode_indices)
config_elapsed_s = time.perf_counter() - config_start
update_batch_status(decode_uuids, SequenceStatus.IN_DECODE, decode_entry_edge)
sync_sequence_metadata(decode_uuids)

prewarm_decode_jit()
configure_criticality_probe(debug_values())

has_queueing = global_batch.has_queueing()
if decode_graph_capture_needed_at_configure(has_queueing):
if has_queueing:
logging.info(
f"Rank {rank}: warming decode CUDA graph with queued "
"prefill work still pending when the requested graph path supports it"
)
warmup_cuda_graphs()

return DecodeWaveConfigOutcome(
local_decode_indices=local_decode_indices,
config_elapsed_s=config_elapsed_s,
)


@dataclass(frozen=True, slots=True)
class DecodeWaveExitOutcome:
break_for_prefill: bool


def finalize_decode_wave_interval(
*,
rank: int,
decode_uuids: List[str],
decode_group_idx: int,
global_batch: Any,
admission_queue: Any,
enable_host_kv_eviction: bool,
multi_batch_diag: bool,
finish_decode_interval: Callable[[], None],
poll_admissions: Callable[[], Any],
check_host_kv_watermark_trigger: Callable[[], bool],
put_sequences_on_hold: Callable[[List[str]], None],
) -> DecodeWaveExitOutcome:
"""Slot 16: finish decode interval, poll admissions, and break for prefill if triggered."""
finish_decode_interval()
dist.barrier()

if admission_queue is not None:
admitted = poll_admissions()
if admitted and rank == 0:
logging.info(f"[DECODE] Mid-cycle admission, total in batch: {len(global_batch)}")

has_pending = global_batch.has_queueing() or (
enable_host_kv_eviction and global_batch.has_evicted()
)
needs_prefill = has_pending and check_host_kv_watermark_trigger()
if needs_prefill:
if rank == 0:
num_queued = len(global_batch.get_sequences_by_status(SequenceStatus.QUEUEING))
num_evicted = (
len(global_batch.get_sequences_by_status(SequenceStatus.EVICTED))
if enable_host_kv_eviction
else 0
)
logging.info(
f"[DECODE] Breaking for prefill (watermark) - {num_queued} queued, {num_evicted} evicted"
)
in_decode_uuids = [
u for u in decode_uuids
if global_batch.get_sequence(u).status == SequenceStatus.IN_DECODE
]
if multi_batch_diag and rank == 0 and in_decode_uuids:
sample = in_decode_uuids[:5]
for u in sample:
s = global_batch.get_sequence(u)
logging.info(
f"[MULTI_DIAG] ON_HOLD transition: {u[:8]} gid={s.global_idx} "
f"decoded={s.decoded_length} ctx={s.current_context_length} "
f"prompt={s.prompt_length} gpu_pages={s.gpu_pages_allocated}"
)
logging.info(
f"[MULTI_DIAG] Putting {len(in_decode_uuids)} seqs ON_HOLD (decode_group={decode_group_idx})"
)
if in_decode_uuids:
put_sequences_on_hold(in_decode_uuids)
return DecodeWaveExitOutcome(break_for_prefill=True)

return DecodeWaveExitOutcome(break_for_prefill=False)


class DecodeModelStateBinder(Protocol):
def _bind_decode_entry_model_state(
self, gpu_manager, worker_view, scale_dict, past_key_states, past_value_states, batch
Expand Down
22 changes: 17 additions & 5 deletions tests/test_worker_pool_restart.py
Original file line number Diff line number Diff line change
Expand Up @@ -2589,14 +2589,26 @@ def test_generate_carries_the_decode_exit_out_before_the_next_collective():
check = latch_checks[0]
assert [type(node) for node in check.body] == [ast.Break]

barriers = [
lineno for lineno, name in _collective_calls(decode_phase)
if name == "dist.barrier"
finalize_calls = [
node.lineno for node in ast.walk(decode_phase)
if isinstance(node, ast.Call)
and ast.unparse(node.func) == "finalize_decode_wave_interval"
]
assert barriers, "the decode phase no longer issues the cleanup barrier"
assert check.lineno < min(barriers), (
assert finalize_calls, "the decode phase no longer invokes finalize_decode_wave_interval"
assert check.lineno < min(finalize_calls), (
"the teardown break must precede the decode cleanup barrier"
)
if "run" not in _decode_engine_tree_cache:
_decode_engine_tree_cache["run"] = ast.parse(DECODE_ENGINE_PATH.read_text())
fin_fn = next(
n for n in _decode_engine_tree_cache["run"].body
if isinstance(n, ast.FunctionDef) and n.name == "finalize_decode_wave_interval"
)
barriers = [
lineno for lineno, name in _collective_calls(fin_fn)
if name == "dist.barrier"
]
assert barriers, "finalize_decode_wave_interval no longer issues the cleanup barrier"


def test_generate_outer_boundary_tests_the_latch_and_never_the_probe():
Expand Down
15 changes: 9 additions & 6 deletions tests/unit/test_decode_group_binding_invariant.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,15 +322,18 @@ def test_prefill_config_checks_bindings_after_it_creates_them():


def test_decode_entry_checks_bindings_before_resolving_local_rows():
# Unparsed (indentation-free): the decode wave's statements live inside
# the decode-phase context try block (AS3.3), so a raw-text pin on their
# tab depth would re-break on any structural change around them.
body = ast.unparse(_method("generate"))
engine_tree = ast.parse((WORKER.parent / "worker" / "decode_engine.py").read_text())
cfg_fn = next(
n for n in engine_tree.body
if isinstance(n, ast.FunctionDef)
and n.name == "configure_decode_wave_local_rows_and_graphs"
)
body = ast.unparse(cfg_fn)
check = body.index(
"self._check_local_binding_matches_group(decode_uuids, 'decode entry')"
"check_local_binding_matches_group(decode_uuids, 'decode entry')"
)
resolve = body.index(
"local_decode_indices = self._get_local_indices_for_uuids(decode_uuids)"
"local_decode_indices = get_local_indices_for_uuids(decode_uuids)"
)
assert check < resolve

Expand Down
9 changes: 5 additions & 4 deletions tests/unit/test_decode_phase_context_once.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,8 @@ def test_generate_brackets_the_decode_wave_with_enter_and_a_finally_exit():
# The entry runs after the wave's pool init: the GPU KV bind is the one
# post-setup reassignment of a context field, so it precedes the build.
before = ast.unparse(ast.Module(body=body[:index], type_ignores=[]))
assert "self._init_gpu_kv_with_actual_size()" in before
assert "prepare_decode_wave_model_and_kv(" in before
assert "init_gpu_kv_with_actual_size=self._init_gpu_kv_with_actual_size" in before
assert "self._decode_phase_context()" not in before

# The entry and the try are the LAST two statements of the wave: every
Expand All @@ -257,9 +258,9 @@ def test_generate_brackets_the_decode_wave_with_enter_and_a_finally_exit():
assert _method_calls(guarded, "decoding_continuous"), (
"the continuous decode loop runs inside the held span"
)
assert _method_calls(guarded, "_prepare_decode_batch"), (
"decode batch selection runs inside the held span"
)
assert "select_and_sync_decode_wave_batch(" in ast.unparse(guarded) and (
"prepare_decode_batch=self._prepare_decode_batch" in ast.unparse(guarded)
), "decode batch selection runs inside the held span"


def test_the_brackets_and_the_builder_have_no_other_call_site():
Expand Down
23 changes: 22 additions & 1 deletion tests/unit/test_prefix_drain_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,6 @@ def test_every_completion_site_releases_before_reporting():
}
assert set(callers) == {
"_finish_prefill_completed_sequences",
"generate",
"_decoding_legacy_modes",
}
for name, node in callers.items():
Expand All @@ -279,6 +278,28 @@ def test_every_completion_site_releases_before_reporting():
)
previous_report = report

# The decode-wave site was extracted into decode_engine.select_and_sync_decode_wave_batch.
decode_engine_tree = ast.parse(
(WORKER.parent / "worker" / "decode_engine.py").read_text()
)
select_fn = next(
node for node in decode_engine_tree.body
if isinstance(node, ast.FunctionDef)
and node.name == "select_and_sync_decode_wave_batch"
)
select_releases = sorted(
call.lineno for call in ast.walk(select_fn)
if isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
and call.func.id == "release_host_kv_pages_for_batch"
)
select_reports = sorted(
call.lineno for call in ast.walk(select_fn)
if isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
and call.func.id == "report_completion"
)
assert select_reports and select_releases
assert any(line < select_reports[0] for line in select_releases)

# The fourth site is the page boundary. Its carry-out is
# BoundaryExecutor.apply, which reports through the completion outlet the
# worker hands it (completion.report_completion is _report_completion).
Expand Down
Loading
Loading