This repository has been archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
infer_meta.py
147 lines (116 loc) · 4.09 KB
/
infer_meta.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import paddle
from paddle.fluid.framework import Program
from paddle.utils import flatten
from .utils import Cache, Singleton, map_if, meta_str
@Singleton
class InferMetaCache(Cache):
def key_fn(self, *args, **kwargs):
return hash(
(tuple(flatten(args)), tuple(kwargs.keys()), tuple(flatten(kwargs)))
)
def value_fn(self, *args, **kwargs):
return infer_meta(*args, **kwargs)
class MetaInfo:
def __init__(self, shape, dtype, stop_gradient):
self.shape = shape
self.dtype = dtype
self.stop_gradient = stop_gradient
@staticmethod
def from_tensor(tensor):
return MetaInfo(tensor.shape, tensor.dtype, tensor.stop_gradient)
def to_input_spec(self):
return paddle.static.InputSpec(
self.shape, dtype=self.dtype, stop_gradient=self.stop_gradient
)
def __repr__(self):
return meta_str(self.shape, self.dtype, self.stop_gradient)
def __eq__(self, meta):
return (
self.shape == meta.shape
and self.dtype == meta.dtype
and self.stop_gradient == meta.stop_gradient
)
def __hash__(self):
return hash((tuple(self.shape), self.dtype, self.stop_gradient))
@Singleton
class VariableCreator:
def __init__(self):
self.var_cache = {}
self.main_program = Program()
self.startup_program = Program()
def gen_name(self, meta):
name = f"{meta.dtype}_{meta.stop_gradient}"
for l in meta.shape:
name += f"_{l}"
return name
def create_var(self, meta):
var = self.main_program.global_block().create_var(
shape=meta.shape,
dtype=meta.dtype,
stop_gradient=meta.stop_gradient,
)
assert not isinstance(
var, paddle.Tensor
), "Expect a Variable, but got a Tensor."
return var
def get_variable(self, meta):
var_feature_name = self.gen_name(meta)
if var_feature_name not in self.var_cache:
self.var_cache[var_feature_name] = self.create_var(meta)
return self.var_cache[var_feature_name]
def infer_meta(self, func, *args, **kwargs):
paddle.enable_static()
args, kwargs = convert_to_variable(args), convert_to_variable(kwargs)
with paddle.static.program_guard(
self.main_program, self.startup_program
):
if isinstance(func, str):
# TODO(Aurelius84): Is length of args always greater than 0?
# Do we need add condition check here?
out = getattr(args[0], func)(*args[1:], **kwargs)
else:
out = func(*args, **kwargs)
paddle.disable_static()
return variable_to_meta_info(out)
def convert_to_variable(args):
return map_if(
args,
pred=lambda x: isinstance(x, MetaInfo),
true_fn=lambda x: VariableCreator().get_variable(x),
false_fn=lambda x: x,
)
def convert_to_input_spec(args):
return map_if(
args,
pred=lambda x: isinstance(x, MetaInfo),
true_fn=lambda x: x.to_input_spec(),
false_fn=lambda x: paddle.static.InputSpec.from_tensor(x),
)
def variable_to_meta_info(args):
return map_if(
args,
pred=lambda x: isinstance(x, paddle.static.Variable),
true_fn=lambda x: MetaInfo(
list(x.shape),
x.dtype,
x.stop_gradient,
),
false_fn=lambda x: x,
)
def infer_meta(func, *args, **kwargs):
return VariableCreator().infer_meta(func, *args, **kwargs)
def infer_meta_for_layer(layer, *args, **kwargs):
assert isinstance(
layer, paddle.nn.Layer
), f"Expect a Layer, but got {layer}."
layer = paddle.jit.to_static(layer, enable_fallback=False)
args, kwargs = convert_to_input_spec(args), convert_to_input_spec(kwargs)
concrete_program = layer.forward.get_concrete_program(*args, **kwargs)[0]
out = concrete_program.outputs[0]
out = MetaInfo(
list(out.shape),
out.dtype,
out.stop_gradient,
)
layer.forward.rollback()
return out