-
Notifications
You must be signed in to change notification settings - Fork 387
[feat][SFT] Support multiple datasets for training and evaluation in SFTTrainer #1883
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
avigyabb
wants to merge
2
commits into
NovaSky-AI:main
Choose a base branch
from
avigyabb:sft-multi-dataset
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+991
−276
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,118 +1,25 @@ | ||
| """Reference custom sampler: weighted data mixing for ``SFTTrainer``. | ||
| """Deprecated location: ``DataMixingSampler`` is now part of core SkyRL. | ||
|
|
||
| Like ``curriculum_sampler.py``, this is an *example* of a user-supplied stateful | ||
| sampler plugged into ``SFTTrainer`` via ``sampler=custom`` -- it is intentionally | ||
| NOT part of the core library. Point ``sampler_class_path`` at this class via a | ||
| dotted path importable from the repo root (run from the repo root; no | ||
| ``__init__.py`` needed thanks to namespace packages), passing the sampler | ||
| config as overrides on the base SFT example script:: | ||
| Weighted multi-dataset mixing no longer requires a custom sampler -- configure it | ||
| natively via the list-based dataset fields, e.g.:: | ||
|
|
||
| bash examples/train/sft/run_sft_megatron.sh \ | ||
| sampler=custom \ | ||
| sampler_class_path=examples.train.sft.data_mixing_sampler.DataMixingSampler \ | ||
| 'sampler_kwargs={lengths: [80, 20], weights: [0.5, 0.5], num_samples: 40, seed: 42}' | ||
|
|
||
| (``lengths`` must sum to the dataset size -- 100 for the script's | ||
| ``train[:100]`` split -- and ``num_samples`` should be | ||
| ``num_steps * batch_size``.) | ||
|
|
||
| Note: the import happens inside a Ray task, which does not inherit the driver's | ||
| ``PYTHONPATH`` -- so the path must resolve from the worker's ``sys.path`` | ||
| (which includes the repo root when launching from it). | ||
|
|
||
| It mixes a concatenation of sources (``ConcatDataset([src_a, src_b, ...])``) | ||
| according to per-source ``weights``, using torch's native | ||
| ``WeightedRandomSampler`` for the weighted draw. Because each source's weight is | ||
| divided across its examples, the *source-level* mixing proportion matches | ||
| ``weights`` regardless of how many examples each source has. | ||
| 'train_datasets=[allenai/tulu-3-sft-mixture,yahma/alpaca-cleaned]' \ | ||
| 'train_dataset_splits=[train[:50000],train[:10000]]' \ | ||
| 'train_dataset_weights=[0.8,0.2]' | ||
|
|
||
| With multiple ``train_datasets`` and the default ``sampler=random``, the trainer | ||
| uses :class:`skyrl.train.dataset.samplers.DataMixingSampler` automatically, | ||
| configured with the tokenized per-dataset lengths and ``train_dataset_weights``. | ||
|
|
||
| This module re-exports the core class so existing configs pointing | ||
| ``sampler_class_path`` here keep working. Note a behavior change from the old | ||
| example: the core sampler draws a *fresh* weighted plan every epoch (the example | ||
| replayed one fixed plan), and its ``state_dict`` now includes the generator | ||
| state so mid-epoch checkpoint resume is exact. Old position-only checkpoints | ||
| load with a warning. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Iterator, List, Optional, Sequence | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| class DataMixingSampler(torch.utils.data.Sampler[int]): | ||
| """Weighted multi-source sampler built on ``WeightedRandomSampler``. | ||
|
|
||
| The dataset is a concatenation of sources with sizes ``lengths`` (in order); | ||
| ``weights`` gives a sampling weight per source. Per-example weights are set to | ||
| ``weight_source / size_source`` so each *source* is sampled in proportion to | ||
| its weight independent of its size. A deterministic plan of ``num_samples`` | ||
| indices is materialized up front from ``seed`` via | ||
| ``torch.utils.data.WeightedRandomSampler``, so iteration is reproducible and a | ||
| single ``position`` cursor is sufficient for checkpoint/resume. | ||
|
|
||
| Args: | ||
| data_source: The (concatenated) training dataset; only its length is used. | ||
| lengths: Size of each source, in the order they appear in the dataset. | ||
| weights: Per-source sampling weight (need not sum to 1; relative scale matters). | ||
| num_samples: Total number of indices to emit. Set to | ||
| ``num_steps * batch_size`` to cover the whole run in one pass (keeps | ||
| the sampler state intact across epoch boundaries and makes resume | ||
| bit-exact across the entire run). Defaults to ``len(data_source)``. | ||
| seed: Seed for the deterministic weighted draw. | ||
| replacement: Whether to sample with replacement (passed through to | ||
| ``WeightedRandomSampler``; mixing across sources generally wants True). | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| data_source: Sequence, | ||
| lengths: Sequence[int], | ||
| weights: Sequence[float], | ||
| num_samples: Optional[int] = None, | ||
| seed: int = 0, | ||
| replacement: bool = True, | ||
| ): | ||
| self.data_source = data_source | ||
| n = len(data_source) | ||
| if sum(lengths) != n: | ||
| raise ValueError(f"DataMixingSampler: sum(lengths)={sum(lengths)} must equal len(data_source)={n}.") | ||
| if len(weights) != len(lengths): | ||
| raise ValueError(f"DataMixingSampler: weights ({len(weights)}) and lengths ({len(lengths)}) must align.") | ||
| if any(length <= 0 for length in lengths): | ||
| raise ValueError(f"DataMixingSampler: all lengths must be > 0, got {list(lengths)}.") | ||
| if any(w < 0 for w in weights) or sum(weights) <= 0: | ||
| raise ValueError( | ||
| f"DataMixingSampler: weights must be non-negative with a positive sum, got {list(weights)}." | ||
| ) | ||
|
|
||
| self.num_samples = num_samples if num_samples is not None else n | ||
| if self.num_samples <= 0: | ||
| raise ValueError(f"DataMixingSampler: num_samples must be > 0, got {self.num_samples}.") | ||
| self.position = 0 | ||
|
|
||
| # Spread each source's weight across its examples so the source-level | ||
| # mixing proportion matches ``weights`` regardless of source size. | ||
| per_example_weights: List[float] = [] | ||
| for length, weight in zip(lengths, weights): | ||
| per_example_weights.extend([weight / length] * length) | ||
|
|
||
| generator = torch.Generator() | ||
| generator.manual_seed(seed) | ||
| weighted = torch.utils.data.WeightedRandomSampler( | ||
| per_example_weights, | ||
| num_samples=self.num_samples, | ||
| replacement=replacement, | ||
| generator=generator, | ||
| ) | ||
| self._plan: List[int] = list(weighted) | ||
|
|
||
| def __iter__(self) -> Iterator[int]: | ||
| while self.position < len(self._plan): | ||
| idx = self._plan[self.position] | ||
| self.position += 1 | ||
| yield idx | ||
| self.position = 0 | ||
|
|
||
| def __len__(self) -> int: | ||
| return len(self._plan) | ||
|
|
||
| def state_dict(self) -> dict: | ||
| return {"position": self.position} | ||
| from skyrl.train.dataset.samplers import DataMixingSampler | ||
|
|
||
| def load_state_dict(self, state: dict) -> None: | ||
| self.position = state["position"] | ||
| __all__ = ["DataMixingSampler"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| #!/bin/bash | ||
| set -x | ||
|
|
||
| # SFT training on a weighted mixture of multiple datasets (Megatron backend). | ||
| # | ||
| # Trains on Tulu3 + Alpaca-Cleaned mixed 80/20 per batch (independent of the | ||
| # dataset sizes) via the core DataMixingSampler, and evaluates on held-out | ||
| # slices of both datasets separately. Eval metrics are logged per dataset under | ||
| # eval/{name}/loss (names from eval_dataset_names). | ||
| # | ||
| # Note the quoting: OmegaConf list overrides must be a single shell argument. | ||
| # | ||
| # Usage: | ||
| # bash examples/train/sft/run_sft_megatron_multi_dataset.sh [extra overrides...] | ||
| # | ||
| # Example: | ||
| # bash examples/train/sft/run_sft_megatron_multi_dataset.sh num_steps=20 'train_dataset_weights=[0.5,0.5]' | ||
|
|
||
| uv run --isolated --extra megatron \ | ||
| python -m skyrl.train.main_sft \ | ||
| strategy=megatron \ | ||
| model.path=Qwen/Qwen2.5-0.5B-Instruct \ | ||
| "train_datasets=['allenai/tulu-3-sft-mixture','yahma/alpaca-cleaned']" \ | ||
| "train_dataset_splits=['train[:800]','train[:200]']" \ | ||
| "train_dataset_weights=[0.8,0.2]" \ | ||
| "eval_datasets=['allenai/tulu-3-sft-mixture','yahma/alpaca-cleaned']" \ | ||
| "eval_dataset_splits=['train[-100:]','train[200:300]']" \ | ||
| "eval_dataset_names=[tulu3,alpaca]" \ | ||
|
Comment on lines
+23
to
+28
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For my understanding: train_datasets="['allenai/tulu-3-sft-mixture','yahma/alpaca-cleaned']" \ |
||
| eval_interval=5 \ | ||
| messages_key=messages \ | ||
| max_length=512 \ | ||
| num_steps=10 \ | ||
| batch_size=4 \ | ||
| micro_train_batch_size_per_gpu=1 \ | ||
| remove_microbatch_padding=true \ | ||
| seed=42 \ | ||
| optimizer_config.lr=1e-6 \ | ||
| optimizer_config.weight_decay=1e-2 \ | ||
| optimizer_config.max_grad_norm=1.0 \ | ||
| optimizer_config.num_warmup_steps=0 \ | ||
| optimizer_config.scheduler=constant_with_warmup \ | ||
| placement.num_nodes=1 \ | ||
| placement.num_gpus_per_node=4 \ | ||
| megatron_config.tensor_model_parallel_size=1 \ | ||
| megatron_config.pipeline_model_parallel_size=1 \ | ||
| megatron_config.context_parallel_size=1 \ | ||
| logger=console \ | ||
| project_name=skyrl_sft \ | ||
| run_name=skyrl_sft_megatron_multi_dataset_run \ | ||
| ckpt_path="" \ | ||
| ckpt_interval=0 \ | ||
| resume_from="" \ | ||
| "$@" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just remove it?