|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
| 15 | +import importlib |
15 | 16 | import logging |
16 | | -from typing import Any, Literal, Optional |
| 17 | +from typing import Any, Callable, Literal, Optional |
17 | 18 |
|
18 | 19 | from megatron.core.process_groups_config import ProcessGroupCollection |
19 | | -from megatron.energon import WorkerConfig, get_savable_loader, get_train_dataset |
| 20 | +from megatron.energon import Sample, WorkerConfig, get_savable_loader, get_train_dataset |
| 21 | +from megatron.energon import dataset_config as _energon_dataset_config |
| 22 | +from megatron.energon.epathlib import EPath |
| 23 | +from megatron.energon.flavors.webdataset.default_generic_webdataset import DefaultGenericWebdatasetFactory |
| 24 | +from megatron.energon.typed_converter import JsonParser |
20 | 25 |
|
21 | 26 |
|
22 | 27 | logger = logging.getLogger(__name__) |
23 | 28 |
|
| 29 | +_ORIGINAL_METHOD_ATTRIBUTE = "__megatron_bridge_original_method__" |
| 30 | +_TRUSTED_DATASET_FACTORY_MODULE_PREFIXES = ( |
| 31 | + "megatron.bridge.data.energon", |
| 32 | + "megatron.energon", |
| 33 | +) |
| 34 | +_TRUSTED_DATASET_FACTORY_MODULE_ALIASES = frozenset( |
| 35 | + { |
| 36 | + "megatron.bridge.models.qwen_vl.data.energon", |
| 37 | + } |
| 38 | +) |
| 39 | +_energon_factory_init = getattr( |
| 40 | + DefaultGenericWebdatasetFactory.__init__, |
| 41 | + _ORIGINAL_METHOD_ATTRIBUTE, |
| 42 | + DefaultGenericWebdatasetFactory.__init__, |
| 43 | +) |
| 44 | +_energon_load_config = getattr( |
| 45 | + _energon_dataset_config.load_config, |
| 46 | + _ORIGINAL_METHOD_ATTRIBUTE, |
| 47 | + _energon_dataset_config.load_config, |
| 48 | +) |
| 49 | + |
| 50 | + |
| 51 | +def _validate_energon_dataset_metadata(value: Any, *, root: bool = True) -> None: |
| 52 | + """Reject executable object references in untrusted dataset factory metadata.""" |
| 53 | + if isinstance(value, list): |
| 54 | + for item in value: |
| 55 | + _validate_energon_dataset_metadata(item, root=False) |
| 56 | + return |
| 57 | + if not isinstance(value, dict): |
| 58 | + return |
| 59 | + |
| 60 | + module_name = value.get("__module__") |
| 61 | + function_name = value.get("__function__") |
| 62 | + class_name = value.get("__class__") |
| 63 | + if function_name is not None: |
| 64 | + raise ValueError( |
| 65 | + "Energon dataset metadata cannot resolve serialized Python functions. " |
| 66 | + "Use declarative configuration or pass a Python callable from trusted application code." |
| 67 | + ) |
| 68 | + if class_name is not None: |
| 69 | + trusted_class = ( |
| 70 | + isinstance(module_name, str) |
| 71 | + and isinstance(class_name, str) |
| 72 | + and ( |
| 73 | + module_name in _TRUSTED_DATASET_FACTORY_MODULE_ALIASES |
| 74 | + or any( |
| 75 | + module_name == prefix or module_name.startswith(f"{prefix}.") |
| 76 | + for prefix in _TRUSTED_DATASET_FACTORY_MODULE_PREFIXES |
| 77 | + ) |
| 78 | + ) |
| 79 | + ) |
| 80 | + if trusted_class: |
| 81 | + module = importlib.import_module(module_name) |
| 82 | + referenced_type = getattr(module, class_name, None) |
| 83 | + required_base = DefaultGenericWebdatasetFactory if root else Sample |
| 84 | + trusted_class = isinstance(referenced_type, type) and issubclass(referenced_type, required_base) |
| 85 | + if not trusted_class: |
| 86 | + raise ValueError( |
| 87 | + "Energon dataset metadata cannot instantiate serialized Python classes. " |
| 88 | + "Only packaged Energon dataset factory and sample classes are allowed." |
| 89 | + ) |
| 90 | + |
| 91 | + for item in value.values(): |
| 92 | + _validate_energon_dataset_metadata(item, root=False) |
| 93 | + |
| 94 | + |
| 95 | +def _secure_energon_load_config( |
| 96 | + path: EPath | dict[str, Any], |
| 97 | + *, |
| 98 | + default_type: type, |
| 99 | + default_kwargs: dict[str, Any] | None = None, |
| 100 | + parser: JsonParser = JsonParser(strict=True), |
| 101 | +) -> Any: |
| 102 | + """Validate dataset metadata before Energon resolves serialized objects.""" |
| 103 | + is_dataset_factory = isinstance(default_type, type) and issubclass(default_type, DefaultGenericWebdatasetFactory) |
| 104 | + if not is_dataset_factory: |
| 105 | + return _energon_load_config( |
| 106 | + path, |
| 107 | + default_type=default_type, |
| 108 | + default_kwargs=default_kwargs, |
| 109 | + parser=parser, |
| 110 | + ) |
| 111 | + |
| 112 | + if isinstance(path, dict): |
| 113 | + data = path |
| 114 | + else: |
| 115 | + with path.open("rb") as config_file: |
| 116 | + data = _energon_dataset_config.load_yaml(config_file) |
| 117 | + _validate_energon_dataset_metadata(data) |
| 118 | + return _energon_load_config( |
| 119 | + data, |
| 120 | + default_type=default_type, |
| 121 | + default_kwargs=default_kwargs, |
| 122 | + parser=parser, |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +def _secure_energon_factory_init( |
| 127 | + self: DefaultGenericWebdatasetFactory, |
| 128 | + path: EPath, |
| 129 | + *, |
| 130 | + subflavors: dict[str, Any] | None = None, |
| 131 | + field_map: dict[str, str] | None = None, |
| 132 | + sample_loader: str | Callable[[dict[str, Any]], dict[str, Any]] | None = None, |
| 133 | + part_filter: str | list[str] | Callable[[str], bool] | None = None, |
| 134 | + **kwargs: Any, |
| 135 | +) -> None: |
| 136 | + """Reject dataset-local Python hooks before Energon resolves their files.""" |
| 137 | + executable_fields = [ |
| 138 | + name |
| 139 | + for name, value in (("sample_loader", sample_loader), ("part_filter", part_filter)) |
| 140 | + if isinstance(value, str) |
| 141 | + ] |
| 142 | + if executable_fields: |
| 143 | + raise ValueError( |
| 144 | + "Energon dataset metadata cannot load Python files through " |
| 145 | + f"{', '.join(executable_fields)}. Use a declarative field_map instead." |
| 146 | + ) |
| 147 | + _energon_factory_init( |
| 148 | + self, |
| 149 | + path, |
| 150 | + subflavors=subflavors, |
| 151 | + field_map=field_map, |
| 152 | + sample_loader=sample_loader, |
| 153 | + part_filter=part_filter, |
| 154 | + **kwargs, |
| 155 | + ) |
| 156 | + |
| 157 | + |
| 158 | +# Energon constructs this factory internally after reading dataset.yaml, so |
| 159 | +# Bridge must install the guard before calling get_train_dataset(). |
| 160 | +setattr(_secure_energon_load_config, _ORIGINAL_METHOD_ATTRIBUTE, _energon_load_config) |
| 161 | +_energon_dataset_config.load_config = _secure_energon_load_config |
| 162 | +setattr(_secure_energon_factory_init, _ORIGINAL_METHOD_ATTRIBUTE, _energon_factory_init) |
| 163 | +DefaultGenericWebdatasetFactory.__init__ = _secure_energon_factory_init |
| 164 | + |
24 | 165 |
|
25 | 166 | class EnergonMultiModalDataModule: |
26 | 167 | """ |
|
0 commit comments