|
| 1 | +import logging |
| 2 | +from graph_net.dynamic_dim_constraints import DynamicDimConstraints |
| 3 | +from graph_net.imp_util import load_module |
| 4 | +from graph_net.tensor_meta import TensorMeta |
| 5 | +import functools |
| 6 | +import sys |
| 7 | +import os |
| 8 | +from contextlib import contextmanager |
| 9 | +import tempfile |
| 10 | +import shutil |
| 11 | +from pathlib import Path |
| 12 | +from dataclasses import asdict |
| 13 | +import graph_net.graph_net_json_file_util as gn_json |
| 14 | + |
| 15 | + |
| 16 | +class ApplyDimGenPasses: |
| 17 | + def __init__(self, config=None): |
| 18 | + if config is None: |
| 19 | + config = {} |
| 20 | + self.config = self._make_config(**config) |
| 21 | + self.num_handled_models = 0 |
| 22 | + |
| 23 | + def _make_config( |
| 24 | + self, |
| 25 | + output_dir: str, |
| 26 | + dimension_generalizer_filepath=None, |
| 27 | + dimension_generalizer_class_name="StaticToDynamic", |
| 28 | + dimension_generalizer_config=None, |
| 29 | + model_path_prefix="", |
| 30 | + resume=False, |
| 31 | + last_model_log_file=None, |
| 32 | + limits_handled_models=None, |
| 33 | + ): |
| 34 | + if dimension_generalizer_config is None: |
| 35 | + dimension_generalizer_config = {} |
| 36 | + return { |
| 37 | + "resume": resume, |
| 38 | + "output_dir": output_dir, |
| 39 | + "model_path_prefix": model_path_prefix, |
| 40 | + "dimension_generalizer_filepath": dimension_generalizer_filepath, |
| 41 | + "dimension_generalizer_class_name": dimension_generalizer_class_name, |
| 42 | + "dimension_generalizer_config": dimension_generalizer_config, |
| 43 | + "last_model_log_file": last_model_log_file, |
| 44 | + "limits_handled_models": limits_handled_models, |
| 45 | + } |
| 46 | + |
| 47 | + def __call__(self, rel_model_path): |
| 48 | + model_path = os.path.join(self.config["model_path_prefix"], rel_model_path) |
| 49 | + output_dir = Path(self.config["output_dir"]) |
| 50 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 51 | + generalized_model_path = output_dir / rel_model_path |
| 52 | + if self.config["resume"] and (generalized_model_path / "model.py").exists(): |
| 53 | + return |
| 54 | + tensor_metas = self._get_tensor_metas(model_path) |
| 55 | + tensor_meta_attrs_list = [asdict(tensor_meta) for tensor_meta in tensor_metas] |
| 56 | + dim_gen_pass_names = self._get_dim_gen_pass_names(model_path) |
| 57 | + dim_generalizer = self._get_dimension_generalizer(dim_gen_pass_names) |
| 58 | + inputs = dim_generalizer.create_inputs_by_metas( |
| 59 | + module=self._get_model(model_path), |
| 60 | + tensor_meta_attrs_list=tensor_meta_attrs_list, |
| 61 | + ) |
| 62 | + dyn_dim_cstrs = DynamicDimConstraints.unserialize_from_py_file( |
| 63 | + os.path.join(model_path, "input_tensor_constraints.py") |
| 64 | + ) |
| 65 | + dim_axes_pairs = self._get_dim_axes_pairs(dyn_dim_cstrs) |
| 66 | + if len(dim_axes_pairs) == 0: |
| 67 | + return |
| 68 | + |
| 69 | + def get_generalized(): |
| 70 | + return self._get_generalized_model_py_file_path( |
| 71 | + dim_generalizer=dim_generalizer, |
| 72 | + dim_axes_pairs=dim_axes_pairs, |
| 73 | + model_path=model_path, |
| 74 | + inputs=inputs, |
| 75 | + ) |
| 76 | + |
| 77 | + with get_generalized() as generalized_model_py_path: |
| 78 | + self._save_generalized_model_path(rel_model_path, generalized_model_py_path) |
| 79 | + |
| 80 | + self._check_num_handled_models() |
| 81 | + |
| 82 | + def _save_generalized_model_path(self, rel_model_path, generalized_model_py_path): |
| 83 | + from_model_path = Path(self.config["model_path_prefix"]) / rel_model_path |
| 84 | + to_model_path = Path(self.config["output_dir"]) / rel_model_path |
| 85 | + print(f"{str(to_model_path)=}") |
| 86 | + to_model_path.mkdir(parents=True, exist_ok=True) |
| 87 | + shutil.copytree(Path(from_model_path), Path(to_model_path), dirs_exist_ok=True) |
| 88 | + generalized_model_py_code = Path(generalized_model_py_path).read_text() |
| 89 | + (to_model_path / "model.py").write_text(generalized_model_py_code) |
| 90 | + |
| 91 | + def _get_dim_axes_pairs(self, dyn_dim_cstrs): |
| 92 | + sym_input_shapes = dyn_dim_cstrs.get_sorted_symbolic_input_shapes() |
| 93 | + return [ |
| 94 | + (dim, axes) |
| 95 | + for symbol in dyn_dim_cstrs.symbols |
| 96 | + for dim in [dyn_dim_cstrs.symbol2example_value[symbol]] |
| 97 | + for axes in [ |
| 98 | + [ |
| 99 | + axis |
| 100 | + for shape in sym_input_shapes |
| 101 | + for axis, sym_or_dim in enumerate(shape) |
| 102 | + if sym_or_dim == symbol |
| 103 | + ] |
| 104 | + ] |
| 105 | + ] |
| 106 | + |
| 107 | + def _get_dim_gen_pass_names(self, model_path): |
| 108 | + json_value = gn_json.read_json(model_path) |
| 109 | + return json_value.get(gn_json.kDimensionGeneralizationPasses, []) |
| 110 | + |
| 111 | + def _check_num_handled_models(self): |
| 112 | + self.num_handled_models += 1 |
| 113 | + limits = self.config["limits_handled_models"] |
| 114 | + if limits is None: |
| 115 | + return |
| 116 | + if self.num_handled_models < limits: |
| 117 | + return |
| 118 | + print("`num_handled_models` exceeds config `limits_handled_models`") |
| 119 | + sys.exit(0) |
| 120 | + |
| 121 | + def _get_dimension_generalizer(self, dim_gen_pass_names): |
| 122 | + assert self.config["dimension_generalizer_filepath"] is not None |
| 123 | + decorator_cls = getattr( |
| 124 | + load_module(self.config["dimension_generalizer_filepath"]), |
| 125 | + self.config["dimension_generalizer_class_name"], |
| 126 | + ) |
| 127 | + config = {"pass_names": dim_gen_pass_names} |
| 128 | + dim_generalizer = decorator_cls(config) |
| 129 | + return dim_generalizer |
| 130 | + |
| 131 | + def _get_model(self, model_path): |
| 132 | + py_module = load_module(os.path.join(model_path, "model.py")) |
| 133 | + GraphModule = getattr(py_module, "GraphModule") |
| 134 | + GraphModule.__graph_net_file_path__ = py_module.__graph_net_file_path__ |
| 135 | + return GraphModule() |
| 136 | + |
| 137 | + @contextmanager |
| 138 | + def _get_generalized_model_py_file_path( |
| 139 | + self, dim_generalizer, dim_axes_pairs, model_path, inputs |
| 140 | + ): |
| 141 | + model = self._get_model(model_path) |
| 142 | + dim_gen_pass = dim_generalizer(model, dim_axes_pairs) |
| 143 | + logging.warning("before need_rewrite") |
| 144 | + need_rewrite = dim_gen_pass.need_rewrite(inputs) |
| 145 | + logging.warning("after need_rewrite") |
| 146 | + if not need_rewrite: |
| 147 | + yield os.path.join(model_path, "model.py") |
| 148 | + return |
| 149 | + logging.warning("before rewrite") |
| 150 | + graph_module = dim_gen_pass.rewrite(inputs) |
| 151 | + logging.warning("after rewrite") |
| 152 | + with tempfile.TemporaryDirectory() as tmp_dir: |
| 153 | + shutil.copytree(Path(model_path), Path(tmp_dir), dirs_exist_ok=True) |
| 154 | + dim_gen_pass.save_graph_module(graph_module, tmp_dir) |
| 155 | + yield os.path.join(tmp_dir, "model.py") |
| 156 | + |
| 157 | + def _get_tensor_metas(self, model_path): |
| 158 | + make = TensorMeta.unserialize_from_py_file |
| 159 | + return [ |
| 160 | + *make(os.path.join(model_path, "input_meta.py")), |
| 161 | + *make(os.path.join(model_path, "weight_meta.py")), |
| 162 | + ] |
| 163 | + |
| 164 | + |
| 165 | +def update_tensor_metas_by_dyn_dim_cstr( |
| 166 | + tensor_metas: list[TensorMeta], dyn_dim_cstr: DynamicDimConstraints |
| 167 | +): |
| 168 | + input_shapes = dyn_dim_cstr.get_reified_input_shapes() |
| 169 | + assert len(tensor_metas) == len(input_shapes) |
| 170 | + for i, tensor_meta in enumerate(tensor_metas): |
| 171 | + tensor_meta.shape = input_shapes[i] |
| 172 | + if tensor_meta.data is not None: |
| 173 | + assert isinstance(tensor_meta.data, (list, tuple)) |
| 174 | + size = functools.reduce(lambda a, b: a * b, tensor_meta.shape, 1) |
| 175 | + doubled_data = [*tensor_meta.data, *tensor_meta.data] |
| 176 | + tensor_meta.data = doubled_data[:size] |
0 commit comments