Skip to content
Merged
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
44 changes: 33 additions & 11 deletions collectivex/bench/ep_harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import math
import os
import re
import statistics

from ep_oracle import (
MODE_ALLOWED_SEMANTICS,
Expand Down Expand Up @@ -140,9 +141,18 @@ def _pcts(xs):
"p95": percentile(xs, 95), "p99": percentile(xs, 99)} if xs else None)


# Consumer contract, not labels: the frontend keys the headline on
# `components.pair_period` carrying exactly CHAIN_PERIOD_ORIGIN, so a typo fails silently.
CHAIN_PERIOD_ORIGIN = "chained-median"
def _error_for_max(value):
"""An error magnitude for a MAX reduction: NaN would vanish from one, so it reads as infinity."""
return 0.0 if value is None else value if math.isfinite(value) else math.inf


def _recorded_error(value):
"""JSON has no infinity: an error that is not finite is written as null beside its failed verdict."""
return value if value is None or math.isfinite(value) else None


# The period's level is the span chain's time per pair; its spread is the pair windows'.
CHAIN_PERIOD_ORIGIN = "chained-span-median"
Comment thread
Oseltamivir marked this conversation as resolved.
Resolved
CHAIN_FLOOR_ORIGIN = "chained-cross-rank-min"
CUDA_GRAPH_ORIGIN = "cuda-graph-replay"

Expand Down Expand Up @@ -279,7 +289,8 @@ class Point:
counts the samples whose start some rank held until its throttled host recovered, and
`host_stalled` the samples some rank's host ran throttled around anyway; `suspect` counts the
samples that were missed or stalled, once. The chained family runs on its own trials:
`chain`/`chain_spread` are per-iteration, `gap` and `settle` one scalar per trial;
`chain`/`chain_spread` are per-iteration, `gap`, `settle` and `window_overhead` one scalar per
trial;
`chain_host_retries` and `chain_host_stalled` count, for a dispatch that waits on the host, the
chain siblings restarted for a throttled host and the trials still throttled after the last
restart (None elsewhere).
Expand Down Expand Up @@ -316,6 +327,7 @@ class Point:
combine_floor: list = field(default_factory=list)
gap: list = field(default_factory=list)
settle: list = field(default_factory=list)
window_overhead: list = field(default_factory=list)
missed: dict = field(default_factory=dict)
host_held: dict = field(default_factory=dict)
host_stalled: dict = field(default_factory=dict)
Expand Down Expand Up @@ -549,8 +561,14 @@ def _sample_chain(self):
point.chain_output_error = max(point.chain_output_error, error)
pair = chained["pair"]
median, spread = self.reduce.median_spread(pair)
point.chain += median
# An event node costs device time, so a window around each pair reads above the
# pairs of the span chain, which has no event between them. The span sets the
# level; the windows, shifted onto it, keep the pair-to-pair spread.
level = statistics.median(self.reduce.scalars(chained["span"]))
overhead = _pcts(median)["p50"] - level
point.chain += [value - overhead for value in median]
point.chain_spread += spread
point.window_overhead.append(overhead)
# Per-op floors: cross-rank MIN only, since chained windows park each rank's wait.
point.dispatch_floor += self.reduce.vec(chained["dispatch"], MIN)
point.combine_floor += self.reduce.vec(chained["combine"], MIN)
Expand Down Expand Up @@ -581,7 +599,7 @@ def _final_oracle(self, point):
and point.graph_ok
)
point.max_rel = max(
report["max_elementwise_relative_error"] or 0.0
_error_for_max(report["max_elementwise_relative_error"])
for report in (point.oracle_pre, point.oracle_post, point.oracle_chain)
)

