[Feat] support cp in sft trainer (#845)
* support ep tp * take parallel dims from torchtitan * fix logger * get back to what we previously supported [skip ci] * duplicate data on non dp rank * refactor parallel dims into training script * take out debug prints * implement pack functions * guard stacking in cp * add back sftdataconfig type annotation * dummy context when no cp * guard in rl because im lazy * make simpler truncate loging in stackingdataset * bucket timeout * greedy combine and pad * cover mesh dim 1 case * why none instead of empty list? * always have dp shard dim * reverse ugly workaround * Update src/prime_rl/trainer/sft/data.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com> --------- Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -199,3 +199,12 @@
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
---------------------------------------------------------------------
|
||||
Third-party code attributions
|
||||
---------------------------------------------------------------------
|
||||
|
||||
This project contains code derived from Meta Platforms, Inc.
|
||||
Licensed under the BSD-style license.
|
||||
|
||||
See individual source file headers for details.
|
||||
|
||||
@@ -68,6 +68,20 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
tp: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="The tensor parallelism size to use. If 1, then no TP will be used.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
cp: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="The context parallelism size to use. If 1, then no CP will be used.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
liger_kernel: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import logging
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from beartype import beartype as typechecker
|
||||
from jaxtyping import Float, Int, jaxtyped
|
||||
@@ -13,6 +12,7 @@ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.config import ActivationCheckpointConfig, ModelConfig
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Add filter to the standard logging module for transformers.modeling_utils to supress the
|
||||
@@ -67,17 +67,10 @@ def setup_tokenizer(config: ModelConfig) -> PreTrainedTokenizer:
|
||||
return tokenizer
|
||||
|
||||
|
||||
def setup_fsdp(model: nn.Module, config: ModelConfig):
|
||||
assert dist.get_world_size() % config.ep == 0, "World size must be divisible by EP"
|
||||
fsdp_dim = dist.get_world_size() // config.ep
|
||||
world_mesh = dist.init_device_mesh("cuda", (fsdp_dim, config.ep), mesh_dim_names=("fsdp", "ep"))
|
||||
def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
|
||||
# TODO: Lets not support EP for now.
|
||||
# (1) Im not sure how the hsdp mesh is supposed to work with EP.
|
||||
# (2) The EP implementation seems to have changes every week in TT and is unstable at the moment
|
||||
# (3) There doesnt seem to be significant MFU gains from EP in my benchmarks
|
||||
assert config.ep == 1, "EP is not supported for now"
|
||||
hsdp_mesh = world_mesh["fsdp"]
|
||||
# TODO: Support dp_replicate
|
||||
hsdp_mesh = parallel_dims.world_mesh["dp_shard_cp"]
|
||||
for layer_id, transformer_block in enumerate(model.model.layers):
|
||||
if config.reshard_after_forward:
|
||||
layer_reshard_after_forward = layer_id < len(model.model.layers) - 1
|
||||
@@ -106,9 +99,9 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
model.model.layers.register_module(layer_name, transformer_block)
|
||||
|
||||
|
||||
def setup_model(config: ModelConfig) -> nn.Module:
|
||||
def setup_model(config: ModelConfig, parallel_dims: ParallelDims) -> nn.Module:
|
||||
model = get_model(config)
|
||||
setup_fsdp(model, config)
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
if config.ac is not None:
|
||||
apply_ac(model, config.ac)
|
||||
if config.compile:
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This source code is licensed under the BSD-style license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
#
|
||||
# Modifications copyright (c) 2025 Prime Intellect, Inc.
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import cached_property
|
||||
|
||||
import torch.distributed as dist
|
||||
from torch._utils import _get_available_device_type
|
||||
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
|
||||
|
||||
from prime_rl.trainer.config import ModelConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
device_type = _get_available_device_type() or "cuda"
|
||||
|
||||
__all__ = ["ParallelDims"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParallelDims:
|
||||
dp_replicate: int
|
||||
dp_shard: int
|
||||
cp: int
|
||||
tp: int
|
||||
pp: int
|
||||
ep: int
|
||||
world_size: int
|
||||
|
||||
_world_mesh: DeviceMesh = None
|
||||
|
||||
def __post_init__(self):
|
||||
self._validate()
|
||||
|
||||
def _validate(self):
|
||||
dp_replicate, dp_shard, cp, tp, pp, ep = (
|
||||
self.dp_replicate,
|
||||
self.dp_shard,
|
||||
self.cp,
|
||||
self.tp,
|
||||
self.pp,
|
||||
self.ep,
|
||||
)
|
||||
for d in (dp_replicate, cp, tp, pp, ep):
|
||||
assert d >= 1, "Parallelism degree should be >= 1, except for dp_shard"
|
||||
|
||||
assert dp_shard == -1 or dp_shard >= 1, " dp_shard must -1 or >=1."
|
||||
if dp_shard < 0:
|
||||
self.dp_shard = dp_shard = self.world_size // (dp_replicate * cp * tp * pp)
|
||||
assert dp_shard >= 1
|
||||
|
||||
assert dp_replicate * dp_shard * cp * tp * pp == self.world_size, (
|
||||
f"Invalid parallel dims: dp_replicate({dp_replicate}) * dp_shard({dp_shard}) * "
|
||||
f"cp({cp}) * tp({tp}) * pp({pp}) != WORLD_SIZE({self.world_size})"
|
||||
)
|
||||
|
||||
if ep > 1:
|
||||
# EP would borrow all cp and some dp_shard degree
|
||||
assert ep % cp == 0 and (dp_shard * cp) % ep == 0
|
||||
|
||||
def build_mesh(self) -> DeviceMesh:
|
||||
if self.ep > 1:
|
||||
return self._build_mesh_with_ep()
|
||||
else:
|
||||
return self._build_mesh_without_ep()
|
||||
|
||||
def _build_mesh_with_ep(self) -> DeviceMesh:
|
||||
# With ep, dp_shard and ep are derived submeshes:
|
||||
# dp_shard = dp_shard_mod_ep * dp_shard_in_ep
|
||||
# ep = dp_shard_in_ep * cp
|
||||
dp_shard_mod_ep = self.dp_shard * self.cp // self.ep
|
||||
dp_shard_in_ep = self.ep // self.cp
|
||||
|
||||
dims = []
|
||||
names = []
|
||||
for d, name in zip(
|
||||
[
|
||||
self.pp,
|
||||
self.dp_replicate,
|
||||
dp_shard_mod_ep,
|
||||
dp_shard_in_ep,
|
||||
self.cp,
|
||||
self.tp,
|
||||
],
|
||||
["pp", "dp_replicate", "dp_shard_mod_ep", "dp_shard_in_ep", "cp", "tp"],
|
||||
):
|
||||
# dp_shard_mod_ep is needed even if it's 1, whose FSDP wrapping
|
||||
# helps the MoE layers do mixed precision training
|
||||
if d > 1 or name == "dp_shard_mod_ep":
|
||||
dims.append(d)
|
||||
names.append(name)
|
||||
|
||||
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
|
||||
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
# Mesh for data loading (no communication on this mesh)
|
||||
dp_mesh_dim_names = []
|
||||
# Mesh for param sharding
|
||||
dp_shard_cp_mesh_dim_names = []
|
||||
# Mesh for loss all-reduce
|
||||
dp_cp_mesh_dim_names = []
|
||||
# Mesh for ep
|
||||
ep_mesh_dim_names = []
|
||||
|
||||
if self.dp_replicate_enabled:
|
||||
dp_mesh_dim_names.append("dp_replicate")
|
||||
dp_cp_mesh_dim_names.append("dp_replicate")
|
||||
# dp_shard_mod_ep is always needed, even if it's 1
|
||||
dp_mesh_dim_names.append("dp_shard_mod_ep")
|
||||
dp_shard_cp_mesh_dim_names.append("dp_shard_mod_ep")
|
||||
dp_cp_mesh_dim_names.append("dp_shard_mod_ep")
|
||||
if "dp_shard_in_ep" in names:
|
||||
dp_mesh_dim_names.append("dp_shard_in_ep")
|
||||
dp_shard_cp_mesh_dim_names.append("dp_shard_in_ep")
|
||||
dp_cp_mesh_dim_names.append("dp_shard_in_ep")
|
||||
ep_mesh_dim_names.append("dp_shard_in_ep")
|
||||
if self.cp_enabled:
|
||||
dp_shard_cp_mesh_dim_names.append("cp")
|
||||
dp_cp_mesh_dim_names.append("cp")
|
||||
ep_mesh_dim_names.append("cp")
|
||||
|
||||
mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
mesh[tuple(ep_mesh_dim_names)]._flatten(mesh_dim_name="ep")
|
||||
|
||||
return mesh
|
||||
|
||||
def _build_mesh_without_ep(self) -> DeviceMesh:
|
||||
dims = []
|
||||
names = []
|
||||
for d, name in zip(
|
||||
[self.pp, self.dp_replicate, self.dp_shard, self.cp, self.tp],
|
||||
["pp", "dp_replicate", "dp_shard", "cp", "tp"],
|
||||
):
|
||||
if d > 1 or name == "dp_shard":
|
||||
dims.append(d)
|
||||
names.append(name)
|
||||
|
||||
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
|
||||
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
# Mesh for data loading (no communication on this mesh)
|
||||
dp_mesh_dim_names = []
|
||||
# Mesh for param sharding
|
||||
dp_shard_cp_mesh_dim_names = []
|
||||
# Mesh for loss all-reduce
|
||||
dp_cp_mesh_dim_names = []
|
||||
|
||||
if self.dp_replicate_enabled:
|
||||
dp_mesh_dim_names.append("dp_replicate")
|
||||
dp_cp_mesh_dim_names.append("dp_replicate")
|
||||
dp_mesh_dim_names.append("dp_shard")
|
||||
dp_shard_cp_mesh_dim_names.append("dp_shard")
|
||||
dp_cp_mesh_dim_names.append("dp_shard")
|
||||
if self.cp_enabled:
|
||||
dp_shard_cp_mesh_dim_names.append("cp")
|
||||
dp_cp_mesh_dim_names.append("cp")
|
||||
|
||||
if dp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_mesh_dim_names)]._flatten(mesh_dim_name="dp")
|
||||
if dp_shard_cp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_shard_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_shard_cp")
|
||||
if dp_cp_mesh_dim_names != []:
|
||||
mesh[tuple(dp_cp_mesh_dim_names)]._flatten(mesh_dim_name="dp_cp")
|
||||
|
||||
return mesh
|
||||
|
||||
@property
|
||||
def world_mesh(self) -> DeviceMesh:
|
||||
# doing late init so ParallelDims can still be used as a lightweight
|
||||
# dataclass without having to initialize the world mesh
|
||||
if self._world_mesh is None:
|
||||
self._world_mesh = self.build_mesh()
|
||||
return self._world_mesh
|
||||
|
||||
@property
|
||||
def dp_enabled(self):
|
||||
return self.dp_replicate > 1 or self.dp_shard > 1
|
||||
|
||||
@property
|
||||
def dp_replicate_enabled(self):
|
||||
return self.dp_replicate > 1
|
||||
|
||||
@property
|
||||
def dp_shard_enabled(self):
|
||||
return self.dp_shard > 1
|
||||
|
||||
@property
|
||||
def cp_enabled(self):
|
||||
return self.cp > 1
|
||||
|
||||
@property
|
||||
def dp_cp_enabled(self):
|
||||
return self.dp_enabled or self.cp_enabled
|
||||
|
||||
@property
|
||||
def fsdp_enabled(self):
|
||||
return self.dp_shard_enabled or self.cp_enabled
|
||||
|
||||
@property
|
||||
def tp_enabled(self):
|
||||
return self.tp > 1
|
||||
|
||||
@property
|
||||
def pp_enabled(self):
|
||||
return self.pp > 1
|
||||
|
||||
@property
|
||||
def ep_enabled(self):
|
||||
return self.ep > 1
|
||||
|
||||
@cached_property
|
||||
def non_data_parallel_size(self):
|
||||
return self.cp * self.tp * self.pp
|
||||
|
||||
@cached_property
|
||||
def seq_len_divisor(self):
|
||||
# Sequence Parallel requires that seq_len be divisible by TP degree.
|
||||
# https://github.com/pytorch/torchtitan/pull/640#discussion_r1849481001
|
||||
|
||||
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
|
||||
# when load balancing is enabled (by default).
|
||||
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
|
||||
return self.tp * (self.cp * 2)
|
||||
|
||||
@cached_property
|
||||
def logger(self):
|
||||
return get_logger()
|
||||
|
||||
|
||||
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
|
||||
# Initialize parallel dimensions
|
||||
parallel_dims = ParallelDims(
|
||||
dp_replicate=1,
|
||||
dp_shard=-1,
|
||||
cp=config.cp,
|
||||
tp=config.tp,
|
||||
pp=1,
|
||||
ep=config.ep,
|
||||
world_size=dist.get_world_size(),
|
||||
)
|
||||
|
||||
# Validate sequence length against parallel dimensions requirements
|
||||
if seq_len is not None and seq_len % parallel_dims.seq_len_divisor != 0:
|
||||
raise ValueError(
|
||||
f"Sequence length ({seq_len}) must be divisible by "
|
||||
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
|
||||
f"This requirement comes from context parallel (CP={config.cp}) and "
|
||||
f"tensor parallel (TP={config.tp}) configurations."
|
||||
)
|
||||
|
||||
return parallel_dims
|
||||
@@ -27,6 +27,7 @@ from prime_rl.trainer.model import (
|
||||
is_tt_moe_model,
|
||||
get_load_balance_stats,
|
||||
)
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.utils import (
|
||||
OffloadedTensor,
|
||||
@@ -64,9 +65,16 @@ def train(config: RLTrainerConfig):
|
||||
setup_torch_distributed()
|
||||
torch.set_float32_matmul_precision("high")
|
||||
|
||||
# Initialize parallel dimensions
|
||||
parallel_dims = get_parallel_dims(config.model)
|
||||
if config.model.cp > 1:
|
||||
raise ValueError(
|
||||
"CP is not supported for RL. No reason it shouldn't, we just didn't test it. If you need it, please open an issue."
|
||||
)
|
||||
|
||||
# Initialize the model and tokenizer
|
||||
logger.info(f"Initializing model and tokenizer ({config.model})")
|
||||
model = setup_model(config.model)
|
||||
model = setup_model(config.model, parallel_dims)
|
||||
tokenizer = setup_tokenizer(config.model)
|
||||
|
||||
# Set up the optimizer
|
||||
@@ -101,7 +109,7 @@ def train(config: RLTrainerConfig):
|
||||
# Initialize the logprob model
|
||||
tensor_offloaded_repository: dict[int, OffloadedTensor] = {}
|
||||
logger.info(f"Initializing logprob model ({config.model})")
|
||||
logprob_model = setup_model(config.model)
|
||||
logprob_model = setup_model(config.model, parallel_dims)
|
||||
|
||||
# Load async models from weights checkpoint if resuming from checkpoint
|
||||
if config.ckpt and config.ckpt.resume_step:
|
||||
@@ -114,7 +122,7 @@ def train(config: RLTrainerConfig):
|
||||
)
|
||||
model_config = deepcopy(config.model)
|
||||
model_config.name = model_name_or_path
|
||||
logprob_model = setup_model(model_config)
|
||||
logprob_model = setup_model(model_config, parallel_dims)
|
||||
tensor_offloaded_repository[step] = offload_model_to_cpu(logprob_model)
|
||||
|
||||
# Set up the data loader (Optionally, use a fake data loader for debugging)
|
||||
|
||||
@@ -25,6 +25,7 @@ class BaseDataConfig(BaseModel):
|
||||
num_examples: Annotated[
|
||||
int | None, Field(description="Number of examples to use from the dataset. If None, will use all examples.")
|
||||
] = None
|
||||
pack_function: Literal["cat", "stack"] = "cat"
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
@@ -149,3 +150,9 @@ class SFTTrainerConfig(BaseSettings):
|
||||
if self.monitor.wandb and self.monitor.wandb.log_extras:
|
||||
self.monitor.wandb.log_extras.samples = False
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pack_function(self):
|
||||
if self.model.cp > 1 and self.data.pack_function != "stack":
|
||||
raise ValueError("Packing function must be 'stack' when CP is enabled")
|
||||
return self
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from typing import Iterator, TypedDict
|
||||
|
||||
@@ -14,6 +15,8 @@ from prime_rl.trainer.sft.config import DataConfigType, FakeDataConfig, SFTDataC
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
STACKING_DATASET_BUCKET_TIMEOUT = 10
|
||||
|
||||
|
||||
class Sample(TypedDict):
|
||||
epoch: int # TODO: Argh, can we find a way to export epoch metainformation in a nicer way?
|
||||
@@ -108,7 +111,7 @@ class FakeDataset(StatefulIterableDataset):
|
||||
class SFTDataset(StatefulIterableDataset):
|
||||
"""A dataset wrapping a HF SFT dataset with prompt + completion format."""
|
||||
|
||||
def __init__(self, tokenizer: PreTrainedTokenizer, config: SFTDataConfig):
|
||||
def __init__(self, tokenizer: PreTrainedTokenizer, config: SFTDataConfig, non_dp_size: int = 1):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.tokenizer = tokenizer
|
||||
@@ -122,6 +125,16 @@ class SFTDataset(StatefulIterableDataset):
|
||||
if "prompt" not in self.dataset.column_names or "completion" not in self.dataset.column_names:
|
||||
raise ValueError("HF dataset must have a 'prompt' and 'completion' column for SFT")
|
||||
|
||||
# Get the data rank and world size
|
||||
worker_info = get_worker_info()
|
||||
worker_id, num_workers = 0, 1
|
||||
if worker_info is not None:
|
||||
worker_id = worker_info.id
|
||||
num_workers = worker_info.num_workers
|
||||
assert get_world().world_size % non_dp_size == 0, "world_size must be divisible by non_dp_size"
|
||||
self.data_rank = get_world().rank // non_dp_size * num_workers + worker_id
|
||||
self.data_world_size = get_world().world_size // non_dp_size * num_workers
|
||||
|
||||
# If specified, select a subset of the dataset
|
||||
if config.num_examples is not None:
|
||||
self.dataset = self.dataset.select(range(config.num_examples))
|
||||
@@ -193,8 +206,8 @@ class SFTDataset(StatefulIterableDataset):
|
||||
yield sample
|
||||
|
||||
|
||||
class PackingDataset(StatefulIterableDataset):
|
||||
"""A dataset that packs samples into a single sequence."""
|
||||
class CatDataset(StatefulIterableDataset):
|
||||
"""A dataset that concatenates samples into a single sequence with a fixed length."""
|
||||
|
||||
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
|
||||
self.dataset = dataset
|
||||
@@ -231,7 +244,91 @@ class PackingDataset(StatefulIterableDataset):
|
||||
packed_samples, seq_len = defaultdict(list), 0
|
||||
|
||||
|
||||
def collate(samples: list[Sample]) -> Batch:
|
||||
class StackDataset(StatefulIterableDataset):
|
||||
"""A dataset that stacks samples into batch with a fixed area"""
|
||||
|
||||
def __init__(self, dataset: StatefulIterableDataset, max_area: int):
|
||||
self.dataset = dataset
|
||||
self.max_area = max_area
|
||||
self.current_seq_len = 0
|
||||
assert math.log2(self.max_area).is_integer(), "max_area must be a power of 2"
|
||||
self.buckets = [[] for _ in range(int(math.log2(self.max_area)) + 1)]
|
||||
# TODO: Can we steal step from dataset?
|
||||
self.step = 0
|
||||
self.bucket_timers = [None] * len(self.buckets)
|
||||
self.bucket_timeout = STACKING_DATASET_BUCKET_TIMEOUT
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
return self.dataset.state_dict()
|
||||
|
||||
def load_state_dict(self, state_dict: dict):
|
||||
self.dataset.load_state_dict(state_dict)
|
||||
|
||||
def __iter__(self) -> Iterator[Sample]:
|
||||
for sample in self.dataset:
|
||||
# Add sample to packed samples
|
||||
len_sample = len(sample["input_ids"])
|
||||
if len_sample > self.max_area:
|
||||
for key, value in sample.items():
|
||||
if key != "epoch":
|
||||
sample[key] = sample[key][: self.max_area]
|
||||
len_sample = self.max_area
|
||||
bucket_idx = int(math.log2(len_sample - 1)) + 1
|
||||
self.buckets[bucket_idx].append(sample)
|
||||
|
||||
if self.bucket_timers[bucket_idx] is not None:
|
||||
hit_timeout = self.bucket_timers[bucket_idx] + self.bucket_timeout < self.step
|
||||
else:
|
||||
hit_timeout = False
|
||||
if (2**bucket_idx) * len(self.buckets[bucket_idx]) >= self.max_area or hit_timeout:
|
||||
if hit_timeout:
|
||||
while bucket_idx < len(self.buckets) - 1:
|
||||
if (
|
||||
2 ** (bucket_idx + 1) * (len(self.buckets[bucket_idx]) + len(self.buckets[bucket_idx + 1]))
|
||||
< self.max_area
|
||||
):
|
||||
self.buckets[bucket_idx + 1].extend(self.buckets[bucket_idx])
|
||||
self.buckets[bucket_idx] = []
|
||||
self.bucket_timers[bucket_idx] = None
|
||||
bucket_idx += 1
|
||||
else:
|
||||
break
|
||||
while (2**bucket_idx) * len(self.buckets[bucket_idx]) < self.max_area:
|
||||
dummy_sample = {}
|
||||
for key, value in sample.items():
|
||||
if key == "epoch":
|
||||
dummy_sample[key] = value
|
||||
else:
|
||||
dummy_sample[key] = [0]
|
||||
self.buckets[bucket_idx].append(dummy_sample)
|
||||
|
||||
packed_samples = defaultdict(list)
|
||||
for bucket_item in self.buckets[bucket_idx]:
|
||||
for key, value in bucket_item.items():
|
||||
if key == "epoch":
|
||||
packed_samples[key] = min(packed_samples.get(key, float("inf")), value)
|
||||
else:
|
||||
packed_samples[key].append(value + [0] * (2**bucket_idx - len(value)))
|
||||
yield packed_samples
|
||||
self.step += 1
|
||||
self.buckets[bucket_idx] = []
|
||||
self.bucket_timers[bucket_idx] = None
|
||||
else:
|
||||
if self.bucket_timers[bucket_idx] is None:
|
||||
self.bucket_timers[bucket_idx] = self.step
|
||||
|
||||
|
||||
def stack_collate(samples: list[Sample]) -> Batch:
|
||||
return {
|
||||
"input_ids": torch.tensor(samples[0]["input_ids"], dtype=torch.long, device="cuda"),
|
||||
"position_ids": torch.tensor(samples[0]["position_ids"], dtype=torch.long, device="cuda"),
|
||||
"loss_mask": torch.tensor(samples[0]["loss_mask"], dtype=torch.bool, device="cuda"),
|
||||
"target_ids": torch.tensor(samples[0]["target_ids"], dtype=torch.long, device="cuda"),
|
||||
"epoch": min([sample["epoch"] for sample in samples]),
|
||||
}
|
||||
|
||||
|
||||
def cat_collate(samples: list[Sample]) -> Batch:
|
||||
return {
|
||||
"input_ids": torch.stack([torch.tensor(sample["input_ids"]) for sample in samples], dim=0).long().to("cuda"),
|
||||
"position_ids": torch.stack([torch.tensor(sample["position_ids"]) for sample in samples], dim=0)
|
||||
@@ -243,11 +340,14 @@ def collate(samples: list[Sample]) -> Batch:
|
||||
}
|
||||
|
||||
|
||||
def setup_dataset(tokenizer: PreTrainedTokenizer, config: DataConfigType) -> StatefulIterableDataset:
|
||||
def setup_dataset(
|
||||
tokenizer: PreTrainedTokenizer, config: DataConfigType, non_dp_size: int = 1
|
||||
) -> StatefulIterableDataset:
|
||||
if config.type == "fake":
|
||||
# Shouldnt matter to handle non_dp_size if dataset is random
|
||||
return FakeDataset(tokenizer, config)
|
||||
elif config.type == "sft":
|
||||
return SFTDataset(tokenizer, config)
|
||||
return SFTDataset(tokenizer, config, non_dp_size)
|
||||
else:
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
@@ -256,5 +356,11 @@ def setup_dataloader(
|
||||
dataset: StatefulIterableDataset, tokenizer: PreTrainedTokenizer, config: DataConfigType
|
||||
) -> StatefulDataLoader:
|
||||
seq_len = config.micro_batch_size * config.seq_len
|
||||
packing_dataset = PackingDataset(dataset, seq_len)
|
||||
return StatefulDataLoader(packing_dataset, batch_size=1, collate_fn=collate)
|
||||
if config.pack_function == "stack":
|
||||
stacking_dataset = StackDataset(dataset, seq_len)
|
||||
return StatefulDataLoader(stacking_dataset, batch_size=1, collate_fn=stack_collate)
|
||||
elif config.pack_function == "cat":
|
||||
packing_dataset = CatDataset(dataset, seq_len)
|
||||
return StatefulDataLoader(packing_dataset, batch_size=1, collate_fn=cat_collate)
|
||||
else:
|
||||
raise ValueError(f"Invalid pack function: {config.pack_function}")
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import time
|
||||
from contextlib import nullcontext
|
||||
|
||||
# Import environment before any other imports
|
||||
# ruff: noqa: I001
|
||||
|
||||
import torch
|
||||
from torch.nn.functional import cross_entropy, softmax
|
||||
from torch.distributed.tensor.experimental import context_parallel
|
||||
from loguru import logger
|
||||
from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.trainer.weights import setup_weight_ckpt_manager
|
||||
@@ -19,6 +21,7 @@ from prime_rl.trainer.model import (
|
||||
is_tt_moe_model,
|
||||
get_load_balance_stats,
|
||||
)
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.sft.data import setup_dataloader, setup_dataset
|
||||
from prime_rl.trainer.utils import (
|
||||
@@ -52,9 +55,12 @@ def train(config: SFTTrainerConfig):
|
||||
setup_torch_distributed()
|
||||
torch.set_float32_matmul_precision("high")
|
||||
|
||||
# Initialize parallel dimensions
|
||||
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
|
||||
|
||||
# Initialize the model and tokenizer
|
||||
logger.info(f"Initializing model and tokenizer ({config.model})")
|
||||
model = setup_model(config.model)
|
||||
model = setup_model(config.model, parallel_dims)
|
||||
tokenizer = setup_tokenizer(config.model)
|
||||
|
||||
# Set up the optimizer
|
||||
@@ -78,7 +84,7 @@ def train(config: SFTTrainerConfig):
|
||||
|
||||
# Set up the dataset and dataloader
|
||||
logger.info(f"Initializing data ({config.data})")
|
||||
dataset = setup_dataset(tokenizer, config.data)
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp * config.model.tp)
|
||||
dataloader = setup_dataloader(dataset, tokenizer, config.data)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
@@ -136,7 +142,12 @@ def train(config: SFTTrainerConfig):
|
||||
forward_backward_start_time = time.time()
|
||||
epoch = 0
|
||||
tensors = Tensors() # Used to accumulate tensor statistics across grad acc and ranks for logging
|
||||
grad_accum_steps = config.data.batch_size // (config.data.micro_batch_size * world.world_size)
|
||||
grad_accum_steps = (
|
||||
config.data.batch_size
|
||||
* config.model.cp
|
||||
* config.model.tp
|
||||
// (config.data.micro_batch_size * world.world_size)
|
||||
)
|
||||
for micro_step in range(grad_accum_steps):
|
||||
micro_batch = next(dataiter)
|
||||
input_ids = micro_batch["input_ids"].to("cuda")
|
||||
@@ -146,38 +157,48 @@ def train(config: SFTTrainerConfig):
|
||||
epoch = micro_batch["epoch"]
|
||||
assert input_ids.shape[0] == position_ids.shape[0]
|
||||
|
||||
# Forward pass
|
||||
logits = forward(model, input_ids, position_ids).contiguous()
|
||||
B, L, V = logits.shape
|
||||
if config.model.cp > 1:
|
||||
maybe_context_parallel = context_parallel(
|
||||
parallel_dims.world_mesh["cp"],
|
||||
buffers=tuple([input_ids, position_ids, target_ids, loss_mask]),
|
||||
buffer_seq_dims=(1, 1, 1, 1),
|
||||
)
|
||||
else:
|
||||
maybe_context_parallel = nullcontext()
|
||||
|
||||
# Compute loss
|
||||
loss = cross_entropy(logits.view(-1, V), target_ids.view(-1), reduction="none").view(B, L)
|
||||
with maybe_context_parallel:
|
||||
# Forward pass
|
||||
logits = forward(model, input_ids, position_ids).contiguous()
|
||||
B, L, V = logits.shape
|
||||
|
||||
# Compute accuracy
|
||||
probs = softmax(logits, dim=-1)
|
||||
pred_ids = probs.argmax(dim=-1)
|
||||
accuracy = torch.eq(pred_ids, target_ids).float()
|
||||
# Compute loss
|
||||
loss = cross_entropy(logits.view(-1, V), target_ids.view(-1), reduction="none").view(B, L)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
for k, v in load_balance_stats.items():
|
||||
tensors[k].append(v)
|
||||
# Compute accuracy
|
||||
probs = softmax(logits, dim=-1)
|
||||
pred_ids = probs.argmax(dim=-1)
|
||||
accuracy = torch.eq(pred_ids, target_ids).float()
|
||||
|
||||
# Add tensors to tensor dict for logging purposes
|
||||
tensors["loss"].append(loss[loss_mask].detach().to("cpu"))
|
||||
tensors["accuracy"].append(accuracy[loss_mask].detach().to("cpu"))
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
for k, v in load_balance_stats.items():
|
||||
tensors[k].append(v)
|
||||
|
||||
# Mean reduction of unmasked tokens
|
||||
loss = loss[loss_mask].mean()
|
||||
# Add tensors to tensor dict for logging purposes
|
||||
tensors["loss"].append(loss[loss_mask].detach().to("cpu"))
|
||||
tensors["accuracy"].append(accuracy[loss_mask].detach().to("cpu"))
|
||||
|
||||
# Scale loss by number of gradient accumulation steps
|
||||
loss /= grad_accum_steps
|
||||
# Mean reduction of unmasked tokens
|
||||
loss = loss[loss_mask].mean()
|
||||
|
||||
# Delete logits before backward pass to avoid memory spike
|
||||
del logits
|
||||
# Scale loss by number of gradient accumulation steps
|
||||
loss /= grad_accum_steps
|
||||
|
||||
# Backward pass
|
||||
loss.backward()
|
||||
# Delete logits before backward pass to avoid memory spike
|
||||
del logits
|
||||
|
||||
# Backward pass
|
||||
loss.backward()
|
||||
|
||||
# Debug log with *local, micro step* stats
|
||||
micro_step_message = f"Micro Step {micro_step} | Loss: {tensors['loss'][-1].mean().item():.4f} | Accuracy: {tensors['accuracy'][-1].mean().item():.4f} | Dataloader Step: {dataloader.state_dict()['dataset_state']['step']}"
|
||||
|
||||
Reference in New Issue
Block a user