From baa81e7a46b4b8e42d227b53467d32627609dca6 Mon Sep 17 00:00:00 2001 From: svcnemo-autobot Date: Fri, 21 Aug 2026 12:30:40 +0000 Subject: [PATCH 1/4] fix(dist-checkpointing): restrict PG cache unpickling Signed-off-by: svcnemo-autobot --- .../core/dist_checkpointing/exchange_utils.py | 45 ++++++++++++++++++- .../test_pg_distribution_cache.py | 21 +++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/megatron/core/dist_checkpointing/exchange_utils.py b/megatron/core/dist_checkpointing/exchange_utils.py index 38628e2e416..3c30ce69b2f 100644 --- a/megatron/core/dist_checkpointing/exchange_utils.py +++ b/megatron/core/dist_checkpointing/exchange_utils.py @@ -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 @@ -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( + { + ("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 @@ -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( diff --git a/tests/unit_tests/dist_checkpointing/test_pg_distribution_cache.py b/tests/unit_tests/dist_checkpointing/test_pg_distribution_cache.py index 78027d666bf..af3e22b0261 100644 --- a/tests/unit_tests/dist_checkpointing/test_pg_distribution_cache.py +++ b/tests/unit_tests/dist_checkpointing/test_pg_distribution_cache.py @@ -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, ) @@ -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. @@ -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 From 840607c969e9921f59c048bc1b0a5fa0a95de09c Mon Sep 17 00:00:00 2001 From: svcnemo-autobot Date: Sat, 22 Aug 2026 14:15:27 +0000 Subject: [PATCH 2/4] refactor(dist-checkpointing): centralize PG cache safety Signed-off-by: svcnemo-autobot --- .../core/dist_checkpointing/exchange_utils.py | 44 +------------------ megatron/core/safe_globals.py | 37 ++++++++++++++++ .../dist_checkpointing/test_safe_globals.py | 9 ++++ 3 files changed, 47 insertions(+), 43 deletions(-) diff --git a/megatron/core/dist_checkpointing/exchange_utils.py b/megatron/core/dist_checkpointing/exchange_utils.py index 3c30ce69b2f..cfa5e848c11 100644 --- a/megatron/core/dist_checkpointing/exchange_utils.py +++ b/megatron/core/dist_checkpointing/exchange_utils.py @@ -14,7 +14,7 @@ import torch from megatron.core._rank_utils import safe_get_rank -from megatron.core.safe_globals import SafeUnpickler +from megatron.core.safe_globals import _PgDistCacheUnpickler from .core import CheckpointingException from .dict_utils import nested_values @@ -179,48 +179,6 @@ 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( - { - ("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 diff --git a/megatron/core/safe_globals.py b/megatron/core/safe_globals.py index d046c3e1e34..d8444cd7620 100755 --- a/megatron/core/safe_globals.py +++ b/megatron/core/safe_globals.py @@ -123,3 +123,40 @@ def find_class(self, module: str, name: str): f"Refusing to unpickle disallowed class '{module}.{name}' " ) return super().find_class(module, name) + + +_PG_DIST_CACHE_SAFE_CLASSES = frozenset( + { + ("builtins", "slice"), + ("megatron.core.dist_checkpointing.exchange_utils", "ShardDistribution"), + ("megatron.core.dist_checkpointing.mapping", "ShardedTensor"), + *(("torch", name) for name in ( + "bfloat16", + "bool", + "complex128", + "complex64", + "float16", + "float32", + "float64", + "float8_e8m0fnu", + "float8_e4m3fn", + "float8_e4m3fnuz", + "float8_e5m2", + "float8_e5m2fnuz", + "int16", + "int32", + "int64", + "int8", + "uint8", + "uint16", + "uint32", + "uint64", + ) if hasattr(torch, name)), + } +) + + +class _PgDistCacheUnpickler(SafeUnpickler): + """Restricted unpickler for process-group distribution cache metadata.""" + + _SAFE_CLASSES = _PG_DIST_CACHE_SAFE_CLASSES diff --git a/tests/unit_tests/dist_checkpointing/test_safe_globals.py b/tests/unit_tests/dist_checkpointing/test_safe_globals.py index 324de974a7d..1b82708682d 100755 --- a/tests/unit_tests/dist_checkpointing/test_safe_globals.py +++ b/tests/unit_tests/dist_checkpointing/test_safe_globals.py @@ -175,3 +175,12 @@ def load(i): assert not errors for i, arr in arrays.items(): np.testing.assert_array_equal(results[i], arr) + + +class TestPgDistCacheUnpickler: + def test_does_not_inherit_fp8_safe_classes(self): + from megatron.core.safe_globals import _PgDistCacheUnpickler + + raw = pickle.dumps(OrderedDict(a=1)) + with pytest.raises(pickle.UnpicklingError, match="Refusing to unpickle"): + _PgDistCacheUnpickler(io.BytesIO(raw)).load() From 737063f174b750c984dc5f447890ef81cd226ac3 Mon Sep 17 00:00:00 2001 From: svcnemo-autobot Date: Sat, 22 Aug 2026 14:53:02 +0000 Subject: [PATCH 3/4] style(dist-checkpointing): format PG cache globals Signed-off-by: svcnemo-autobot --- megatron/core/safe_globals.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/megatron/core/safe_globals.py b/megatron/core/safe_globals.py index d8444cd7620..382b4c15c8c 100755 --- a/megatron/core/safe_globals.py +++ b/megatron/core/safe_globals.py @@ -130,7 +130,9 @@ def find_class(self, module: str, name: str): ("builtins", "slice"), ("megatron.core.dist_checkpointing.exchange_utils", "ShardDistribution"), ("megatron.core.dist_checkpointing.mapping", "ShardedTensor"), - *(("torch", name) for name in ( + *( + ("torch", name) + for name in ( "bfloat16", "bool", "complex128", @@ -151,7 +153,9 @@ def find_class(self, module: str, name: str): "uint16", "uint32", "uint64", - ) if hasattr(torch, name)), + ) + if hasattr(torch, name) + ), } ) From 2fb227da647aea146433b0a3dcdc629b5af2b465 Mon Sep 17 00:00:00 2001 From: svcnemo-autobot Date: Sat, 22 Aug 2026 15:22:17 +0000 Subject: [PATCH 4/4] style(dist-checkpointing): format safe globals Signed-off-by: svcnemo-autobot --- megatron/core/safe_globals.py | 40 +++++++++++++++++------------------ 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/megatron/core/safe_globals.py b/megatron/core/safe_globals.py index 382b4c15c8c..2f3cc1c193c 100755 --- a/megatron/core/safe_globals.py +++ b/megatron/core/safe_globals.py @@ -133,26 +133,26 @@ def find_class(self, module: str, name: str): *( ("torch", name) for name in ( - "bfloat16", - "bool", - "complex128", - "complex64", - "float16", - "float32", - "float64", - "float8_e8m0fnu", - "float8_e4m3fn", - "float8_e4m3fnuz", - "float8_e5m2", - "float8_e5m2fnuz", - "int16", - "int32", - "int64", - "int8", - "uint8", - "uint16", - "uint32", - "uint64", + "bfloat16", + "bool", + "complex128", + "complex64", + "float16", + "float32", + "float64", + "float8_e8m0fnu", + "float8_e4m3fn", + "float8_e4m3fnuz", + "float8_e5m2", + "float8_e5m2fnuz", + "int16", + "int32", + "int64", + "int8", + "uint8", + "uint16", + "uint32", + "uint64", ) if hasattr(torch, name) ),