Expand Down Expand Up @@ -619,12 +637,12 @@ def _correctness(self, point):
# The chain's own final output vs a drained pair: proves the last pair of each chain,
# never the interior ones. Read beside the error, never alone.
"chain_last_output_passed": chain_passed,
"chain_last_output_error": chain_error,
"chain_last_output_error": _recorded_error(chain_error),
# The full oracle against the state the chain left behind (a fresh pair afterwards).
"post_chain_state_passed": post_chain_state_passed,
"cuda_graph_output_rewritten": graph_rewritten,
"cuda_graph_last_output_passed": graph_passed,
"cuda_graph_last_output_error": graph_error,
"cuda_graph_last_output_error": _recorded_error(graph_error),
"max_relative_error": None, # filled after `passed` below keeps collective order
"oracle_passed": oracle_passed,
"oracle_failed_checks": oracle_failed_checks,
Expand Down Expand Up @@ -668,7 +686,7 @@ def measured(samples, pcts=None):
recv_min = reduce.integer(received, ops.MIN)
global_ok = reduce.integer(point.local_ok, ops.MIN)
correctness = self._correctness(point)
correctness["max_relative_error"] = reduce.vec([point.max_rel], ops.MAX)[0]
correctness["max_relative_error"] = _recorded_error(reduce.vec([point.max_rel], ops.MAX)[0])
correctness["passed"] = point_ok = bool(global_ok) and recv_total > 0
dispatch_bytes, combine_bytes, roundtrip_bytes = self._bytes(rstats["routed_copies"])
# The wire basis is a property of the RECEIVE (MoRI's LL kernels deduplicate where the other
Expand All @@ -687,12 +705,13 @@ def measured(samples, pcts=None):
"dispatch": measured(point.dispatch, dp),
"isolated_sum": _component(pub(isum), 0, derived=True),
# What a decode loop pays per MoE layer: the steady-state period of back-to-back
# pairs, cross-rank median. Do not sum it.
# pairs with no event between them, cross-rank median. Do not sum it.
"pair_period": _component(chainp, len(point.chain), origin=CHAIN_PERIOD_ORIGIN),
"roundtrip": measured(point.roundtrip, rtp),
"stage": _component(sp, len(point.stage)),
},
# The last-entering rank's op windows from the floors chain; tracks kernel time ~10%.
# The last-entering rank's op windows from the floors chain. Each holds its events'
# own cost, so the two can sum to more than the pair period.
"chain_floor_us": {
"combine": _component(_pcts(point.combine_floor), len(point.combine_floor), origin=CHAIN_FLOOR_ORIGIN),
"dispatch": _component(_pcts(point.dispatch_floor), len(point.dispatch_floor), origin=CHAIN_FLOOR_ORIGIN),
Expand All @@ -702,6 +721,9 @@ def measured(samples, pcts=None):
"interpair_gap_us": _component(_pcts(point.gap), len(point.gap)),
"pair_spread_us": _component(_pcts(point.chain_spread), len(point.chain_spread)),
"settle_drift_us": _component(_pcts(point.settle), len(point.settle)),
# What an event window around one pair adds: the windowed median minus the span
# chain's time per pair.
"window_overhead_us": _component(_pcts(point.window_overhead), len(point.window_overhead)),
# Dispatch that waits on the host only (null elsewhere): siblings restarted for a
# throttled host, and trials still throttled after the last restart.
"host_retried_siblings": point.chain_host_retries,
Expand Down
70 changes: 55 additions & 15 deletions collectivex/bench/ep_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,17 @@ def _series(starts, ends, drop):
return [start.elapsed_time(end) * 1000.0 for start, end in zip(starts[drop:], ends[drop:])]


def _chain_result(pair, floors, drop, combined):
def _span_us(start, end, kept):
"""Time per kept pair (us) of a chain with no event between its pairs."""
return start.elapsed_time(end) * 1000.0 / kept


def _chain_result(pair, floors, span, drop, combined):
pair_start, pair_end = pair
return {
"pair": _series(pair_start, pair_end, drop),
"start_to_start": _series(pair_start[:-1], pair_start[1:], drop),
"span": span,
"dispatch": _series(*floors["dispatch"], drop),
"combine": _series(*floors["combine"], drop),
# The period chain's final output, cloned post-sync so the caller can compare it against a
Expand Down Expand Up @@ -347,10 +353,13 @@ def staged_dispatch():
raise RuntimeError(f"unknown timed component {name!r}")

def chain(self, problem, staged, iters, drop):
"""A floors chain (op windows only), then a period chain (one outer window per pair).
"""A floors chain (op windows only), a span chain (one window around every kept pair), then
a period chain (one outer window per pair).

Two siblings because per-op events inside a pair land the host's record() cost in the pair
window: six events per pair published a +10-30us host constant on every vendor.
Separate siblings because per-op events inside a pair land the host's record() cost in the
pair window: six events per pair published a +10-30us host constant on every vendor. An
event also costs device time of its own, so the pair windows read above pairs that run
with nothing between them; the span chain times those and sets the period's level.
Events are allocated before the loops so no allocation lands inside a window.

Each sibling opens with the all-reduce alone. A spin in front would let the host queue a
Expand All @@ -369,6 +378,7 @@ def events():

floors = {"dispatch": (events(), events()), "combine": (events(), events())}
pair = (events(), events())
span_start, span_end = (torch.cuda.Event(enable_timing=True) for _ in range(2))
out = {}

def floors_chain():
Expand All @@ -384,6 +394,19 @@ def floors_chain():
b.combine(problem, handle)
floors["combine"][1][i].record()

def span_chain():
for kept in (False, True):
if kept:
span_start.record()
for _ in range(iters - drop if kept else drop):
handle = b.dispatch(problem)
if staged is None:
b.stage(problem, handle)
else:
handle.combine_input = staged
b.combine(problem, handle)
span_end.record()

def period_chain():
for i in range(iters):
pair[0][i].record()
Expand All @@ -403,7 +426,7 @@ def period_chain():
collecting = gc.isenabled()
gc.disable()
try:
for sibling in (floors_chain, period_chain):
for sibling in (floors_chain, span_chain, period_chain):
for attempt in range(self.CHAIN_RETRIES + 1):
if gated:
self.gate.hold()
Expand All @@ -419,7 +442,8 @@ def period_chain():
finally:
if collecting:
gc.enable()
result = _chain_result(pair, floors, drop, out["combined"])
span = _span_us(span_start, span_end, iters - drop)
result = _chain_result(pair, floors, span, drop, out["combined"])
result["host_retries"] = retries if gated else None
result["host_stalled"] = bool(stalled) if gated else None
return result
Expand Down Expand Up @@ -531,9 +555,10 @@ def host_stalls(self):
def components(self):
return ["roundtrip", "dispatch", "combine"]

def capture_pairs(self, problem, staged, pairs, marks):
def capture_pairs(self, problem, staged, pairs, marks, span_head=0):
"""Capture `pairs` back-to-back pairs into one graph; `marks` picks the windows that get
event nodes ("pair", "dispatch", "combine"). Returns (graph, {mark: (starts, ends)},
event nodes: "pair", "dispatch" and "combine" one per pair, "span" a single window from
before pair `span_head` to after the last pair. Returns (graph, {mark: (starts, ends)},
last combined output, last dispatch handle)."""
import torch
import torch.distributed as dist
Expand All @@ -544,7 +569,8 @@ def capture_pairs(self, problem, staged, pairs, marks):
self._all_reduce()
if self.spin_cycles is None:
self.calibrate_spin()
stamps = {mark: ([graph_event() for _ in range(pairs)], [graph_event() for _ in range(pairs)])
stamps = {mark: tuple([graph_event() for _ in range(1 if mark == "span" else pairs)]
for _ in range(2))
for mark in marks}

def record(mark, edge, i):
Expand All @@ -567,6 +593,8 @@ def record(mark, edge, i):
torch.cuda._sleep(self.spin_cycles)
dist.all_reduce(self._align_token)
for i in range(pairs):
if i == span_head:
record("span", 0, 0)
record("pair", 0, i)
record("dispatch", 0, i)
handle = b.dispatch(problem)
Expand All @@ -576,6 +604,7 @@ def record(mark, edge, i):
combined = b.combine(problem, handle)
record("combine", 1, i)
record("pair", 1, i)
record("span", 1, 0)
torch.cuda.synchronize()
return graph, stamps, combined, handle

Expand Down Expand Up @@ -617,18 +646,29 @@ def component(self, name, problem, warmup, iters):

def chain(self, problem, staged, iters, drop):
"""Each sibling is ONE graph of `iters` unrolled pairs, the shape of a decode graph, replayed
once untimed (upload) and once timed, with alignment captured before the first event."""
once untimed (upload) and once timed, with alignment captured before the first event. The
span sibling holds two event nodes, around the kept pairs: an event node costs device time
of its own, so a window around every pair reads above the pairs of a graph without them."""
import torch

def replay_twice(graph):
for _ in range(2):
graph.replay()
torch.cuda.synchronize()

self.calibrate_spin()
# Replayed and released before the other two are captured, so no more chain graphs are
# ever alive at once than the floors and period siblings.
graph, stamps, _, _ = self.capture_pairs(problem, staged, iters, ("span",), span_head=drop)
replay_twice(graph)
(span_start,), (span_end,) = stamps["span"]
span = _span_us(span_start, span_end, iters - drop)
del graph
floors, floor_stamps, _, _ = self.capture_pairs(problem, staged, iters, ("dispatch", "combine"))
period, period_stamps, combined, _ = self.capture_pairs(problem, staged, iters, ("pair",))
for graph in (floors, period):
graph.replay()
torch.cuda.synchronize()
graph.replay()
torch.cuda.synchronize()
result = _chain_result(period_stamps["pair"], floor_stamps, drop, combined)
replay_twice(graph)
result = _chain_result(period_stamps["pair"], floor_stamps, span, drop, combined)
result["host_retries"] = result["host_stalled"] = None
return result

Expand Down
6 changes: 3 additions & 3 deletions collectivex/configs/swap_sweep.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,21 @@
"block_bytes": [257, 4096, 65536, 262144],
"num_blocks": [1, 4, 16, 64, 256, 1024, 2048],
"warmup": 4,
"iterations": 100,
"iterations": 40,
"max_payload_bytes": 2147483648
},
"standard": {
"block_bytes": [4096, 65536, 1048576],
"num_blocks": [1, 4, 16, 64, 256, 1024, 2048],
"warmup": 32,
"iterations": 100,
"iterations": 40,
"max_payload_bytes": 2147483648
},
"large-blocks": {
"block_bytes": [257, 4096, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824],
"num_blocks": [1, 4, 16, 64, 256, 1024, 2048],
"warmup": 4,
"iterations": 100,
"iterations": 40,
"max_payload_bytes": 1073741824
}
}
Expand Down
Loading
Loading