Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions release_notes/fragments/24532.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pr: 24532
entries:
- category: bugfix
text: Fixed incorrect first tokens and reduced throughput on external prefix hits when serving DeepSeek-V4.1 Flash with layerwise MemCache KV pooling.
8 changes: 6 additions & 2 deletions tests/ut/distributed/ascend_store/test_kv_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,12 +553,16 @@ def record_h2d(*_args) -> int:
is_last_chunks=[False],
),
)
load_task = LayerLoadTask(wait_for_save_layers=(0,), transfer_tasks=[task], layer_id=1)
boundary = MagicMock()
boundary.synchronize.side_effect = lambda: call_order.append(("block_init", 0))
load_task = LayerLoadTask(
wait_for_save_layers=(0,), transfer_tasks=[task], layer_id=1, compute_boundary=boundary
)
thread.request_queue.put(load_task)

thread._handle_request(load_task)

self.assertEqual(call_order, [("save", 0), ("reuse", 0), ("reuse", 1), ("h2d", 1)])
self.assertEqual(call_order, [("block_init", 0), ("save", 0), ("reuse", 0), ("reuse", 1), ("h2d", 1)])

def test_empty_load_waits_for_target_layer_reuse_before_finish(self):
load_finished_observed: list[bool] = []
Expand Down
64 changes: 64 additions & 0 deletions tests/ut/distributed/ascend_store/test_pool_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,41 @@ def make_worker(
worker.sync_save_events = [MagicMock() for _ in range(6)]
return worker

def test_partial_gva_step_finishes_submitted_puts(self):
worker = self.make_worker()
metadata = AscendConnectorMetadata(set())
with patch.object(worker, "_drain_attention_transfers") as drain:
worker.current_layer = 0
worker.wait_for_save(metadata)
drain.assert_not_called()
worker.current_layer = 4
worker.wait_for_save(metadata)
drain.assert_called_once_with(drain_recv=False, full=True)
worker.current_layer = worker.num_layers
worker.wait_for_save(metadata)
drain.assert_called_once()

def test_first_gva_prefetch_carries_kv_initialization_event(self):
worker = self.make_worker()
worker.num_prefetch_layers = 0
worker.current_layer = 0
with patch.object(torch.npu, "Event") as event_factory:
worker.wait_for_layer_load()
event_factory.assert_not_called()
worker.layer_load_tasks[1] = [MagicMock()]
worker.layer_load_tasks[2] = [MagicMock()]
worker.next_layer_to_submit = 0
worker.wait_for_layer_load()
event = event_factory.return_value
event.record.assert_called_once_with()
event.synchronize.assert_not_called()
for layer in (1, 2):
worker.current_layer = layer
worker._submit_ready_layer_loads()
first, second = worker.kv_recv_thread.add_request.call_args_list
self.assertIs(first.args[0].compute_boundary, event)
self.assertIsNone(second.args[0].compute_boundary)

def test_draft_layers_are_persistent_and_outside_target_reuse(self):
worker = self.make_worker(reuse=True)
self.assertEqual(worker.num_layers, 6)
Expand Down Expand Up @@ -3607,6 +3642,35 @@ def test_mtp_gva_prepare_uses_safe_extent_not_store_skip_extent(self):
queried_keys = worker.m_store.batch_get_key_info.call_args.args[0]
self.assertEqual(len(queried_keys), 1)

def test_queued_gva_put_keeps_its_addresses_across_steps(self):
database = SimpleNamespace(
group_block_len={0: [64]},
group_kv_caches_base_addr={0: [1024]},
group_block_stride={0: [64]},
group_layer_cache_entry_offsets={0: [0, 1]},
)
builder = LayerBatchBuilder(database, page_size_bytes=64, num_layers=1)

def prepare_put(block_id, gva):
request = ReqMeta(
req_id="r",
save_end_token=128,
target_token_len=128,
block_ids_by_group=[[block_id]],
block_hashes=[b"hash"],
block_ids_by_group_np=[np.array([block_id])],
block_gvas_by_group_np=[np.array([gva])],
)
task = LayerTransferTask(layer_id=0, block_ranges=[LayerBlockRange(request, 0, 1)])
return builder.build_shared(task, is_save=True)

pending = prepare_put(3, 4096)
following = prepare_put(7, 8192)
self.assertEqual(pending.block_ids_arr.tolist(), [3])
self.assertEqual(pending.block_gvas_arr.tolist(), [4096])
self.assertEqual(following.block_ids_arr.tolist(), [7])
self.assertEqual(following.block_gvas_arr.tolist(), [8192])

def test_save_range_clamps_to_allocated_blocks(self):
for offload in (False, True):
for start_token in (768, 12288):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ def wait_for_save(self):
assert self.connector_worker is not None
worker = cast(LayerwiseKVPoolWorker, self.connector_worker)
if self.has_connector_metadata():
worker.save_dflash_draft_kv(self._get_connector_metadata())
worker.wait_for_save(self._get_connector_metadata())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

According to the Repository Style Guide (Release notes, lines 45-47), every user-facing PR must add a release notes fragment under release_notes/fragments/<PR number>.yaml following release_notes/TEMPLATE.yaml. Since this PR introduces user-facing changes (as noted in the PR description), please ensure a release notes fragment is added.

References
  1. Every user-facing PR must add release_notes/fragments/<PR number>.yaml following release_notes/TEMPLATE.yaml. (link)

return

assert self.connector_worker is not None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,13 @@ def build_shared(self, task: LayerTransferTask, is_save: bool = True) -> SharedB
if block_range.partial_block_index is not None:
total += 1

block_ids_arr, block_gvas_arr = self._ensure_buf(total)
if is_save:
# A queued put can outlive this model step. Its worker resolves the
# local blocks and destination GVAs after the next batch is built.
block_ids_arr = np.empty(total, dtype=np.int64)
block_gvas_arr = np.empty(total, dtype=np.int64)
else:
block_ids_arr, block_gvas_arr = self._ensure_buf(total)
req_ids: list[str] = []
is_last_chunks: list[bool | None] = []
all_save_keys: list[str] = []
Expand Down Expand Up @@ -1078,6 +1084,8 @@ def _copy_gva_layers(self, data: LayerLoadTask) -> bool:
transfer_tasks = data.transfer_tasks
layer_id = data.layer_id
load_gate = data.load_gate
if data.compute_boundary is not None:
data.compute_boundary.synchronize()
if not self._wait_for_reuse_saves(data):
return False

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,7 @@ def prepare_layerwise_step(self, metadata: AscendConnectorMetadata) -> None:
self._dflash_save_pending = False
self.layerwise_retrievers: list[Any] = []
self.next_layer_to_submit = 0
self._gva_load_boundary: torch.npu.Event | None = None
reset_attention_load_gate()
if self.use_kvpp:
assert self.layer_load_finished_events is not None
Expand Down Expand Up @@ -1691,6 +1692,11 @@ def submit_layer_load(layer_id: int, boundary: torch.npu.Event | None) -> bool:
and not getattr(self, "has_shared_kv", False)
):
load_gate = get_attention_load_gate()
if (gva_boundary := getattr(self, "_gva_load_boundary", None)) is not None:
# The receiving thread processes tasks in order. A single
# event on the first queued task protects the entire step.
boundary = gva_boundary
self._gva_load_boundary = None
recv_thread.add_request(
LayerLoadTask( # type: ignore[arg-type]
wait_for_save_layers=reuse_sources,
Expand Down Expand Up @@ -1777,6 +1783,16 @@ def save_dflash_draft_kv(self, metadata: AscendConnectorMetadata) -> None:
self.save_kv_layer(metadata)
self._drain_deferred_last_save()

def wait_for_save(self, metadata: AscendConnectorMetadata) -> None:
self.save_dflash_draft_kv(metadata)
if not self.use_layerwise_transfer or self.kv_send_thread is None:
return
expected_layers = (self.layerwise_key_layers or self.num_layers) if self.pp_size > 1 else self.num_layers

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

In wait_for_save, self.pp_size is accessed directly. However, throughout the rest of the file (e.g., lines 221, 403, 404), getattr(self, "pp_size", 1) is used defensively because self.pp_size is not guaranteed to be initialized or defined on self (for instance, during partial initialization in unit tests). To prevent potential AttributeError runtime crashes, please use getattr here as well.

Suggested change
expected_layers = (self.layerwise_key_layers or self.num_layers) if self.pp_size > 1 else self.num_layers
expected_layers = (self.layerwise_key_layers or self.num_layers) if getattr(self, "pp_size", 1) > 1 else self.num_layers

if 0 < self.current_layer < expected_layers:
# A chunk can skip its draft layers. The nominal final-layer
# fence then never runs, but the next step can reuse these pages.
self._drain_attention_transfers(drain_recv=False, full=True)

def _shared_read_ahead_enabled(self) -> bool:
# Only extend the window for the persistent full-attention pages.
return (
Expand All @@ -1790,6 +1806,16 @@ def wait_for_layer_load(self) -> None:
return
assert self.layer_load_finished_events is not None
assert self.kv_recv_thread is not None
if (
self.current_layer == 0
and any(self.layer_load_tasks)
and self.use_layerwise_transfer
and self.kv_role in ("kv_producer", "kv_both")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we record the first GVA load event for a kv_consumer with enable_lookup=true as well? When new KV pages need zeroing, the receiver can start its first H2D copy on a separate stream while initialization is still pending. The role check here leaves that copy without a compute-stream event. Could we base the fence on whether a load is queued and cover a load-only consumer in the first-prefetch test?

):
# The native GVA receiver has its own stream. Order its first read
# after KV block initialization while the model can keep issuing work.
self._gva_load_boundary = torch.npu.Event()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

To optimize NPU performance and reduce overhead in the hot path, it is recommended to initialize the synchronization event with enable_timing=False. This avoids the overhead of tracking elapsed time when the event is only used for stream synchronization.

Suggested change
self._gva_load_boundary = torch.npu.Event()
self._gva_load_boundary = torch.npu.Event(enable_timing=False)

self._gva_load_boundary.record()
load_gate = reset_attention_load_gate()
try:
self.kv_recv_thread.raise_if_failed()
Expand Down
Loading