folded_result_fence.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Detach folded DSpark verify results from the verify graph's persistent buffers. Default OFF.
  2. DSV41_FOLDED_FENCE=1. On the folded path (all-greedy batches replayed from the verify CUDA graph),
  3. accept_and_finalize returns views of DsparkVerifyEpilogue's persistent buffers (out_tokens_buf,
  4. commit_lens_buf, ...). With overlap scheduling the scheduler copies them to host on its copy stream
  5. while the next step already runs, and the next verify replay can overwrite those buffers before the
  6. copy finishes (sglang#40919). Cloning them on the forward stream right after the verify, before
  7. anything else is queued, gives the copy its own memory; later replays cannot touch it. Six tensors
  8. of bs x 6 ints: negligible. Sampled batches take the eager path, which already allocates fresh
  9. tensors, and are left alone.
  10. """
  11. import os
  12. ENABLED = os.environ.get("DSV41_FOLDED_FENCE", "0").strip() not in ("0", "", "off", "false")
  13. FIELDS = ("correct_len", "bonus", "cap_trim_lens", "commit_lens", "new_seq_lens", "out_tokens")
  14. def install(module):
  15. """sglang.srt.speculative.dspark_components.dspark_verify"""
  16. if not ENABLED:
  17. return
  18. cls = getattr(module, "TargetVerifyExecutor", None)
  19. outs_cls = getattr(module, "AcceptOuts", None)
  20. if cls is None or outs_cls is None or not hasattr(cls, "accept_and_finalize"):
  21. raise RuntimeError("DSV41_FOLDED_FENCE: TargetVerifyExecutor.accept_and_finalize / AcceptOuts gone; engine drifted")
  22. if getattr(cls, "_dsv41_folded_fence", False):
  23. return
  24. cls._dsv41_folded_fence = True
  25. orig = cls.accept_and_finalize
  26. def accept_and_finalize(self, *a, **kw):
  27. outs = orig(self, *a, **kw)
  28. if not kw.get("folded_accept", False):
  29. return outs
  30. return outs_cls(**{f: getattr(outs, f).clone() for f in FIELDS})
  31. cls.accept_and_finalize = accept_and_finalize
  32. print("[folded_fence] folded DSpark results cloned off the persistent verify buffers", flush=True)