Skip to content

Commit 96ac913

Browse files
Plan and pack AsyncGRPO micro-batches with array operations (#8533)
Co-authored-by: AmineDiro <aminedirhoussi1@gmail.com>
1 parent 66233d8 commit 96ac913

2 files changed

Lines changed: 161 additions & 80 deletions

File tree

‎tests/test_async_grpo_trainer.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4261,6 +4261,35 @@ def test_cost_counts_unique_tokens_and_surviving_score_pairs(self):
42614261
row = _tree_row(self.ROWS)
42624262
assert (len(row.tokens), row.load) == (10, 15 + 12 + 11) # depths 1..5, then 3..5 and 5..6 for the branches
42634263

4264+
# 10 20 30 40 50, 10 20 30 60 70 and 10 20 30 60 80: the trie drawn in `TreeRow`'s docstring
4265+
FORKS = [[10, 20, 30, 40, 50], [10, 20, 30, 60, 70], [10, 20, 30, 60, 80]]
4266+
4267+
@pytest.mark.parametrize(
4268+
("tokens", "shared"),
4269+
[
4270+
pytest.param([10, 20, 30, 40, 50], 5, id="copy"),
4271+
pytest.param([10, 20, 30, 60, 80], 5, id="copy-of-a-fork"),
4272+
pytest.param([10, 20, 30], 2, id="prefix"), # its last 30 is keyed on no next token
4273+
pytest.param([10, 20, 30, 40, 50, 60], 4, id="extension"), # the 50 it shares ends a sample
4274+
pytest.param([10, 20, 30, 60, 90], 3, id="fork-off-a-fork"),
4275+
pytest.param([10, 21], 0, id="first-token-only"),
4276+
pytest.param([11, 20, 30], 0, id="new-root"),
4277+
],
4278+
)
4279+
def test_cost_counts_only_the_tokens_the_row_lacks(self, tokens, shared):
4280+
row = _tree_row([_tree_sample(forked, n_prompt=1) for forked in self.FORKS])
4281+
n = len(tokens)
4282+
4283+
assert row.cost(_tree_sample(tokens, n_prompt=1)) == (n * (n + 1) - shared * (shared + 1)) // 2
4284+
4285+
def test_chains_are_laid_out_depth_first(self):
4286+
packed = _tree_row([_tree_sample(forked, n_prompt=1) for forked in self.FORKS]).pack()
4287+
4288+
assert packed["input_ids"].tolist() == [10, 20, 30, 40, 50, 30, 60, 70, 60, 80]
4289+
assert packed["position_ids"].tolist() == [0, 1, 2, 3, 4, 2, 3, 4, 3, 4]
4290+
assert packed["tree_cu_seqlens_q"].tolist() == [0, 2, 5, 6, 8, 10]
4291+
assert packed["tree_segment_parents"].tolist() == [-1, 0, 0, 2, 2]
4292+
42644293
def test_groups_share_a_common_prefix(self):
42654294
rows = [_tree_sample([1, 2, 3, last], n_prompt=1, group_id=g) for g, last in ((0, 4), (1, 5))]
42664295
packed = _tree_row(rows).pack()

‎trl/trainer/async_grpo_trainer.py‎

Lines changed: 132 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
import asyncio
16+
import bisect
1617
import contextvars
1718
import copy
1819
import functools
@@ -125,55 +126,91 @@ class TreeRow:
125126
it. The trie therefore forks one token before the samples diverge, and every node has a single next-token label: a
126127
branch costs one extra token per extra branch, and the loss can go through plain per-position labels. A sample's
127128
last token is keyed on `None`, which no other sample extends, so every sample ends on a leaf.
129+
130+
The trie is stored as chains: the tokens a sample adds, from where it leaves the trie to its end, form one chain,
131+
laid out in `tokens` after the previous ones, and the chain hangs off the last node the sample shares:
132+
133+
```
134+
S0 = 10 20 30 40 50 node 0 1 2 3 4 5 6 7 8 9
135+
S1 = 10 20 30 60 70 token 10 20 30 40 50 30 60 70 60 80
136+
S2 = 10 20 30 60 80 chain └───── 0 ────┘ └── 1 ─┘ └ 2 ┘
137+
138+
┌── 30 40 50 chain_offsets = [0, 5, 8, 10]
139+
10 ── 20 ─────┤ chain_parents = [-1, 1, 5] node each chain hangs off
140+
└── 30 ──┬── 60 70 chain_depths = [0, 2, 3] depth of its first token
141+
└── 60 80
142+
```
128143
"""
129144

130145
def __init__(self):
131146
self.samples: list[dict[str, Any]] = []
132-
self.sample_nodes: list[list[int]] = [] # sample -> trie node of each of its tokens
133-
self.tokens: list[int] = [] # node -> its token
134-
self.children: list[dict[tuple[int, int | None], int]] = [] # node -> {(token, next token): child node}
135-
self.roots: dict[tuple[int, int | None], int] = {} # {(token, next token): root node}
147+
self.sample_ends: list[int] = [] # sample -> node of its last token
148+
self.tokens = np.zeros(0, dtype=np.int64) # node -> its token
149+
self.chain_offsets: list[int] = [0] # chain c holds the nodes chain_offsets[c] to chain_offsets[c + 1] - 1
150+
self.chain_parents: list[int] = [] # chain -> node it hangs off, -1 for a root
151+
self.chain_depths: list[int] = [] # chain -> depth of its first node
136152
self.groups: set[Any] = set()
137153
self.trained = 0
138154
self.load = 0
139155

156+
def _walk(self, input_ids: np.ndarray) -> tuple[int, int]:
157+
"""
158+
How many leading tokens of `input_ids` the trie holds, and the node of the last one, `-1` if none.
159+
160+
The walk compares whole chains. Since a node is also keyed on the next token, the sample shares a chain's nodes
161+
up to one before the first token that differs, then goes on along the chains hanging off the last one:
162+
163+
```
164+
chain 30 60 70
165+
sample 30 60 80 same = 2 tokens, so 1 node shared (the 30); then the chains hanging off that 30
166+
```
167+
"""
168+
depth, node = 0, -1
169+
while True:
170+
for c in np.flatnonzero(np.asarray(self.chain_parents) == node): # the chains hanging off `node`
171+
start, end = self.chain_offsets[c], self.chain_offsets[c + 1]
172+
ids = input_ids[depth : depth + end - start]
173+
match = ids == self.tokens[start : start + len(ids)]
174+
same = len(ids) if match.all() else int(match.argmin())
175+
if same == end - start and depth + same == len(input_ids):
176+
return len(input_ids), end - 1 # a copy of the sample that added this chain
177+
if same >= 2:
178+
depth, node = depth + same - 1, start + same - 2
179+
break
180+
else:
181+
return depth, node
182+
183+
def _nodes(self, end: int) -> np.ndarray:
184+
"""Node of each token of the sample ending at `end`: the chains from the root down to it."""
185+
runs = []
186+
while end != -1:
187+
c = bisect.bisect_right(self.chain_offsets, end) - 1 # the chain holding `end`
188+
runs.append(np.arange(self.chain_offsets[c], end + 1))
189+
end = self.chain_parents[c]
190+
return np.concatenate(runs[::-1])
191+
140192
def fits(self, sample: dict[str, Any], budget: int) -> bool:
141193
"""Whether the row stays within `budget` unique tokens and `budget` trained tokens with `sample` added."""
142-
input_ids = sample["input_ids"].tolist()
143-
children, shared = self.roots, 0
144-
for key in zip(input_ids, [*input_ids[1:], None], strict=True):
145-
if key not in children:
146-
break
147-
children = self.children[children[key]]
148-
shared += 1
149-
novel = len(input_ids) - shared
194+
novel = len(sample["input_ids"]) - self._walk(sample["input_ids"])[0]
150195
return len(self.tokens) + novel <= budget and self.trained + int(sample["completion_mask"].sum()) <= budget
151196

152197
def cost(self, sample: dict[str, Any]) -> int:
153198
"""Load `add(sample)` would add to the row: `depth + 1` for each of its tokens not already in the trie."""
154-
input_ids = sample["input_ids"].tolist()
155-
children, shared = self.roots, 0
156-
for key in zip(input_ids, [*input_ids[1:], None], strict=True):
157-
if key not in children:
158-
break
159-
children = self.children[children[key]]
160-
shared += 1
161-
return sum(depth + 1 for depth in range(shared, len(input_ids)))
199+
n, shared = len(sample["input_ids"]), self._walk(sample["input_ids"])[0]
200+
return (n * (n + 1) - shared * (shared + 1)) // 2 # sum of depth + 1 over depths shared..n - 1
162201

163202
def add(self, sample: dict[str, Any]) -> None:
164-
input_ids = sample["input_ids"].tolist()
165-
children = self.roots
166-
nodes = []
167-
for depth, key in enumerate(zip(input_ids, [*input_ids[1:], None], strict=True)):
168-
if key not in children:
169-
children[key] = len(self.tokens)
170-
self.tokens.append(key[0])
171-
self.children.append({})
172-
self.load += depth + 1
173-
nodes.append(children[key])
174-
children = self.children[nodes[-1]]
203+
input_ids = sample["input_ids"]
204+
self.load += self.cost(sample)
205+
shared, node = self._walk(input_ids)
206+
if shared < len(input_ids): # a copy of a sample already in the row adds no chain
207+
self.chain_parents.append(node)
208+
self.chain_depths.append(shared)
209+
self.tokens = np.concatenate([self.tokens, input_ids[shared:]])
210+
self.chain_offsets.append(len(self.tokens))
211+
node = len(self.tokens) - 1
175212
self.samples.append(sample)
176-
self.sample_nodes.append(nodes)
213+
self.sample_ends.append(node)
177214
self.groups.add(sample["group_id"])
178215
self.trained += int(sample["completion_mask"].sum())
179216

@@ -208,59 +245,74 @@ def pack(self) -> dict[str, torch.Tensor]:
208245
- `old_log_probs` (`M`), `advantages` (`M`): generator log-probability and advantage of each target.
209246
- `segment_id` (`M`): index of the sample each target came from.
210247
"""
211-
input_ids, position_ids, offsets, paths, kv_index, cu_seqlens_k = [], [], [0], [], [], [0]
248+
# Chains are laid out depth-first, each one whole. A chain is cut into segments after each node other chains
249+
# hang off; those chains follow the whole chain, the ones hanging off its last segments first:
250+
#
251+
# ┌── 30 40 50 packed 10 20 | 30 40 50 | 30 | 60 70 | 60 80
252+
# 10 ── 20 ─┤ segment └ 0 ┘ └── 1 ─┘ └2┘ └ 3 ─┘ └ 4 ┘
253+
# └── 30 ──┬── 60 70 parent -1 0 0 2 2
254+
# └── 60 80
255+
children = defaultdict(list) # node -> the chains hanging off it, in the order they were added
256+
for c, parent in enumerate(self.chain_parents):
257+
children[parent].append(c)
258+
is_branch = np.zeros(len(self.tokens), dtype=bool)
259+
is_branch[[node for node in children if node != -1]] = True
260+
packed = np.empty(len(self.tokens), dtype=np.int64) # node -> its packed position
261+
input_ids, position_ids, offsets, paths, cu_seqlens_k = [], [], [0], [], [0]
212262
parents, depths = [], []
213-
packed = [0] * len(self.tokens)
214-
stack = [(node, None, 0) for node in reversed(self.roots.values())]
263+
stack = [(c, -1) for c in reversed(children[-1])] # (chain, segment it follows)
215264
while stack:
216-
node, parent, depth = stack.pop()
217-
segment = len(paths)
218-
start = len(input_ids)
219-
parents.append(-1 if parent is None else parent)
220-
depths.append(0 if parent is None else depths[parent] + 1)
221-
while True:
222-
packed[node] = len(input_ids)
223-
input_ids.append(self.tokens[node])
224-
position_ids.append(depth)
225-
depth += 1
226-
if len(self.children[node]) != 1:
227-
break
228-
node = next(iter(self.children[node].values()))
229-
offsets.append(len(input_ids))
230-
paths.append((paths[parent] if parent is not None else []) + list(range(start, len(input_ids))))
231-
kv_index.extend(paths[-1])
232-
cu_seqlens_k.append(len(kv_index))
233-
stack.extend((child, segment, depth) for child in reversed(self.children[node].values()))
265+
c, parent = stack.pop()
266+
start, end, depth = self.chain_offsets[c], self.chain_offsets[c + 1], self.chain_depths[c]
267+
packed[start:end] = np.arange(offsets[-1], offsets[-1] + end - start)
268+
input_ids.append(self.tokens[start:end])
269+
position_ids.append(np.arange(depth, depth + end - start))
270+
for last in [*(start + np.flatnonzero(is_branch[start : end - 1])).tolist(), end - 1]:
271+
segment = len(paths)
272+
parents.append(parent)
273+
depths.append(0 if parent == -1 else depths[parent] + 1)
274+
positions = np.arange(offsets[-1], packed[last] + 1)
275+
paths.append(positions if parent == -1 else np.concatenate([paths[parent], positions]))
276+
offsets.append(int(packed[last]) + 1)
277+
cu_seqlens_k.append(cu_seqlens_k[-1] + len(paths[-1]))
278+
stack.extend((child, segment) for child in reversed(children.get(last, [])))
279+
parent = segment
234280

235281
lengths = [end - start for start, end in zip(offsets[:-1], offsets[1:], strict=True)]
236-
shift_labels = [-100] * len(input_ids)
237-
sampling_mask = [[] for _ in input_ids]
282+
shift_labels = np.full(len(packed), -100)
283+
# A position shared by several samples takes the candidate set of the last one, like its label
284+
owner = np.zeros(len(packed), dtype=np.int64) # position -> sample that labels it
285+
owner_token = np.zeros(len(packed), dtype=np.int64) # position -> that sample's token it predicts
286+
counts = np.zeros(len(packed), dtype=np.int64) # position -> size of its candidate set
238287
num_logprobs = max(sample["sampler_ids"].shape[1] for sample in self.samples)
239-
sampler_ids = np.full((len(input_ids), num_logprobs), -1, dtype=np.int64)
240-
sampler_log_probs = np.full((len(input_ids), num_logprobs), -math.inf, dtype=np.float32)
288+
sampler_ids = np.full((len(packed), num_logprobs), -1, dtype=np.int64)
289+
sampler_log_probs = np.full((len(packed), num_logprobs), -math.inf, dtype=np.float32)
241290
token_index, old_log_probs, advantages, segment_id = [], [], [], []
242-
for i, (sample, nodes) in enumerate(zip(self.samples, self.sample_nodes, strict=True)):
243-
ids, mask, logps = (sample[key].tolist() for key in ("input_ids", "completion_mask", "old_log_probs"))
244-
first = len(token_index)
245-
for p in range(1, len(nodes)):
246-
if mask[p]:
247-
shift_labels[packed[nodes[p - 1]]] = ids[p]
248-
sampling_mask[packed[nodes[p - 1]]] = sample["sampling_mask"][p]
249-
token_index.append(packed[nodes[p - 1]])
250-
old_log_probs.append(logps[p])
251-
advantages.append(sample["advantage"])
252-
segment_id.append(i)
291+
for i, (sample, end) in enumerate(zip(self.samples, self.sample_ends, strict=True)):
253292
trained = np.flatnonzero(sample["completion_mask"][1:]) + 1
254-
sampler_ids[token_index[first:], : sample["sampler_ids"].shape[1]] = sample["sampler_ids"][trained]
255-
sampler_log_probs[token_index[first:], : sample["sampler_ids"].shape[1]] = sample["sampler_log_probs"][
256-
trained
257-
]
293+
index = packed[self._nodes(end)[trained - 1]]
294+
shift_labels[index] = sample["input_ids"][trained]
295+
owner[index], owner_token[index] = i, trained
296+
sizes = np.fromiter(map(len, sample["sampling_mask"]), dtype=np.int64, count=len(sample["sampling_mask"]))
297+
counts[index] = sizes[trained]
298+
sampler_ids[index, : sample["sampler_ids"].shape[1]] = sample["sampler_ids"][trained]
299+
sampler_log_probs[index, : sample["sampler_ids"].shape[1]] = sample["sampler_log_probs"][trained]
300+
token_index.append(index)
301+
old_log_probs.append(sample["old_log_probs"][trained])
302+
advantages.append(np.full(len(trained), sample["advantage"]))
303+
segment_id.append(np.full(len(trained), i))
304+
kv_index = np.concatenate(paths)
305+
sampled = np.flatnonzero(counts)
306+
candidates = (
307+
self.samples[i]["sampling_mask"][p]
308+
for i, p in zip(owner[sampled].tolist(), owner_token[sampled].tolist(), strict=True)
309+
)
258310
return {
259-
"input_ids": torch.tensor(input_ids),
260-
"position_ids": torch.tensor(position_ids),
311+
"input_ids": torch.tensor(np.concatenate(input_ids)),
312+
"position_ids": torch.tensor(np.concatenate(position_ids)),
261313
"shift_labels": torch.tensor(shift_labels),
262-
"sampling_mask": torch.tensor(list(chain.from_iterable(sampling_mask)), dtype=torch.long),
263-
"sampling_mask_counts": torch.tensor(list(map(len, sampling_mask))),
314+
"sampling_mask": torch.tensor(list(chain.from_iterable(candidates)), dtype=torch.long),
315+
"sampling_mask_counts": torch.from_numpy(counts),
264316
"sampler_ids": torch.from_numpy(sampler_ids),
265317
"sampler_log_probs": torch.from_numpy(sampler_log_probs),
266318
"tree_kv_index": torch.tensor(kv_index, dtype=torch.long),
@@ -272,10 +324,10 @@ def pack(self) -> dict[str, torch.Tensor]:
272324
[max(lengths), max(map(len, paths)), len(kv_index), sum(-(-length // 64) for length in lengths)]
273325
+ [depths.count(depth) for depth in range(max(depths) + 1)]
274326
),
275-
"token_index": torch.tensor(token_index, dtype=torch.long),
276-
"old_log_probs": torch.tensor(old_log_probs, dtype=torch.float32),
277-
"advantages": torch.tensor(advantages, dtype=torch.float32),
278-
"segment_id": torch.tensor(segment_id, dtype=torch.long),
327+
"token_index": torch.tensor(np.concatenate(token_index), dtype=torch.long),
328+
"old_log_probs": torch.tensor(np.concatenate(old_log_probs), dtype=torch.float32),
329+
"advantages": torch.tensor(np.concatenate(advantages), dtype=torch.float32),
330+
"segment_id": torch.tensor(np.concatenate(segment_id), dtype=torch.long),
279331
}
280332

281333

0 commit comments

Comments
 (0)