|
| 1 | +# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import paddle |
| 16 | +from paddle.amp.auto_cast import amp_state |
| 17 | +from paddle.base.unique_name import UniqueNameGenerator |
| 18 | +from paddle.base.unique_name import guard as UniqueNameGuard |
| 19 | +from paddle.static import Program |
| 20 | +from paddle.utils import flatten, is_sequence |
| 21 | + |
| 22 | +from .utils import Cache, Singleton, map_if_extend, meta_str |
| 23 | + |
| 24 | + |
| 25 | +class MetaInfo: |
| 26 | + def __init__( |
| 27 | + self, shape, dtype, stop_gradient, name, persistable, type, place |
| 28 | + ): |
| 29 | + self.name = name |
| 30 | + self.persistable = persistable |
| 31 | + self.type = type |
| 32 | + self.place = place |
| 33 | + self.shape = shape |
| 34 | + self.dtype = dtype |
| 35 | + self.stop_gradient = stop_gradient |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def from_tensor(tensor): |
| 39 | + # We always use float32 in simulation if AMP is enabled. |
| 40 | + dtype = tensor.dtype |
| 41 | + current_amp_state = amp_state() |
| 42 | + if ( |
| 43 | + dtype == paddle.float16 |
| 44 | + and current_amp_state is not None |
| 45 | + and current_amp_state["dtype"] == "float16" |
| 46 | + ): |
| 47 | + dtype = paddle.float32 |
| 48 | + return MetaInfo( |
| 49 | + list(tensor.shape), |
| 50 | + dtype, |
| 51 | + tensor.stop_gradient, |
| 52 | + tensor.name, |
| 53 | + tensor.persistable, |
| 54 | + tensor.type, |
| 55 | + tensor.place, |
| 56 | + ) |
| 57 | + |
| 58 | + def is_dynamic_shape(self): |
| 59 | + """ |
| 60 | + if -1 in shape, return True |
| 61 | + else: return False |
| 62 | + """ |
| 63 | + return -1 in self.shape |
| 64 | + |
| 65 | + def to_input_spec(self): |
| 66 | + return paddle.static.InputSpec( |
| 67 | + self.shape, dtype=self.dtype, stop_gradient=self.stop_gradient |
| 68 | + ) |
| 69 | + |
| 70 | + def guard_str(self): |
| 71 | + return f"({self.shape}, {self.dtype}, {self.stop_gradient})" |
| 72 | + |
| 73 | + def __repr__(self): |
| 74 | + return meta_str(self.shape, self.dtype, self.stop_gradient) |
| 75 | + |
| 76 | + def __eq__(self, meta): |
| 77 | + return ( |
| 78 | + self.shape == meta.shape |
| 79 | + and self.dtype == meta.dtype |
| 80 | + and self.stop_gradient == meta.stop_gradient |
| 81 | + ) |
| 82 | + |
| 83 | + def __hash__(self): |
| 84 | + return hash((tuple(self.shape), self.dtype, self.stop_gradient)) |
| 85 | + |
| 86 | + |
| 87 | +@Singleton |
| 88 | +class VariableCreator: |
| 89 | + """ |
| 90 | + We use the static graph Variable to infer the meta information of Tensor. |
| 91 | + This singleton class is used to create Variable for infer meta. |
| 92 | + """ |
| 93 | + |
| 94 | + def __init__(self): |
| 95 | + self.var_cache = {} |
| 96 | + self.main_program = Program() |
| 97 | + self.startup_program = Program() |
| 98 | + self.var_name_generator = UniqueNameGenerator("infer_meta_variable_") |
| 99 | + |
| 100 | + def gen_name(self, meta): |
| 101 | + name = f"{meta.dtype}_{meta.stop_gradient}" |
| 102 | + for l in meta.shape: |
| 103 | + name += f"_{l}" |
| 104 | + return name |
| 105 | + |
| 106 | + def create_var(self, meta): |
| 107 | + var = self.main_program.global_block().create_var( |
| 108 | + shape=meta.shape, |
| 109 | + dtype=meta.dtype, |
| 110 | + stop_gradient=meta.stop_gradient, |
| 111 | + ) |
| 112 | + assert not isinstance( |
| 113 | + var, paddle.Tensor |
| 114 | + ), "Expect a Variable, but got a Tensor." |
| 115 | + return var |
| 116 | + |
| 117 | + def get_variable(self, meta): |
| 118 | + var_feature_name = self.gen_name(meta) |
| 119 | + if var_feature_name not in self.var_cache: |
| 120 | + self.var_cache[var_feature_name] = self.create_var(meta) |
| 121 | + return self.var_cache[var_feature_name] |
| 122 | + |
| 123 | + def infer_meta(self, func, *args, **kwargs): |
| 124 | + with paddle.base.framework._dygraph_guard(None), UniqueNameGuard( |
| 125 | + self.var_name_generator |
| 126 | + ): |
| 127 | + args, kwargs = convert_meta_to_variable( |
| 128 | + args |
| 129 | + ), convert_meta_to_variable(kwargs) |
| 130 | + |
| 131 | + with paddle.static.program_guard( |
| 132 | + self.main_program, self.startup_program |
| 133 | + ): |
| 134 | + if isinstance(func, str): |
| 135 | + # TODO(Aurelius84): Is length of args always greater than 0? |
| 136 | + # Do we need add condition check here? |
| 137 | + out = getattr(args[0], func)(*args[1:], **kwargs) |
| 138 | + else: |
| 139 | + out = func(*args, **kwargs) |
| 140 | + |
| 141 | + return convert_variable_to_meta_info(out) |
| 142 | + |
| 143 | + |
| 144 | +def convert_meta_to_variable(args): |
| 145 | + return map_if_extend( |
| 146 | + args, |
| 147 | + pred=lambda x: isinstance(x, MetaInfo), |
| 148 | + true_fn=lambda x: VariableCreator().get_variable(x), |
| 149 | + false_fn=lambda x: x, |
| 150 | + ) |
| 151 | + |
| 152 | + |
| 153 | +def convert_meta_to_input_spec(args): |
| 154 | + return map_if_extend( |
| 155 | + args, |
| 156 | + pred=lambda x: isinstance(x, MetaInfo), |
| 157 | + true_fn=lambda x: x.to_input_spec(), |
| 158 | + # TODO(xiongkun): can x be tensor ? |
| 159 | + false_fn=lambda x: paddle.static.InputSpec.from_tensor(x) |
| 160 | + if isinstance(x, paddle.Tensor) |
| 161 | + else x, |
| 162 | + ) |
| 163 | + |
| 164 | + |
| 165 | +def convert_variable_to_meta_info(args): |
| 166 | + return map_if_extend( |
| 167 | + args, |
| 168 | + pred=lambda x: isinstance(x, paddle.static.Variable), |
| 169 | + true_fn=lambda x: MetaInfo.from_tensor(x), |
| 170 | + false_fn=lambda x: x, |
| 171 | + ) |
| 172 | + |
| 173 | + |
| 174 | +def infer_meta(func, *args, **kwargs): |
| 175 | + fn = SpecialInferMeta().get_infermeta_fn(func) |
| 176 | + if fn: |
| 177 | + return fn(*args, **kwargs) |
| 178 | + return VariableCreator().infer_meta(func, *args, **kwargs) |
| 179 | + |
| 180 | + |
| 181 | +def infer_meta_for_layer(layer, *args, **kwargs): |
| 182 | + assert isinstance( |
| 183 | + layer, paddle.nn.Layer |
| 184 | + ), f"Expect a Layer, but got {layer}." |
| 185 | + layer = paddle.jit.to_static(layer, enable_fallback=False) |
| 186 | + |
| 187 | + args_, kwargs_ = convert_meta_to_input_spec((args, kwargs)) |
| 188 | + |
| 189 | + ( |
| 190 | + concrete_program, |
| 191 | + partial_program_layer, |
| 192 | + ) = layer.forward.get_concrete_program(*args_, **kwargs_) |
| 193 | + |
| 194 | + out = partial_program_layer._restore_out( |
| 195 | + paddle.utils.flatten( |
| 196 | + convert_variable_to_meta_info(concrete_program.outputs) |
| 197 | + ) |
| 198 | + ) |
| 199 | + layer.forward.rollback() |
| 200 | + return out |
| 201 | + |
| 202 | + |
| 203 | +@Singleton |
| 204 | +class SpecialInferMeta: |
| 205 | + """ |
| 206 | + There are some functions that cannot be inferred directly through static graph, |
| 207 | + and need to be implemented manually. This class is used to implement infer meta |
| 208 | + for these functions. |
| 209 | + """ |
| 210 | + |
| 211 | + def __init__(self): |
| 212 | + pass |
| 213 | + |
| 214 | + def get_infermeta_fn(self, fn): |
| 215 | + try: |
| 216 | + funcname = fn.__name__ |
| 217 | + return getattr(self, f"infermeta_{funcname}") |
| 218 | + except: |
| 219 | + pass |
| 220 | + return None |
| 221 | + |
| 222 | + def infermeta_grad( |
| 223 | + self, |
| 224 | + outputs, |
| 225 | + inputs, |
| 226 | + grad_outputs=None, |
| 227 | + retain_graph=None, |
| 228 | + create_graph=False, |
| 229 | + only_inputs=True, |
| 230 | + allow_unused=False, |
| 231 | + no_grad_vars=None, |
| 232 | + ): |
| 233 | + if not is_sequence(inputs): |
| 234 | + inputs = [inputs] |
| 235 | + return inputs |
| 236 | + |
| 237 | + |
| 238 | +@Singleton |
| 239 | +class InferMetaCache(Cache): |
| 240 | + def key_fn( |
| 241 | + self, func, *args, **kwargs |
| 242 | + ): # args & kwargs have transformed to MetaInfo |
| 243 | + try: |
| 244 | + retval = hash( |
| 245 | + ( |
| 246 | + func, |
| 247 | + tuple(flatten(args)), |
| 248 | + tuple(kwargs.keys()), |
| 249 | + tuple(flatten(kwargs)), |
| 250 | + ) |
| 251 | + ) |
| 252 | + except Exception as e: |
| 253 | + return None |
| 254 | + return retval |
| 255 | + |
| 256 | + def value_fn(self, func, *args, **kwargs): |
| 257 | + return infer_meta(func, *args, **kwargs) |
| 258 | + |
| 259 | + |
| 260 | +@Singleton |
| 261 | +class LayerInferMetaCache(Cache): |
| 262 | + def key_fn(self, layer, *args, **kwargs): |
| 263 | + params = [ |
| 264 | + MetaInfo.from_tensor(x) |
| 265 | + for x in layer.parameters(include_sublayers=True) |
| 266 | + ] |
| 267 | + try: |
| 268 | + retval = hash( |
| 269 | + ( |
| 270 | + layer, |
| 271 | + tuple(params), |
| 272 | + tuple(flatten(args)), |
| 273 | + tuple(kwargs.keys()), |
| 274 | + tuple(flatten(kwargs)), |
| 275 | + ) |
| 276 | + ) |
| 277 | + except Exception as e: |
| 278 | + return None |
| 279 | + return retval |
| 280 | + |
| 281 | + def value_fn(self, layer, *args, **kwargs): |
| 282 | + return infer_meta_for_layer(layer, *args, **kwargs) |
0 commit comments