Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions scripts/inference/text_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,15 @@
from megatron.bridge import AutoBridge
from megatron.bridge.models.hf_pretrained.utils import is_safe_repo
from megatron.bridge.training.utils.checkpoint_utils import get_hf_model_id_from_checkpoint
from megatron.bridge.utils.common_utils import disable_mtp_for_inference, get_local_rank_preinit, print_rank_0
from megatron.bridge.utils.common_utils import (
disable_mtp_for_inference,
get_local_rank_preinit,
get_master_addr_safe,
get_master_port_safe,
get_rank_safe,
get_world_size_safe,
print_rank_0,
)


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -258,11 +266,12 @@ def _maybe_initialize_distributed(timeout_minutes: int) -> None:
if not dist.is_available() or dist.is_initialized():
return

os.environ["RANK"] = os.environ.get("RANK", "0")
os.environ["WORLD_SIZE"] = os.environ.get("WORLD_SIZE", "1")
os.environ["MASTER_ADDR"] = os.environ.get("MASTER_ADDR", "localhost")
os.environ["MASTER_PORT"] = os.environ.get("MASTER_PORT", "12355")
torch.cuda.set_device(get_local_rank_preinit())
os.environ["RANK"] = os.environ.get("RANK", str(get_rank_safe()))
os.environ["WORLD_SIZE"] = os.environ.get("WORLD_SIZE", str(get_world_size_safe()))
os.environ["LOCAL_RANK"] = os.environ.get("LOCAL_RANK", str(get_local_rank_preinit()))
os.environ["MASTER_ADDR"] = os.environ.get("MASTER_ADDR", get_master_addr_safe())
os.environ["MASTER_PORT"] = os.environ.get("MASTER_PORT", str(get_master_port_safe()))
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
dist.init_process_group("nccl", timeout=timedelta(minutes=timeout_minutes))


