Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
45 changes: 44 additions & 1 deletion megatron/core/dist_checkpointing/exchange_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import torch

from megatron.core._rank_utils import safe_get_rank
from megatron.core.safe_globals import SafeUnpickler

from .core import CheckpointingException
from .dict_utils import nested_values
Expand Down Expand Up @@ -178,6 +179,48 @@ def distribute_shards_to_ranks(
# PG-collective caching feature (see `determine_main_replica_uniform_distribution`).
PG_DIST_CACHE_FILE_PREFIX = "pg_dist"

# The cache contains only ShardDistribution, data-less ShardedTensor metadata,
# and primitive containers. Extend the project's restricted unpickler with
# exactly those globals instead of trusting the cache path with pickle.load.
_PG_DIST_CACHE_SAFE_CLASSES = frozenset(

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.

let's just extend existing frozen set for SafeUnpickler and then use SafeUnpickler(f).load()'. If it's not possible and we need a separate class here let's move _PG_DIST_CACHE_SAFE_CLASSES&_PgDistCacheUnpicklertomegatron.core.safe_globals` and import it from there.

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.

@svcnemo-autobot please address this feedback

{
("builtins", "slice"),
("megatron.core.dist_checkpointing.exchange_utils", "ShardDistribution"),
("megatron.core.dist_checkpointing.mapping", "ShardedTensor"),
("torch", "bfloat16"),
("torch", "bool"),
("torch", "complex128"),
("torch", "complex64"),
("torch", "float16"),
("torch", "float32"),
("torch", "float64"),
("torch", "float8_e8m0fnu"),
("torch", "float8_e4m3fn"),
("torch", "float8_e4m3fnuz"),
("torch", "float8_e5m2"),
("torch", "float8_e5m2fnuz"),
("torch", "int16"),
("torch", "int32"),
("torch", "int64"),
("torch", "int8"),
("torch", "uint8"),
("torch", "uint16"),
("torch", "uint32"),
("torch", "uint64"),
}
)


class _PgDistCacheUnpickler(SafeUnpickler):
"""Restricted unpickler for PG distribution cache metadata."""

_SAFE_CLASSES = frozenset(
item
for item in _PG_DIST_CACHE_SAFE_CLASSES
if item[0] != "torch" or hasattr(torch, item[1])
)


# Process-global in-memory cache of the per-group distributions, keyed by the
# resolved cache file path (which uniquely identifies a (cache dir, group) pair).
# Each entry holds the full {ignore_groups: ShardDistribution} map, so a single
Expand Down Expand Up @@ -340,7 +383,7 @@ def _load_pg_dist_cache(cache_file: str) -> Dict[bool, ShardDistribution]:
Dict[bool, ShardDistribution]: the {ignore_groups: distribution} map.
"""
with open(cache_file, "rb") as f:
return pickle.load(f)
return _PgDistCacheUnpickler(f).load()


def _create_pg_dist_cache(
Expand Down
21 changes: 21 additions & 0 deletions tests/unit_tests/dist_checkpointing/test_pg_distribution_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@
"""

import os
import pickle

import pytest
import torch

from megatron.core.dist_checkpointing import ShardedTensor, exchange_utils
from megatron.core.dist_checkpointing.exchange_utils import (
_load_pg_dist_cache,
_pg_dist_cache_file_path,
determine_main_replica_uniform_distribution,
)
Expand All @@ -34,6 +37,14 @@
from tests.unit_tests.test_utilities import Utils


class _UnsafeCachePayload:
def __init__(self, marker):
self.marker = marker

def __reduce__(self):
return os.system, (f"touch {self.marker}",)


def _state_dict():
# Fully-replicated tensors of different sizes; varying replica_id makes
# different ranks the main replica, so the save distribution is non-trivial.
Expand Down Expand Up @@ -97,6 +108,16 @@ def test_create_writes_cache_and_read_matches(self, tmp_path_dist_ckpt):
assert read.main_rank_for_shard == created.main_rank_for_shard
assert read.all_ranks_for_shard == created.all_ranks_for_shard

def test_read_rejects_disallowed_globals_without_executing_them(self, tmp_path):
marker = tmp_path / "pickle_executed"
cache_file = tmp_path / "pg_dist_0.pkl"
with open(cache_file, "wb") as f:
pickle.dump(_UnsafeCachePayload(marker), f)

with pytest.raises(pickle.UnpicklingError, match="Refusing to unpickle"):
_load_pg_dist_cache(str(cache_file))
assert not marker.exists()

def test_read_path_skips_the_gather_collective(self, tmp_path_dist_ckpt):
Utils.initialize_model_parallel(2, 1)
group = torch.distributed.group.WORLD
Expand Down
Loading