Rollout records are split into light metadata, used to plan the layout, and heavy per-token fields, loaded one mini-batch at a time. Implement four functions.
split_records(records, heavy_keys): each record is a dict with an integer "id", a "tokens" list and other fields; heavy_keys names the heavy fields (always including "tokens"). Return (metadata, heavy): metadata lists, in input order, each record's non-heavy fields followed by "length": len(record["tokens"]); heavy maps id to a dict of that record's heavy fields.
plan_layout(metadata, capacity, seed): visit the metadata in the order np.random.default_rng(seed).permutation(len(metadata)) (positions, not ids) and pack greedily: a sequence joins the current mini-batch unless its length would push the total above capacity, in which case a new mini-batch starts (an over-long sequence gets one of its own). Return a list of lists of ids.
iter_minibatches(layout, heavy): a generator yielding (ids, [heavy[id] for id in ids]) per mini-batch, looking heavy fields up only when that mini-batch is yielded.
dispatch(records, heavy_keys, capacity, seed): split, plan, iterate with the generator; return a dict with these keys in order:
"layout": the mini-batch id lists"batch_tokens": tokens resident per mini-batch"peak_resident_tokens": max of batch_tokens (0 if none)"eager_resident_tokens": total tokens over all records"num_minibatches"