Expand Down
85 changes: 82 additions & 3 deletions scripts/training/pack_sft_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@
"""

import argparse
import inspect
import sys
from dataclasses import fields
from pathlib import Path


def main() -> None:
Expand All @@ -38,21 +40,52 @@ def main() -> None:
parser.add_argument(
"--recipe",
required=True,
help="Recipe name, e.g. gpt_oss_20b_sft_openmathinstruct2_thinking_packed_config",
help="Recipe name for a packed-sequence SFT dataset config.",
)
parser.add_argument("--seq-length", type=int, default=None, help="Optional sequence length override.")
parser.add_argument("--hf-path", default=None, help="Optional Hugging Face model ID or local snapshot path.")
parser.add_argument(
"--train-input-path", default=None, help="Optional processed JSONL path for the training split."
)
parser.add_argument(
"--val-input-path", default=None, help="Optional processed JSONL path for the validation split."
)
parser.add_argument(
"--packed-train-data-path", default=None, help="Optional output path for packed training data."
)
parser.add_argument(
"--packed-val-data-path", default=None, help="Optional output path for packed validation data."
)
parser.add_argument("--packed-metadata-path", default=None, help="Optional output path for packing metadata.")
args = parser.parse_args()

import megatron.bridge.recipes as all_recipes
from megatron.bridge.data.builders.finetuning_dataset import FinetuningDatasetBuilder
from megatron.bridge.data.builders.hf_dataset import HFDatasetBuilder, HFDatasetConfig
from megatron.bridge.data.datasets.packed_sequence import prepare_packed_sequence_data
from megatron.bridge.training.config import DataloaderConfig
from megatron.bridge.training.tokenizers.tokenizer import build_tokenizer

recipe_fn = getattr(all_recipes, args.recipe, None)
if recipe_fn is None:
sys.exit(f"Error: recipe '{args.recipe}' not found. Check available recipes in megatron.bridge.recipes.")

cfg = recipe_fn()
sig = inspect.signature(recipe_fn)
params = sig.parameters
has_var_keyword = any(param.kind == inspect.Parameter.VAR_KEYWORD for param in params.values())
recipe_kwargs = {}
if args.seq_length is not None:
if "seq_length" in params or has_var_keyword:
recipe_kwargs["seq_length"] = args.seq_length
else:
sys.exit(f"Error: recipe '{args.recipe}' does not accept a 'seq_length' parameter.")
if args.hf_path is not None:
if "hf_path" in params or has_var_keyword:
recipe_kwargs["hf_path"] = args.hf_path
else:
sys.exit(f"Error: recipe '{args.recipe}' does not accept an 'hf_path' parameter.")

cfg = recipe_fn(**recipe_kwargs)

if cfg.dataset is None:
sys.exit("Error: recipe has no dataset configuration.")
Expand Down Expand Up @@ -87,7 +120,53 @@ def main() -> None:
},
)

# For HF datasets, download + apply process_example_fn → training.jsonl. The
custom_pack_paths = [
args.train_input_path,
args.val_input_path,
args.packed_train_data_path,
args.packed_val_data_path,
args.packed_metadata_path,
]
if any(custom_pack_paths):
if not args.train_input_path:
sys.exit("Error: --train-input-path is required when using explicit pack paths.")
if not args.packed_train_data_path:
sys.exit("Error: --packed-train-data-path is required when using explicit pack paths.")

packed_metadata_path = Path(args.packed_metadata_path) if args.packed_metadata_path else builder.pack_metadata
prepare_packed_sequence_data(
input_path=Path(args.train_input_path),
output_path=Path(args.packed_train_data_path),
output_metadata_path=packed_metadata_path,
packed_sequence_size=cfg.dataset.packed_sequence_specs.packed_sequence_size,
tokenizer=tokenizer,
max_seq_length=cfg.dataset.seq_length,
seed=cfg.dataset.seed,
dataset_kwargs=cfg.dataset.dataset_kwargs,
pad_seq_to_mult=cfg.dataset.packed_sequence_specs.pad_seq_to_mult,
num_tokenizer_workers=cfg.dataset.packed_sequence_specs.num_tokenizer_workers,
)

if args.val_input_path and args.packed_val_data_path:
prepare_packed_sequence_data(
input_path=Path(args.val_input_path),
output_path=Path(args.packed_val_data_path),
output_metadata_path=packed_metadata_path,
packed_sequence_size=cfg.dataset.packed_sequence_specs.packed_sequence_size,
tokenizer=tokenizer,
max_seq_length=cfg.dataset.seq_length,
seed=cfg.dataset.seed,
dataset_kwargs=cfg.dataset.dataset_kwargs,
pad_seq_to_mult=cfg.dataset.packed_sequence_specs.pad_seq_to_mult,
num_tokenizer_workers=cfg.dataset.packed_sequence_specs.num_tokenizer_workers,
)
elif args.val_input_path or args.packed_val_data_path:
sys.exit("Error: --val-input-path and --packed-val-data-path must be provided together.")

print("Done.")
return

# For HF datasets, download + apply process_example_fn -> training.jsonl. The
# packer in prepare_packed_data() reads that JSONL; without this step the
# cache directory is empty and packing fails with FileNotFoundError.
if isinstance(builder, HFDatasetBuilder):
Expand Down
220 changes: 220 additions & 0 deletions tests/unit_tests/scripts/test_pack_sft_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
#
# 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.

"""Unit tests for ``scripts/training/pack_sft_data.py``."""

from __future__ import annotations

import importlib.util
import sys
import types
from dataclasses import dataclass, field
from pathlib import Path
from unittest.mock import Mock

import pytest


_REPO_ROOT = Path(__file__).resolve().parents[3]
_SCRIPT_PATH = _REPO_ROOT / "scripts" / "training" / "pack_sft_data.py"


@dataclass
class _DataloaderConfig:
micro_batch_size: int = 1


@dataclass
class _PackedSequenceSpecs:
packed_sequence_size: int = 2048
pad_seq_to_mult: int = 8
num_tokenizer_workers: int = -1


@dataclass
class _DatasetConfig:
seq_length: int = 2048
seed: int = 123
dataset_kwargs: dict[str, object] = field(default_factory=lambda: {"chat": "template"})
packed_sequence_specs: _PackedSequenceSpecs | None = field(default_factory=_PackedSequenceSpecs)


@dataclass
class _RecipeConfig:
dataset: _DatasetConfig | None = field(default_factory=_DatasetConfig)
tokenizer: object = "tokenizer-config"


class _FinetuningDatasetBuilder:
pack_metadata = Path("default-pack-metadata.json")

def __init__(self, *, tokenizer: object, **kwargs: object) -> None:
self.tokenizer = tokenizer
self.kwargs = kwargs

def prepare_packed_data(self) -> None:
raise AssertionError("explicit pack-path tests should not call prepare_packed_data")


class _HFDatasetConfig:
pass


class _HFDatasetBuilder(_FinetuningDatasetBuilder):
def prepare_data(self) -> None:
raise AssertionError("explicit pack-path tests should not call prepare_data")


def _load_module():
spec = importlib.util.spec_from_file_location("pack_sft_data_under_test", _SCRIPT_PATH)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
try:
spec.loader.exec_module(module)
return module
finally:
sys.modules.pop(spec.name, None)


def _install_pack_sft_stubs(monkeypatch: pytest.MonkeyPatch, recipe_fn) -> Mock:
megatron = sys.modules.get("megatron", types.ModuleType("megatron"))
bridge = types.ModuleType("megatron.bridge")
data = types.ModuleType("megatron.bridge.data")
builders = types.ModuleType("megatron.bridge.data.builders")
datasets = types.ModuleType("megatron.bridge.data.datasets")
training = types.ModuleType("megatron.bridge.training")
tokenizers = types.ModuleType("megatron.bridge.training.tokenizers")
recipes = types.ModuleType("megatron.bridge.recipes")
recipes.unit_recipe = recipe_fn

finetuning_dataset = types.ModuleType("megatron.bridge.data.builders.finetuning_dataset")
finetuning_dataset.FinetuningDatasetBuilder = _FinetuningDatasetBuilder

hf_dataset = types.ModuleType("megatron.bridge.data.builders.hf_dataset")
hf_dataset.HFDatasetBuilder = _HFDatasetBuilder
hf_dataset.HFDatasetConfig = _HFDatasetConfig

packed_sequence = types.ModuleType("megatron.bridge.data.datasets.packed_sequence")
prepare_packed_sequence_data = Mock()
packed_sequence.prepare_packed_sequence_data = prepare_packed_sequence_data

training_config = types.ModuleType("megatron.bridge.training.config")
training_config.DataloaderConfig = _DataloaderConfig

tokenizer_module = types.ModuleType("megatron.bridge.training.tokenizers.tokenizer")
tokenizer_module.build_tokenizer = Mock(return_value="tokenizer")

monkeypatch.setitem(sys.modules, "megatron", megatron)
monkeypatch.setitem(sys.modules, "megatron.bridge", bridge)
monkeypatch.setitem(sys.modules, "megatron.bridge.data", data)
monkeypatch.setitem(sys.modules, "megatron.bridge.data.builders", builders)
monkeypatch.setitem(sys.modules, "megatron.bridge.data.datasets", datasets)
monkeypatch.setitem(sys.modules, "megatron.bridge.training", training)
monkeypatch.setitem(sys.modules, "megatron.bridge.training.tokenizers", tokenizers)
monkeypatch.setitem(sys.modules, "megatron.bridge.recipes", recipes)
monkeypatch.setitem(sys.modules, "megatron.bridge.data.builders.finetuning_dataset", finetuning_dataset)
monkeypatch.setitem(sys.modules, "megatron.bridge.data.builders.hf_dataset", hf_dataset)
monkeypatch.setitem(sys.modules, "megatron.bridge.data.datasets.packed_sequence", packed_sequence)
monkeypatch.setitem(sys.modules, "megatron.bridge.training.config", training_config)
monkeypatch.setitem(sys.modules, "megatron.bridge.training.tokenizers.tokenizer", tokenizer_module)
monkeypatch.setattr(megatron, "bridge", bridge, raising=False)
monkeypatch.setattr(bridge, "recipes", recipes, raising=False)
monkeypatch.setattr(bridge, "data", data, raising=False)
monkeypatch.setattr(data, "builders", builders, raising=False)
monkeypatch.setattr(data, "datasets", datasets, raising=False)
monkeypatch.setattr(builders, "finetuning_dataset", finetuning_dataset, raising=False)
monkeypatch.setattr(builders, "hf_dataset", hf_dataset, raising=False)
monkeypatch.setattr(datasets, "packed_sequence", packed_sequence, raising=False)
monkeypatch.setattr(bridge, "training", training, raising=False)
monkeypatch.setattr(training, "config", training_config, raising=False)
monkeypatch.setattr(training, "tokenizers", tokenizers, raising=False)
monkeypatch.setattr(tokenizers, "tokenizer", tokenizer_module, raising=False)
return prepare_packed_sequence_data


def test_pack_sft_data_rejects_unsupported_seq_length(monkeypatch):
module = _load_module()

def unit_recipe():
raise AssertionError("recipe should not run when explicit override cannot be forwarded")

_install_pack_sft_stubs(monkeypatch, unit_recipe)
monkeypatch.setattr(sys, "argv", ["pack_sft_data.py", "--recipe", "unit_recipe", "--seq-length", "4096"])

with pytest.raises(SystemExit) as exc_info:
module.main()

assert str(exc_info.value) == "Error: recipe 'unit_recipe' does not accept a 'seq_length' parameter."


def test_pack_sft_data_rejects_unsupported_hf_path(monkeypatch):
module = _load_module()

def unit_recipe():
raise AssertionError("recipe should not run when explicit override cannot be forwarded")

_install_pack_sft_stubs(monkeypatch, unit_recipe)
monkeypatch.setattr(sys, "argv", ["pack_sft_data.py", "--recipe", "unit_recipe", "--hf-path", "nvidia/unit"])

with pytest.raises(SystemExit) as exc_info:
module.main()

assert str(exc_info.value) == "Error: recipe 'unit_recipe' does not accept an 'hf_path' parameter."


def test_pack_sft_data_forwards_supported_overrides_and_explicit_paths(monkeypatch, tmp_path):
module = _load_module()
recipe_calls = []

def unit_recipe(seq_length: int, hf_path: str):
recipe_calls.append({"seq_length": seq_length, "hf_path": hf_path})
return _RecipeConfig(dataset=_DatasetConfig(seq_length=seq_length))

prepare_packed_sequence_data = _install_pack_sft_stubs(monkeypatch, unit_recipe)

train_input = tmp_path / "train.jsonl"
train_output = tmp_path / "packed-train.parquet"
metadata_output = tmp_path / "metadata.json"
monkeypatch.setattr(
sys,
"argv",
[
"pack_sft_data.py",
"--recipe",
"unit_recipe",
"--seq-length",
"4096",
"--hf-path",
"nvidia/unit",
"--train-input-path",
str(train_input),
"--packed-train-data-path",
str(train_output),
"--packed-metadata-path",
str(metadata_output),
],
)

module.main()

assert recipe_calls == [{"seq_length": 4096, "hf_path": "nvidia/unit"}]
prepare_packed_sequence_data.assert_called_once()
_, kwargs = prepare_packed_sequence_data.call_args
assert kwargs["input_path"] == train_input
assert kwargs["output_path"] == train_output
assert kwargs["output_metadata_path"] == metadata_output
assert kwargs["packed_sequence_size"] == 2048
assert kwargs["max_seq_length"] == 4096
assert kwargs["num_tokenizer_workers"] == 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: _PackedSequenceSpecs defaults num_tokenizer_workers to -1, and the script passes it through unchanged to prepare_packed_sequence_data. This assertion will fail.

Suggested change
assert kwargs["num_tokenizer_workers"] == 1
assert kwargs["num_tokenizer_workers"] == -1

@cuichenx cuichenx Jun 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the existing assertion is intentional here. The script sets cfg.dataset.packed_sequence_specs.num_tokenizer_workers = 1 before it calls prepare_packed_sequence_data(...) (see scripts/training/pack_sft_data.py around the worker cap), so the value forwarded to the packer should be 1 rather than the dataclass default -1. I reran the targeted test and it passes with the current assertion.

Loading
Loading