-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy pathprogram_translator.py
More file actions
1863 lines (1588 loc) · 65.5 KB
/
program_translator.py
File metadata and controls
1863 lines (1588 loc) · 65.5 KB
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import collections
import inspect
import threading
import warnings
import weakref
from typing import TYPE_CHECKING
import paddle.pir.core as ir_static
from paddle import decomposition, get_flags
from paddle.base import core, framework
from paddle.base.data_feeder import check_type
from paddle.base.dygraph.base import (
_to_static_mode_guard_,
param_guard,
switch_to_static_graph,
)
from paddle.framework import in_dynamic_mode, use_pir_api
from paddle.nn.layer import layers
from paddle.pir import Value
from paddle.pir.core import _convert_into_value, static_op_arg_cast_guard
from paddle.utils import flatten, gast
from . import error, logging_utils
from .function_spec import (
FunctionSpec,
_hash_spec_names,
get_buffers,
get_parameters,
)
from .origin_info import (
attach_origin_info,
create_and_update_origin_info_map,
update_op_callstack_with_origin_info,
)
from .partial_program import PartialProgramLayerHook
from .pir_partial_program import (
PartialProgramLayerHook as PirPartialProgramLayerHook,
)
from .transformers import DygraphToStaticAst
from .utils import (
ALREADY_D2S,
NO_SHAPE_VAR_TYPE,
ast_to_func,
backend_guard,
cuda_pinned_tensors_move_to_excepted_place,
func_to_source_code,
input_specs_compatible,
is_paddle_func,
make_hashable,
prim_is_enabled,
prim_or_cinn_is_enabled,
type_name,
)
if TYPE_CHECKING:
from paddle.static.amp.fp16_utils import AmpOptions
__all__ = []
# For each traced function, we set `max_traced_program_count` = 10 to consider caching performance.
# Once exceeding the threshold, we will raise warning to users to make sure the conversion is as expected.
MAX_TRACED_PROGRAM_COUNT = 10
CONVERSION_OPTIONS = "__jst_not_to_static"
def synchronized(func):
func.__lock__ = threading.Lock()
def lock_func(*args, **kwargs):
with func.__lock__:
return func(*args, **kwargs)
return lock_func
class FunctionCache:
"""
Caches the transformed functions to avoid redundant conversions of the same function.
"""
def __init__(self):
# Caches the converted static functions. {dygraph_func: static_func}
self._converted_static_func_caches = weakref.WeakKeyDictionary()
# Caches the converted ast node for same source code. {source_code: ast_root}
self._code_to_ast_caches = {}
self._dygraph_to_static = DygraphToStaticAst()
def convert_with_cache(self, func):
"""
Returns the cached static function or converts it when first encounters the function.
"""
# If hit cache, return it directly.
static_func = self._converted_static_func_caches.get(func, None)
if static_func is None:
static_func = self._convert(func)
self._converted_static_func_caches[func] = static_func
return static_func
def _convert(self, func):
"""
Converts dygraph function into static function. For two functions with same dedent code,
the second function will reuse the transformed ast node of previous one.
For example:
# A.py
def foo(x, y):
z = x + y
return z
# B.py
def foo(x, y):
z = x + y
return z
If the conversion of A.foo happens after B.foo, it will reuse the transformed ast node of B.foo
to speed up the conversion.
"""
func = inspect.unwrap(func)
source_code = func_to_source_code(func)
# TODO(liym27):
# Consider this case: source_code in self._code_to_ast_caches,
# but actually they are methods in different classes.
# Maybe use (__class__, source_code) as key
if source_code in self._code_to_ast_caches:
root = self._code_to_ast_caches[source_code]
else:
root = gast.parse(source_code)
root = attach_origin_info(root, func)
root = self._dygraph_to_static.get_static_ast(root)
self._code_to_ast_caches[source_code] = root
# Get static function from AST
static_func, file_name = ast_to_func(root, func)
create_and_update_origin_info_map(root, static_func)
return static_func
def exist(self, func):
return func in self._converted_static_func_caches
_CACHE_LOCK = threading.Lock()
_FUNCTION_CACHE = FunctionCache()
def convert_to_static(function):
"""
Transforms function of dygraph into static function using the cache mechanism.
Note(dev): It will return function.__func__ if encountering class method.
Args:
function(callable): The function with dygraph layers that will be converted into static layers.
"""
if getattr(function, ALREADY_D2S, None):
return function
# Return directly if decorated with @not_to_static and DO NOT Cache it
options = getattr(function, CONVERSION_OPTIONS, None)
# or ignore paddle api
need_skip = (options is not None and options.not_convert) or is_paddle_func(
function
)
if need_skip:
return function.__func__ if inspect.ismethod(function) else function
with _CACHE_LOCK:
static_func = _FUNCTION_CACHE.convert_with_cache(function)
setattr(static_func, ALREADY_D2S, True)
return static_func
class CacheKey:
"""
Cached key for ProgramCache.
"""
__slots__ = [
'function_spec',
'input_args_with_spec',
'input_kwargs_with_spec',
'class_instance',
'kwargs',
'_spec_names_id',
'_pir_flags',
]
def __init__(
self,
function_spec,
input_args_with_spec,
input_kwargs_with_spec,
class_instance,
**kwargs,
):
"""
Initializes a cache key.
Args:
functions_spec(FunctionSpec): a FunctionSpec instance of decorated function.
input_args_with_spec(list[InputSpec]): actual input args with some arguments replaced by InputSpec.
input_kwargs_with_spec(list[{string:InputSpec}]): actual input kwargs with some arguments replaced by InputSpec.
class_instance(object): a instance of class `Layer`.
**kwargs(dict): manage other arguments used for better scalability
"""
self.function_spec = function_spec
self.input_args_with_spec = input_args_with_spec
self.input_kwargs_with_spec = input_kwargs_with_spec
self.class_instance = class_instance
# NOTE: `kwargs` is usually not considered as basic member for `__hash__`
self.kwargs = kwargs
self._spec_names_id = _hash_spec_names(
input_args_with_spec, input_kwargs_with_spec
)
self._pir_flags = (
get_flags('FLAGS_enable_pir_in_executor')[
'FLAGS_enable_pir_in_executor'
]
or get_flags('FLAGS_enable_pir_with_pt_in_dy2st')[
'FLAGS_enable_pir_with_pt_in_dy2st'
]
)
@classmethod
def from_func_and_args(cls, function_spec, args, kwargs, class_instance):
"""
Generated a CacheKey instance by given inputs.
Args:
functions_spec(FunctionSpec): a FunctionSpec instance of decorated function.
args(tuple): tuple of actual inputs arguments.
kwargs(dict): dict of actual inputs keyword arguments.
class_instance(object): a instance of class `Layer`.
"""
# 1. filter `self` in args
if args and isinstance(args[0], layers.Layer):
args = args[1:]
# 2. convert tensor and numpy array into InputSpec
_args, _kwargs = function_spec.unified_args_and_kwargs(args, kwargs)
(
input_args_with_spec,
input_kwargs_with_spec,
) = function_spec.args_to_input_spec(_args, _kwargs)
# 3. check whether hit the cache or build a new program for the input arguments
return CacheKey(
function_spec,
input_args_with_spec,
input_kwargs_with_spec,
class_instance,
)
def __hash__(self):
error_msg = "Arguments to a `@paddle.jit.to_static` must be a hashable Python objects (or nested structures of these types)."
with_hook = self.kwargs.get("with_hook", False)
is_train = self.kwargs.get("is_train", False)
return hash(
(
id(self.function_spec),
make_hashable(self.input_args_with_spec, error_msg),
make_hashable(self.input_kwargs_with_spec, error_msg),
self._spec_names_id,
self.class_instance,
with_hook,
is_train,
self._pir_flags,
)
)
def __eq__(self, other):
return (type(self) is type(other)) and hash(self) == hash(other)
def __neq__(self, other):
return not self == other
def __repr__(self):
return "id(function_spec): {}, input_args_with_spec: {}, input_kwargs_with_spec: {}, class_instance: {}".format(
id(self.function_spec),
self.input_args_with_spec,
self.input_kwargs_with_spec,
self.class_instance,
)
def unwrap_decorators(func):
"""
Unwraps a decorated function and returns the decorator list and inner target.
"""
decorators = []
cur = func
while True:
if isinstance(cur, StaticFunction):
decorators.append(cur)
# Note: if `cur` is a method, keep it as bound method of class.
instance = cur._class_instance
if instance is not None:
cur = cur.dygraph_function.__get__(instance)
else:
cur = cur.dygraph_function
else:
break
return decorators, cur
class StaticFunction:
def __init__(self, function, input_spec=None, **kwargs):
"""
Initializes a `StaticFunction`.
Args:
function(callable): A function or method that will be converted into static program.
input_spec(list[InputSpec]): list of InputSpec to specify the `shape/dtype/name` information for each input argument, default None.
**kwargs(dict): other arguments like `build_strategy` et.al.
"""
# save the instance `self` while decorating a method of class.
if inspect.ismethod(function):
self._dygraph_function = function.__func__
self._class_instance = function.__self__
if not hasattr(self._class_instance, '_original_funcs'):
raise TypeError(
"When using 'to_static' to convert method of a class, "
"please ensure the class inherits from nn.Layer"
)
self._class_instance._original_funcs[
function.__name__
] = self._dygraph_function
else:
self._dygraph_function = function
self._class_instance = None
# TODO(chenzhuo): Remove this after lowering prim into C++
if (
input_spec is not None
and prim_is_enabled()
and not core._enable_prim_dynamic_shape()
):
from paddle.static import InputSpec
for spec in flatten(input_spec):
if isinstance(spec, InputSpec) and -1 in spec.shape:
input_spec = None
warnings.warn(
'Now prim and cinn do not support -1 shape, but input_spec has -1 shape so we set it to None.'
)
break
self._input_spec = input_spec
self._function_spec = FunctionSpec(function, input_spec)
self._program_cache = ProgramCache()
self._descriptor_cache = weakref.WeakKeyDictionary()
# Note: Hold a reference to ProgramTranslator for switching `enable_to_static`.
self._program_trans = ProgramTranslator()
self._kwargs = kwargs
self._training = True
self._cuda_graph_capture_mode = ""
self._cuda_graph_pool_id = 0
self._property = kwargs.get("property", False)
self._get_debug_name()
def _get_debug_name(self):
try:
if self._class_instance:
self._debug_name = self._class_instance.__class__.__name__
else:
self._debug_name = self._dygraph_function.__name__
except Exception:
self._debug_name = "static_function"
@property
def is_property(self):
# whether is class proproty to be exported.
return self._property
def train(self):
if (
isinstance(self._class_instance, layers.Layer)
and self._class_instance.training is False
):
raise RuntimeError(
"Failed to switch train mode. {} is a Layer's method, "
"please use Layer.train() to switch train mode.".format(
self.dygraph_function
)
)
self._training = True
def eval(self):
if (
isinstance(self._class_instance, layers.Layer)
and self._class_instance.training is True
):
raise RuntimeError(
"Failed to switch eval mode. {} is a Layer's method, "
"please use Layer.eval() to switch eval mode.".format(
self.dygraph_function
)
)
self._training = False
def __get__(self, instance, owner):
"""
Overrides this method to parse the class instance and call bound method correctly.
For example:
'''
class Net(Layer):
def __init__(self):
pass
@paddle.jit.to_static
def forward(self, x, y):
return x + y
net = Net()
out = net(x, y)
'''
In above case, `net(x, y)` will call `net.forward(x, y)` firstly that is a bound method
of `Net` instance. After decorated by `@paddle.jit.to_static`, it will firstly to call `__get__`
to parse the class instance correctly instead of the `StaticFunction` instance.
"""
if instance not in self._descriptor_cache:
if instance is None:
return self
# Note(Aurelius84): To construct new instance of StaticFunction when we
# first encouter the bound function of layer and cache it.
new_static_layer = self._clone()
if (
isinstance(instance, layers.Layer)
and self._dygraph_function.__name__
not in instance._original_funcs.keys()
):
instance._original_funcs[
self._dygraph_function.__name__
] = self._dygraph_function
new_static_layer._class_instance = instance
self._descriptor_cache[instance] = new_static_layer
return self._descriptor_cache[instance]
def _clone(self):
return self.__class__(
self.dygraph_function, self._input_spec, **self._kwargs
)
def __call__(self, *args, **kwargs):
"""
Supports to call the returned instance with input `args` and `kwargs` directly.
Args:
*args(tuple): tuple of all input arguments from original decorated function.
**kwargs(dict): dict of all input keyward arguments from original decorated function.
Return:
Outputs of decorated function.
"""
if self._property:
return self._call_dygraph_function(*args, **kwargs)
# 1. call dygraph function directly if not enable `declarative`
if not self._program_trans.enable_to_static:
# NOTE(liym27):
# Here calls `warnings.warn` but not `logging_utils.warn` because by default warnings.warn(message)
# will show up **only once**. StaticFunction.__call__ will run many times, it is appropriate to
# display this warning message only once.
logging_utils.warn(
"The decorator '@paddle.jit.to_static' does NOT work when setting 'paddle.jit.enable_to_static' to False. "
"We will just return dygraph output. If you would like to get static graph output, please call API "
"paddle.jit.enable_to_static(True)"
)
return self._call_dygraph_function(*args, **kwargs)
if not in_dynamic_mode():
raise RuntimeError(
f"Failed to run the callable object {self.dygraph_function} decorated by '@paddle.jit.to_static', "
"because it is NOT in dynamic mode. Please disable the static graph mode to enter dynamic mode with the "
"following API: paddle.disable_static()."
)
return self._perform_call(*args, **kwargs)
def _is_train_mode(self):
if self._class_instance is not None:
if not hasattr(self._class_instance, 'training'):
raise TypeError(
"When using 'to_static' to convert method of a class, "
"please ensure the class inherits from nn.Layer"
)
return self._class_instance.training
else:
return self._training
def _call_dygraph_function(self, *args, **kwargs):
"""
Calls dygraph function directly and returns the outputs.
Args:
*args(tuple): tuple of all input arguments from original decorated function.
**kwargs(dict): dict of all input keyward arguments from original decorated function.
Return:
Outputs of dygraph function.
"""
return self.dygraph_function(*args, **kwargs)
def _raise_when_property(self):
"""raise RuntimeError when property=True
Raises:
RuntimeError: can not call this func when property=True
"""
if self.is_property:
raise RuntimeError("Can not call the func when property=True.")
def get_concrete_program(self, *args, **kwargs):
raise NotImplementedError("Not implemented yet.")
def get_concrete_program_with_cache_key(self, cached_key):
raise NotImplementedError("Not implemented yet.")
def get_traced_count(self):
raise NotImplementedError("Not implemented yet.")
@property
def code(self):
raise NotImplementedError("Not implemented yet.")
@property
def dygraph_function(self):
"""
Returns the original decorated function.
"""
if self._class_instance is not None:
return self._dygraph_function.__get__(self._class_instance)
else:
return self._dygraph_function
@property
def concrete_program(self):
raise NotImplementedError("Not implemented yet.")
def concrete_program_specify_input_spec(
self, input_spec=None, with_hook=False, is_prim_infer=False
):
raise NotImplementedError("Not implemented yet.")
def rollback(self):
"""
Rollback into original dygraph functions for current class instance.
Returns:
Function or Method
Example::
.. code-block:: python
>>> # doctest: +SKIP('`paddle.jit.to_static` can not run in xdoctest')
>>> import paddle
>>> class Net(paddle.nn.Layer):
... def __init__(self):
... super().__init__()
...
... def forward(self, x, flag=True):
... if flag:
... out = x + 1
... else:
... out = x - 1
... return out
...
>>> x = paddle.randn([10, 1], 'float32')
>>> net = paddle.jit.to_static(Net()) # convert into static graph mode
>>> out = net(x)
>>> net.forward.rollback() # rollback into dygraph mode
>>> out = net(x)
"""
def rollback_impl(class_instance):
for name, func in class_instance._original_funcs.items():
setattr(class_instance, name, func.__get__(class_instance))
for sublayer in class_instance.sublayers(include_self=False):
rollback_impl(sublayer)
if self._class_instance is None:
return self._dygraph_function
# only rollback sub-functions on path of top _dygraph_function
func_name = self._dygraph_function.__name__
assert (
func_name in self._class_instance._original_funcs
), "Not Found function '{}' in class '{}'.".format(
func_name, self._class_instance.__class__
)
func = self._class_instance._original_funcs[func_name]
setattr(
self._class_instance, func_name, func.__get__(self._class_instance)
)
for sublayer in self._class_instance.sublayers(include_self=False):
rollback_impl(sublayer)
return getattr(self._class_instance, func_name)
def __deepcopy__(self, memo):
"""
Customized behavior for copy.deepcopy, return original decorated function instead
of a new StaticFunction Object. StaticFunction itself is not copyable becuase it's
associated with class_instance.
We add __deepcopy__ here only for the following usage:
Example::
.. code-block:: python
>>> import copy
>>> import paddle
>>> class Net(paddle.nn.Layer):
... def __init__(self):
... super().__init__()
...
... def forward(self, x, flag=True):
... if flag:
... out = x + 1
... else:
... out = x - 1
... return out
...
>>> x = paddle.randn([10, 1], 'float32')
>>> net = paddle.jit.to_static(Net()) # convert into static graph mode
>>> copy_net = copy.deepcopy(net) # deepcopy a new net without @to_static
Please attention that original 'net' will unwrap @to_static and rollback into simple Layer.
"""
if self._class_instance is not None:
net_name = type(self._class_instance).__name__
logging_utils.log(
level=-1,
msg="Not recommend to deepcopy '{}' decorated with @to_static, it has side effect that will"
" rollback into original state before @to_static. Please deepcopy '{}' before applying @to_static.".format(
net_name, net_name
),
)
self.rollback()
return self._dygraph_function.__get__(
memo[id(self._class_instance)]
)
else:
return self._dygraph_function
@property
def inputs(self):
raise NotImplementedError("Not implemented yet.")
@property
def outputs(self):
raise NotImplementedError("Not implemented yet.")
@property
def main_program(self):
raise NotImplementedError("Not implemented yet.")
@property
def program_cache(self):
raise NotImplementedError("Not implemented yet.")
@property
def function_spec(self):
raise NotImplementedError("Not implemented yet.")
def raise_error_template(func_str):
def _raise_error(*args, **kwargs):
error_template = (
"Can't call {func} when full_graph=False. "
"Use paddle.jit.to_static(full_graph=True) instead."
)
raise RuntimeError(error_template.format(func=func_str))
return _raise_error
class SymbolicStaticFunction(StaticFunction):
def __init__(self, function, input_spec=None, **kwargs):
if input_spec is not None:
warnings.warn(
"full_graph=False don't support input_spec arguments. It will not produce any effect.\n"
"You can set full_graph=True, then you can assign input spec.\n"
)
super().__init__(function, input_spec, **kwargs)
self.last_call_input_spec = None
def _perform_call(self, *args, **kwargs):
from ..sot import symbolic_translate
args, kwargs = self._function_spec.unified_args_and_kwargs(args, kwargs)
cuda_pinned_tensors_move_to_excepted_place(args)
(
input_args_with_spec,
input_kwargs_with_spec,
) = self._function_spec.args_to_input_spec(args, kwargs)
self.last_call_input_spec = input_args_with_spec
build_strategy = self._kwargs.get("build_strategy", None)
backend = self._kwargs.get("backend", None)
traced_fun = symbolic_translate(
self._dygraph_function,
build_strategy=build_strategy,
training=self._is_train_mode(),
backend=backend,
)
if self._class_instance is not None:
args = (self._class_instance,) + args
return traced_fun(*args, **kwargs)
@property
def code(self):
raise_error_template("code")()
@property
def concrete_program(self):
raise_error_template("concrete_program")()
concrete_program_specify_input_spec = raise_error_template(
"concrete_program_specify_input_spec"
)
get_concrete_program = raise_error_template("get_concrete_program")
get_concrete_program_with_cache_key = raise_error_template(
"get_concrete_program_with_cache_key"
)
get_traced_count = raise_error_template("get_traced_count")
@property
def inputs(self):
raise_error_template("inputs")()
@property
def outputs(self):
raise_error_template("outputs")()
@property
def main_program(self):
raise_error_template("main_program")()
@property
def program_cache(self):
raise_error_template("program_cache")()
@property
def function_spec(self):
raise_error_template("function_spec ")()
class ASTStaticFunction(StaticFunction):
"""
Wrapper class to Manage program conversion of decorated function.
"""
def __init__(self, function, input_spec=None, **kwargs):
super().__init__(function, input_spec, **kwargs)
def _perform_call(self, *args, **kwargs):
# 1. trace ops from dygraph layers and cache the generated program.
args, kwargs = self._function_spec.unified_args_and_kwargs(args, kwargs)
try:
_, partial_program_layer = self.get_concrete_program(
*args, **kwargs, is_train=self._is_train_mode()
)
# 2. synchronize self.training attribute.
if isinstance(self._class_instance, layers.Layer):
partial_program_layer.training = self._class_instance.training
else:
partial_program_layer.training = self._training
partial_program_layer._cuda_graph_capture_mode = (
self._cuda_graph_capture_mode
)
partial_program_layer._cuda_graph_pool_id = self._cuda_graph_pool_id
# 3. return outputs.
try:
return partial_program_layer(args)
except Exception as e:
if not hasattr(e, error.ERROR_DATA):
# runtime error
error.attach_error_data(e, in_runtime=True)
raise
except Exception as e:
error_data = getattr(e, error.ERROR_DATA, None)
if error_data:
error_data.raise_new_exception()
else:
logging_utils.warn(
"Please file an issue at 'https://github.com/PaddlePaddle/Paddle/issues'"
f" if you can't handle this {type(e)} yourself."
)
raise e
def get_concrete_program(self, *args, **kwargs):
"""
Returns traced concrete program and inner executable partial layer.
Args:
*args(tuple): input arguments values or InputSpec
**kwargs(dict) : input kwargs values.
Returns:
Traced ConcreteProgram and executable translated Layer.
"""
self._raise_when_property()
with_hook = kwargs.get("with_hook", False)
is_train = kwargs.get("is_train", True)
is_prim_infer = kwargs.get("is_prim_infer", False)
if "is_train" in kwargs:
kwargs.pop("is_train")
if "with_hook" in kwargs:
kwargs.pop("with_hook")
if "is_prim_infer" in kwargs:
kwargs.pop("is_prim_infer")
# 1. unify args/kwargs and replace Tensor with InputSpec
if len(args) != len(self._function_spec.args_name):
args, kwargs = self._function_spec.unified_args_and_kwargs(
args, kwargs
)
(
input_args_with_spec,
input_kwargs_with_spec,
) = self._function_spec.args_to_input_spec(args, kwargs)
# 2. generate cache key
cache_key = CacheKey(
self._function_spec,
input_args_with_spec,
input_kwargs_with_spec,
self._class_instance,
**self._kwargs,
with_hook=with_hook,
is_train=is_train,
)
if is_prim_infer:
(
concrete_program,
partial_program_layer,
) = self._program_cache.get_program_without_cache(cache_key)
else:
# 3. check whether hit the cache or build a new program for the input arguments
concrete_program, partial_program_layer = self._program_cache[
cache_key
]
partial_program_layer._debug_name = self._debug_name
return concrete_program, partial_program_layer
def get_concrete_program_with_cache_key(self, cached_key):
"""
Returns traced concrete program and inner executable partial layer by cached key.
Args:
cached_key(CacheKey): The cached key use to get concrete program.
Returns:
Traced ConcreteProgram and executable translated Layer.
"""
self._raise_when_property()
(
concrete_program,
partial_program_layer,
) = self._program_cache.get_program_without_cache(cached_key)
return concrete_program, partial_program_layer
def get_traced_count(self):
"""
Returns the number of traced programs for the decorated function.
"""
return len(self._program_cache)
@property
def code(self):
"""
Returns the source code of transformed static function for debugging.
"""
static_func = convert_to_static(self.dygraph_function)
source_code = func_to_source_code(static_func)
return source_code
@property
def concrete_program(self):
"""
Returns recent ConcreteProgram instance of decorated function.
Examples:
.. code-block:: python
>>> # doctest: +SKIP('`paddle.jit.to_static` can not run in xdoctest')
>>> import paddle
>>> from paddle.jit import to_static
>>> from paddle.static import InputSpec
>>> paddle.disable_static()
>>> def foo(x, y):
... z = x + y
... return z
...
>>> # usage 1:
>>> decorated_foo = to_static(foo, input_spec=[InputSpec([10], name='x'), InputSpec([10], name='y')])
>>> print(decorated_foo.concrete_program)
>>> # usage 2:
>>> decorated_foo = to_static(foo)
>>> out_foo = decorated_foo(paddle.rand([10]), paddle.rand([10]))
>>> print(decorated_foo.concrete_program)
"""
return self.concrete_program_specify_input_spec(input_spec=None)
def concrete_program_specify_input_spec(
self, input_spec=None, with_hook=False, is_prim_infer=False
):
"""
Returns recent ConcreteProgram instance of decorated function while
specifying input_spec. If the self._function_spec already has
input_spec, it will check the compatibility of input input_spec and
the self._function_spec.input_spec. If input input_spec=None, then
this method uses self._function_spec.input_spec
args:
input_spec (list[InputSpec], optional): Describes the input of
the translate function.
"""
self._raise_when_property()
# if specific the `input_spec`, the length of program_cache will always 1,
# else, return the last one.
cached_program_len = len(self._program_cache)
# If specific `input_spec`, apply convertion from dygraph layers into static Program.
# NOTE(jiabin): is_prim_infer indicates this method called by paddle.jit.save and it is worked in prim mode
desired_input_spec = input_spec
if self._function_spec.input_spec is not None:
if input_spec is not None and not input_specs_compatible(
flatten(input_spec), flatten(self._function_spec.input_spec)
):
raise ValueError(
"The `input_spec`: {} used to construct concrete_program is conflict with the `input_spec`: {} in `@paddle.jit.to_static`".format(
input_spec, self._function_spec.input_spec
)
)
# NOTE(chenweihang): we should always translated program based on the `input_spec`
# decorated on forward if it is valid
desired_input_spec = self._function_spec.input_spec
if input_spec is not None:
logging_utils.warn(
"\n\nYou have specified `input_spec` both in function definition (higher priority) and `paddle.jit.save` (will be ignored.)\n\n\t Using: {}\n\n\t Ignore: {}\n".format(
desired_input_spec, input_spec
)
)
has_input_spec = desired_input_spec is not None
if has_input_spec:
concrete_program, _ = self.get_concrete_program(
*desired_input_spec,
with_hook=with_hook,
is_train=self._is_train_mode(),
is_prim_infer=is_prim_infer,
)
return concrete_program
else:
if cached_program_len != 0:
logging_utils.warn(
"No input_spec is found, save cached program instead"
)
if cached_program_len > 1:
logging_utils.warn(