feat: vectorize the packer's swap refinement (#4255)
## Summary - Vectorize `_refine_by_swapping` in `orchestrator/batch.py`. For each rank pair, NumPy now scores all candidate swaps at once. Before, a pure-Python loop rebuilt the load list for each candidate. - Keep the scoring `(max load, max - min load)` and the tie-break order (rank pair, left position, right position). The result is the same partition. - Take loads relative to the current max load. This keeps the int64 math in range when total FLOPs exceed int64. ## Verification - Real data: one 2048-sample batch (744 bins, 8 train ranks), replayed through `BatchPacker.pack` on CPU. - `_refine_by_swapping`: 8.2 s → 0.06 s (50 swap passes). - `BatchPacker.pack`: 17.7 s → 4.1 s. - Equivalence: the old and new versions return identical partitions on 210 random cases (various sizes and rank counts) and on the real-data input. - Overflow: a k=2 case with 4e18 weights gives the correct result. - `pytest tests/unit/orchestrator`: 132 passed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes hot-path load-balancing logic for multi-GPU micro-batch distribution; logic is complex but claimed equivalent and tested on random and overflow cases. > > **Overview** > **`_refine_by_swapping`** (used after Karmarkar–Karp in `balanced_partition` for orchestrator batch packing) is rewritten to score all candidate swaps between a rank pair with NumPy broadcasting instead of nested Python loops that rebuilt load lists per candidate. > > Scoring still minimizes **(max partition load, max − min load)** with the same tie-break order (rank pair, then left/right item index). Loads are expressed **relative to the current max** so int64 arithmetic stays in range when per-item weights (e.g. FLOP estimates) are huge. Applied swaps now **incrementally update** partition loads instead of carrying a full `new_loads` tuple. > > Behavior is intended to be **partition-equivalent** to the prior implementation, with large speedups on real pack workloads. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit b7eda0e3d676ae352b0d88604222efbe440b07f0. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
62b1791a1a
commit
87ddbcf081
@@ -95,33 +95,51 @@ def _partition_loads(weights: Sequence[int], partitions: list[list[int]]) -> lis
|
||||
|
||||
|
||||
def _refine_by_swapping(weights: Sequence[int], partitions: list[list[int]]) -> list[list[int]]:
|
||||
"""Apply the best pairwise swap until none lowers ``(max load, max - min load)``.
|
||||
|
||||
Ties go to the first swap in (rank pair, left position, right position) order.
|
||||
Loads are taken relative to the current max load, so the int64 math stays within
|
||||
the spread plus the largest weight even when total FLOPs exceed int64.
|
||||
"""
|
||||
partitions = [list(partition) for partition in partitions]
|
||||
loads = _partition_loads(weights, partitions)
|
||||
item_weights = np.asarray(weights, dtype=np.int64)
|
||||
num_partitions = len(partitions)
|
||||
no_other_max, no_other_min = np.iinfo(np.int64).min, np.iinfo(np.int64).max
|
||||
|
||||
while True:
|
||||
top = max(loads)
|
||||
relative = np.array([load - top for load in loads], dtype=np.int64)
|
||||
best_score = (0, top - min(loads))
|
||||
best_swap = None
|
||||
best_score = (max(loads), max(loads) - min(loads))
|
||||
for left_rank in range(len(partitions)):
|
||||
for right_rank in range(left_rank + 1, len(partitions)):
|
||||
for left_pos, left_idx in enumerate(partitions[left_rank]):
|
||||
for right_pos, right_idx in enumerate(partitions[right_rank]):
|
||||
new_left = loads[left_rank] - weights[left_idx] + weights[right_idx]
|
||||
new_right = loads[right_rank] - weights[right_idx] + weights[left_idx]
|
||||
new_loads = list(loads)
|
||||
new_loads[left_rank] = new_left
|
||||
new_loads[right_rank] = new_right
|
||||
score = (max(new_loads), max(new_loads) - min(new_loads))
|
||||
if score < best_score:
|
||||
best_score = score
|
||||
best_swap = (left_rank, right_rank, left_pos, right_pos, new_loads)
|
||||
for left_rank in range(num_partitions):
|
||||
for right_rank in range(left_rank + 1, num_partitions):
|
||||
others = np.delete(relative, [left_rank, right_rank])
|
||||
other_max = others.max() if len(others) else no_other_max
|
||||
other_min = others.min() if len(others) else no_other_min
|
||||
left_weights = item_weights[partitions[left_rank]][:, None]
|
||||
right_weights = item_weights[partitions[right_rank]][None, :]
|
||||
new_left = relative[left_rank] - left_weights + right_weights
|
||||
new_right = relative[right_rank] - right_weights + left_weights
|
||||
new_max = np.maximum(np.maximum(new_left, new_right), other_max)
|
||||
lowest_max = int(new_max.min())
|
||||
if lowest_max > best_score[0]:
|
||||
continue
|
||||
new_min = np.minimum(np.minimum(new_left, new_right), other_min)
|
||||
spread = np.where(new_max == lowest_max, new_max - new_min, no_other_min)
|
||||
flat = int(spread.argmin())
|
||||
score = (lowest_max, int(spread.flat[flat]))
|
||||
if score < best_score:
|
||||
best_score = score
|
||||
best_swap = (left_rank, right_rank, *divmod(flat, right_weights.shape[1]))
|
||||
if best_swap is None:
|
||||
return partitions
|
||||
|
||||
left_rank, right_rank, left_pos, right_pos, loads = best_swap
|
||||
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = (
|
||||
partitions[right_rank][right_pos],
|
||||
partitions[left_rank][left_pos],
|
||||
)
|
||||
left_rank, right_rank, left_pos, right_pos = best_swap
|
||||
left_idx, right_idx = partitions[left_rank][left_pos], partitions[right_rank][right_pos]
|
||||
partitions[left_rank][left_pos], partitions[right_rank][right_pos] = right_idx, left_idx
|
||||
loads[left_rank] += weights[right_idx] - weights[left_idx]
|
||||
loads[right_rank] += weights[left_idx] - weights[right_idx]
|
||||
|
||||
|
||||
def balanced_partition(weights: Sequence[int], num_partitions: int) -> list[list[int]]:
|
||||
|
||||
Reference in New Issue
Block a user