-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
api.py
1871 lines (1563 loc) · 67.1 KB
/
api.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
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) 2019 PaddlePaddle Authors. All Rights Reserved.
# Copyright (c) 2021 NVIDIA Corporation. 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.
# Temporary disable isort to avoid circular import
# This can be removed after the circular import is resolved
# isort: skip_file
from __future__ import annotations
import os
import pickle
import warnings
from collections import OrderedDict
import inspect
import threading
from typing import Any
import paddle
from paddle.fluid import core, dygraph
from paddle.fluid.compiler import (
BuildStrategy,
CompiledProgram,
ExecutionStrategy,
)
from paddle.fluid.data_feeder import check_type
from paddle.fluid.dygraph.base import (
program_desc_tracing_guard,
switch_to_static_graph,
)
from .dy2static import logging_utils
from .dy2static.convert_call_func import (
ConversionOptions,
add_ignore_module,
)
from .dy2static.program_translator import (
ProgramTranslator,
StaticFunction,
unwrap_decorators,
)
from paddle.jit.translated_layer import (
TranslatedLayer,
INFER_MODEL_SUFFIX,
INFER_PARAMS_SUFFIX,
INFER_PARAMS_INFO_SUFFIX,
INFER_PROPERTY_SUFFIX,
)
from paddle.nn import Layer
from paddle.fluid.executor import Executor, scope_guard
from paddle.fluid.framework import (
Block,
Program,
Variable,
Parameter,
EagerParamBase,
)
from paddle.fluid.framework import (
_current_expected_place,
_dygraph_guard,
_dygraph_tracer,
)
from paddle.fluid.framework import dygraph_only
from paddle.fluid.wrapped_decorator import wrap_decorator
from paddle.fluid.io import save_inference_model
from paddle.framework import in_dynamic_mode
def create_program_from_desc(program_desc):
program = Program()
program.desc = program_desc
program.blocks = [Block(program, 0)]
program._sync_with_cpp()
return program
def _extract_vars(inputs, result_list, err_tag='inputs'):
if isinstance(inputs, Variable):
result_list.append(inputs)
elif isinstance(inputs, (list, tuple)):
for var in inputs:
_extract_vars(var, result_list, err_tag)
else:
raise TypeError(
"The type of 'each element of {}' in paddle.jit.TracedLayer.trace must be fluid.Variable, but received {}.".format(
err_tag, type(inputs)
)
)
def extract_vars(inputs, err_tag='inputs'):
result_list = []
_extract_vars(inputs, result_list, err_tag)
return result_list
def _dygraph_to_static_func_(dygraph_func):
"""
Converts imperative dygraph APIs into declarative function APIs. Decorator
@dygraph_to_static_func only converts imperative dygraph APIs into
declarative net-building APIs, which means it doesn't return immediate
digital result as imperative mode. Users should handle Program and Executor
by themselves.
Note:
This decorator is NOT our recommended way to transform imperative function
to declarative function. We will remove this decorator after we finalize
cleaning up code.
Args:
dygraph_func (callable): callable imperative function.
Returns:
Callable: converting imperative dygraph APIs into declarative
net-building APIs.
Examples:
.. code-block:: python
import paddle
import paddle.fluid as fluid
import numpy as np
from paddle.jit.api import dygraph_to_static_func
@dygraph_to_static_func
def func(x):
if paddle.mean(x) < 0:
x_v = x - 1
else:
x_v = x + 1
return x_v
x = paddle.full(shape=[3, 3], fill_value=0, dtype='float64')
x_v = func(x)
exe = fluid.Executor(fluid.CPUPlace())
out = exe.run(fetch_list=[x_v])
print(out[0])
# [[1. 1. 1.]
# [1. 1. 1.]
# [1. 1. 1.]]
"""
# TODO: remove this decorator after we finalize training API
def __impl__(*args, **kwargs):
program_translator = ProgramTranslator()
if in_dynamic_mode() or not program_translator.enable_to_static:
logging_utils.warn(
"The decorator 'dygraph_to_static_func' doesn't work in "
"dygraph mode or set 'paddle.jit.enable_to_static' to False. "
"We will just return dygraph output."
)
return dygraph_func(*args, **kwargs)
static_func = program_translator.get_func(dygraph_func)
return static_func(*args, **kwargs)
return __impl__
dygraph_to_static_func = wrap_decorator(_dygraph_to_static_func_)
def copy_decorator_attrs(original_func, decorated_obj):
"""
Copies some necessary attributes from original function into decorated function.
Args:
original_func(callable): the original decorated function.
decorated_obj(StaticFunction): the target decorated StaticFunction object.
"""
decorator_name = "to_static"
decorated_obj.__name__ = original_func.__name__
decorated_obj._decorator_name = decorator_name
decorated_obj.__wrapped__ = original_func
decorated_obj.__doc__ = original_func.__doc__
if hasattr(original_func, "__module__"):
decorated_obj.__module__ = original_func.__module__
return decorated_obj
def ignore_module(modules: list[Any]):
"""
Adds modules that ignore transcription.
Builtin modules that have been ignored are collections, pdb, copy, inspect, re, numpy, logging, six
Args:
modules (List[Any]): Ignored modules that you want to add
Examples:
.. code-block:: python
import scipy
import astor
import paddle
from paddle.jit import ignore_module
modules = [
scipy,
astor
]
ignore_module(modules)
"""
add_ignore_module(modules)
def _check_and_set_backend(backend, build_strategy):
if backend not in ['CINN', None]:
raise ValueError(
"The backend of to_static should be 'CINN' or None, but received {}.".format(
backend
)
)
if backend == 'CINN':
build_strategy.build_cinn_pass = True
def to_static(
function=None,
input_spec=None,
build_strategy=None,
backend=None,
**kwargs,
):
"""
Converts imperative dygraph APIs into declarative function APIs. Decorator
@to_static handles the Program and Executor of static graph mode and returns
the result as dygraph Tensor(s). Users could use the returned dygraph
Tensor(s) to do imperative training, inference, or other operations. If the
decorated function calls other imperative function, the called one will be
converted into declarative function as well.
Args:
function (callable): callable imperative function.
input_spec(list[InputSpec]|tuple[InputSpec]): list/tuple of InputSpec to specific the shape/dtype/name
information of each input Tensor.
build_strategy(BuildStrategy|None): This argument is used to compile the
converted program with the specified options, such as operators' fusion
in the computational graph and memory optimization during the execution
of the computational graph. For more information about build_strategy,
please refer to :code:`paddle.static.BuildStrategy`. The default is None.
backend(str, Optional): Specifies compilation backend, which can be `CINN` or None. When backend is `CINN`, CINN compiler will be used to speed up training and inference.
kwargs: Support keys including `property`, set `property` to True if the fucntion is python property.
Returns:
Tensor(s): containing the numerical result.
Examples:
.. code-block:: python
import paddle
from paddle.jit import to_static
@to_static
def func(x):
if paddle.mean(x) < 0:
x_v = x - 1
else:
x_v = x + 1
return x_v
x = paddle.ones([1, 2], dtype='float32')
x_v = func(x)
print(x_v) # [[2. 2.]]
"""
property = kwargs.get("property", False)
def decorated(python_func):
"""
Decorates a python function into a StaticFunction object.
"""
# Step 1. unwrap the function if it is already decorated.
_, python_func = unwrap_decorators(python_func)
# Step 2. copy some attributes from original python function.
static_layer = copy_decorator_attrs(
original_func=python_func,
decorated_obj=StaticFunction(
function=python_func,
input_spec=input_spec,
build_strategy=build_strategy,
property=property,
backend=backend,
),
)
return static_layer
build_strategy = build_strategy or BuildStrategy()
if not isinstance(build_strategy, BuildStrategy):
raise TypeError(
"Required type(build_strategy) shall be `paddle.static.BuildStrategy`, but received {}".format(
type(build_strategy).__name__
)
)
_check_and_set_backend(backend, build_strategy)
# for usage: `to_static(foo, ...)`
if function is not None:
if isinstance(function, Layer):
if isinstance(function.forward, StaticFunction):
class_name = function.__class__.__name__
logging_utils.warn(
"`{}.forward` has already been decorated somewhere. It will be redecorated to replace previous one.".format(
class_name
)
)
function.forward = decorated(function.forward)
return function
else:
return decorated(function)
# for usage: `@to_static`
return decorated
def not_to_static(func=None):
"""
A Decorator to suppresses the convertion of a function.
Args:
func(callable): The function to decorate.
Returns:
callable: A function which won't be converted in Dynamic-to-Static.
Examples:
.. code-block:: python
import paddle
@paddle.jit.not_to_static
def func_not_to_static(x):
res = x - 1
return res
@paddle.jit.to_static
def func(x):
if paddle.mean(x) < 0:
out = func_not_to_static(x)
else:
out = x + 1
return out
x = paddle.ones([1, 2], dtype='float32')
out = func(x)
print(out) # [[2. 2.]]
"""
if func is None:
return not_to_static
options = ConversionOptions(not_convert=True)
options.attach(func)
return func
class _SaveLoadConfig:
def __init__(self):
self._output_spec = None
self._model_filename = None
self._params_filename = None
self._separate_params = False
# used for `paddle.load`
self._keep_name_table = False
# NOTE: Users rarely use following configs, so these configs are not open to users,
# reducing user learning costs, but we retain the configuration capabilities
# If True, programs are modified to only support direct inference deployment.
# Otherwise,more information will be stored for flexible optimization and re-training.
# Currently, only True is supported
self._export_for_deployment = True
# If True, It will save inference program only, and do not save params of Program
self._program_only = False
self.with_hook = False
# if True, multi `StaticFunction` will share params in one file.
self.combine_params = False
@property
def output_spec(self):
return self._output_spec
@output_spec.setter
def output_spec(self, spec):
if spec is None:
return
if not isinstance(spec, list):
raise TypeError(
"The config `output_spec` should be 'list', but received input type is %s."
% type(input)
)
for var in spec:
if not isinstance(var, core.eager.Tensor):
raise TypeError(
"The element in config `output_spec` list should be 'Variable', but received element's type is %s."
% type(var)
)
self._output_spec = spec
@property
def model_filename(self):
return self._model_filename
@model_filename.setter
def model_filename(self, filename):
if filename is None:
return
if not isinstance(filename, str):
raise TypeError(
"The config `model_filename` should be str, but received input's type is %s."
% type(filename)
)
if len(filename) == 0:
raise ValueError("The config `model_filename` is empty string.")
self._model_filename = filename
@property
def params_filename(self):
return self._params_filename
@params_filename.setter
def params_filename(self, filename):
if filename is None:
return
if not isinstance(filename, str):
raise TypeError(
"The config `params_filename` should be str, but received input's type is %s."
% type(filename)
)
if len(filename) == 0:
raise ValueError("The config `params_filename` is empty string.")
self._params_filename = filename
@property
def keep_name_table(self):
return self._keep_name_table
@keep_name_table.setter
def keep_name_table(self, value):
if value is None:
return
if not isinstance(value, bool):
raise TypeError(
"The config `keep_name_table` should be bool value, but received input's type is %s."
% type(value)
)
self._keep_name_table = value
def _parse_save_configs(configs):
supported_configs = [
'output_spec',
"with_hook",
"combine_params",
"clip_extra",
"skip_forward",
]
# input check
for key in configs:
if key not in supported_configs:
raise ValueError(
"The additional config (%s) of `paddle.jit.save` is not supported."
% (key)
)
# construct inner config
inner_config = _SaveLoadConfig()
inner_config.output_spec = configs.get('output_spec', None)
inner_config.with_hook = configs.get('with_hook', False)
inner_config.combine_params = configs.get("combine_params", False)
inner_config.clip_extra = configs.get("clip_extra", True)
inner_config.skip_forward = configs.get("skip_forward", False)
return inner_config
def _parse_load_config(configs):
supported_configs = ['model_filename', 'params_filename']
# input check
for key in configs:
if key not in supported_configs:
raise ValueError(
"The additional config (%s) of `paddle.jit.load` is not supported."
% (key)
)
# construct inner config
inner_config = _SaveLoadConfig()
inner_config.model_filename = configs.get('model_filename', None)
inner_config.params_filename = configs.get('params_filename', None)
return inner_config
def _get_input_var_names(inputs, input_spec):
name_none_error = (
"The %s's name is None. "
"When using jit.save, please set InputSepc's name in "
"to_static(input_spec=[]) and jit.save(input_spec=[]) "
"and make sure they are consistent."
)
name_no_exists_error = (
"The tensor `%s` does not exists. "
"Please make sure the name of InputSpec or example Tensor "
"in input_spec is the same as the name of InputSpec in "
"`to_static` decorated on the Layer.forward method."
)
result_list = []
input_var_names = [
var.name
for var in paddle.utils.flatten(inputs)
if isinstance(var, Variable)
]
if input_spec is None:
# no prune
return input_var_names
else:
# fileter out non-tensor type spec infos.
input_spec = [
spec
for spec in input_spec
if isinstance(spec, paddle.static.InputSpec)
]
if len(input_spec) == len(input_var_names):
# no prune
result_list = input_var_names
# if input spec name not in input_var_names, only raise warning
for spec in input_spec:
if spec.name is None:
warnings.warn(name_none_error % spec)
elif spec.name not in input_var_names:
warnings.warn(name_no_exists_error % spec.name)
else:
# do nothing
pass
else:
# prune
for spec in input_spec:
if spec.name is None:
# name is None, the input_spec only can be InputSpec
raise ValueError(name_none_error % spec)
elif spec.name not in input_var_names:
# the input_spec can be `InputSpec` or `Tensor`
raise ValueError(name_no_exists_error % spec.name)
else:
result_list.append(spec.name)
return result_list
def _get_output_vars(outputs, output_spec, with_hook=False):
name_no_exists_error = (
"The tensor `%s` does not exists. "
"Please make sure the name of example Tensor "
"in configs.output_spec is the output tensor of "
"Layer.forward method."
)
if output_spec and with_hook:
raise RuntimeError(
"Currently not support specify output_spec while founding pre/post hooks in your outermost layer."
)
result_list = []
output_vars_dict = OrderedDict()
for var in paddle.utils.flatten(outputs):
if isinstance(var, Variable):
output_vars_dict[var.name] = var
if output_spec is None:
result_list = list(output_vars_dict.values())
elif output_spec is not None and len(output_spec) == len(output_vars_dict):
result_list = list(output_vars_dict.values())
for var in output_spec:
if var.name not in output_vars_dict:
warnings.warn(name_no_exists_error % var.name)
else:
for var in output_spec:
if var.name not in output_vars_dict:
raise ValueError(name_no_exists_error % var.name)
else:
result_list.append(output_vars_dict[var.name])
return result_list
# NOTE(chenweihang): [ Handling of use cases of API paddle.jit.load ]
# `paddle.jit.load` may be used to load saved results of:
# 1. Expected cases:
# - paddle.jit.save
# - paddle.static.save_inference_model
# - paddle.fluid.io.save_inference_model
# 2. Error cases:
# - paddle.save: no .pdmodel for prefix
# - paddle.static.save: no .pdiparams but .pdparams exists
# - paddle.fluid.io.save_params/save_persistables: no __model__
# TODO(chenweihang): polish error message in above error cases
def _build_load_path_and_config(path, config):
# NOTE(chenweihang): If both [prefix save format] and [directory save format] exist,
# raise error, avoid confusing behavior
prefix_format_path = path + INFER_MODEL_SUFFIX
prefix_format_exist = os.path.exists(prefix_format_path)
directory_format_exist = os.path.isdir(path)
if prefix_format_exist and directory_format_exist:
raise ValueError(
"The {}.pdmodel and {} directory exist at the same time, "
"don't know which one to load, please make sure that the specified target "
"of ``path`` is unique.".format(path, path)
)
elif not prefix_format_exist and not directory_format_exist:
raise ValueError(
"The ``path`` (%s) to load model not exists. "
"Please make sure that *.pdmodel exists or "
"don't using ``skip_forward=True`` to jit.save." % path
)
else:
if prefix_format_exist:
file_prefix = os.path.basename(path)
model_path = os.path.dirname(path)
if config.model_filename is not None:
warnings.warn(
"When loading the result saved with the "
"specified file prefix, the ``model_filename`` config does "
"not take effect."
)
config.model_filename = file_prefix + INFER_MODEL_SUFFIX
if config.params_filename is not None:
warnings.warn(
"When loading the result saved with the "
"specified file prefix, the ``params_filename`` config does "
"not take effect."
)
config.params_filename = file_prefix + INFER_PARAMS_SUFFIX
else:
# Compatible with the old save_inference_model format
model_path = path
return model_path, config
_save_pre_hooks_lock = threading.Lock()
_save_pre_hooks = []
class HookRemoveHelper:
"""A HookRemoveHelper that can be used to remove hook."""
def __init__(self, hook):
self._hook = hook
def remove(self):
_remove_save_pre_hook(self._hook)
def _register_save_pre_hook(hook):
"""
Register a save pre-hook for `paddle.jit.save`.
This hook will be executed before `save` function has been invoked.
hook(layer, input_spec, configs) -> None
- layer (Layer|function): This argument is corresponding to `layer` in `paddle.jit.save`.
- input_spec (list or tuple[InputSpec|Tensor|Python built-in variable]): This argument is corresponding to `input_spec` in `paddle.jit.save`.
- configs (dict): This argument is corresponding to `configs` in `paddle.jit.save`.
Args:
hook(function): a function registered as a save pre-hook
Returns:
HookRemoveHelper: a HookRemoveHelper object that can be used to remove the added hook by calling `hook_remove_helper.remove()`.
Examples:
.. code-block:: python
import numpy as np
import paddle
IMAGE_SIZE = 256
CLASS_NUM = 10
class LinearNet(paddle.nn.Layer):
def __init__(self):
super().__init__()
self._linear = paddle.nn.Linear(IMAGE_SIZE, CLASS_NUM)
def forward(self, x):
return self._linear(x)
saving_count = 0
def save_pre_hook(layer, input_spec, configs):
global saving_count
saving_count += 1
remove_handler = paddle.jit.register_save_pre_hook(save_pre_hook)
layer = LinearNet()
paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])])
# saving_count == 1
remove_handler.remove()
paddle.jit.save(layer, "/tmp", [paddle.static.InputSpec(shape=[-1, IMAGE_SIZE])])
# saving_count == 1
"""
global _save_pre_hooks_lock
global _save_pre_hooks
_save_pre_hooks_lock.acquire()
if hook not in _save_pre_hooks:
_save_pre_hooks.append(hook)
_save_pre_hooks_lock.release()
return HookRemoveHelper(hook)
def _clear_save_pre_hooks():
global _save_pre_hooks_lock
global _save_pre_hooks
_save_pre_hooks_lock.acquire()
_save_pre_hooks.clear()
_save_pre_hooks_lock.release()
def _remove_save_pre_hook(hook):
global _save_pre_hooks_lock
global _save_pre_hooks
_save_pre_hooks_lock.acquire()
if hook in _save_pre_hooks:
_save_pre_hooks.remove(hook)
_save_pre_hooks_lock.release()
@wrap_decorator
def _run_save_pre_hooks(func):
def wrapper(layer, path, input_spec=None, **configs):
global _save_pre_hooks
for hook in _save_pre_hooks:
hook(layer, input_spec, configs)
func(layer, path, input_spec, **configs)
return wrapper
def _save_property(filename: str, property_vals: list[tuple[Any, str]]):
"""class property serialization.
Args:
filename (str): *.meta
property_vals (list[tuple[Any, str]]): class property.
"""
def set_property(meta, key, val):
if isinstance(val, float):
meta.set_float(key, val)
elif isinstance(val, int):
meta.set_int(key, val)
elif isinstance(val, str):
meta.set_string(key, val)
elif isinstance(val, (tuple, list)):
if isinstance(val[0], float):
meta.set_floats(key, val)
elif isinstance(val[0], int):
meta.set_ints(key, val)
elif isinstance(val[0], str):
meta.set_strings(key, val)
else:
raise ValueError(f"Note support val type: {type(val)}")
return
with open(filename, 'wb') as f:
meta = paddle.framework.core.Property()
for item in property_vals:
val, key = item[0], item[1]
set_property(meta, key, val)
f.write(meta.serialize_to_string())
@_run_save_pre_hooks
@switch_to_static_graph
def save(layer, path, input_spec=None, **configs):
"""
Saves input Layer or function as ``paddle.jit.TranslatedLayer``
format model, which can be used for inference or fine-tuning after loading.
It will save the translated program and all related persistable
variables of input Layer to given ``path`` .
``path`` is the prefix of saved objects, and the saved translated program file
suffix is ``.pdmodel`` , the saved persistable variables file suffix is ``.pdiparams`` ,
and here also saved some additional variable description information to a file,
its suffix is ``.pdiparams.info``, these additional information is used in fine-tuning.
The saved model can be loaded by follow APIs:
- ``paddle.jit.load``
- ``paddle.static.load_inference_model``
- Other C++ inference APIs
.. note::
When using ``paddle.jit.save`` to save a function, parameters will not be saved. If you have to
save the parameter, please pass the Layer containing function and parameter to ``paddle.jit.save``.
Args:
layer (Layer|function): The Layer or function to be saved.
path (str): The path prefix to save model. The format is ``dirname/file_prefix`` or ``file_prefix``.
input_spec (list or tuple[InputSpec|Tensor|Python built-in variable], optional): Describes the input of the saved model's forward
method, which can be described by InputSpec or example Tensor. Moreover, we support to specify non-tensor type argument,
such as int, float, string, or list/dict of them.If None, all input variables of
the original Layer's forward method would be the inputs of the saved model. Default None.
**configs (dict, optional): Other save configuration options for compatibility. We do not
recommend using these configurations, they may be removed in the future. If not necessary,
DO NOT use them. Default None.
The following options are currently supported:
(1) output_spec (list[Tensor]): Selects the output targets of the saved model.
By default, all return variables of original Layer's forward method are kept as the
output of the saved model. If the provided ``output_spec`` list is not all output variables,
the saved model will be pruned according to the given ``output_spec`` list.
Returns:
None
Examples:
.. code-block:: python
# example 1: save layer
import numpy as np
import paddle
import paddle.nn as nn
import paddle.optimizer as opt
BATCH_SIZE = 16
BATCH_NUM = 4
EPOCH_NUM = 4
IMAGE_SIZE = 784
CLASS_NUM = 10
# define a random dataset
class RandomDataset(paddle.io.Dataset):
def __init__(self, num_samples):
self.num_samples = num_samples
def __getitem__(self, idx):
image = np.random.random([IMAGE_SIZE]).astype('float32')
label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
return image, label
def __len__(self):
return self.num_samples
class LinearNet(nn.Layer):
def __init__(self):
super().__init__()
self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
@paddle.jit.to_static
def forward(self, x):
return self._linear(x)
def train(layer, loader, loss_fn, opt):
for epoch_id in range(EPOCH_NUM):
for batch_id, (image, label) in enumerate(loader()):
out = layer(image)
loss = loss_fn(out, label)
loss.backward()
opt.step()
opt.clear_grad()
print("Epoch {} batch {}: loss = {}".format(
epoch_id, batch_id, np.mean(loss.numpy())))
# 1. train & save model.
# create network
layer = LinearNet()
loss_fn = nn.CrossEntropyLoss()
adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())
# create data loader
dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
loader = paddle.io.DataLoader(dataset,
batch_size=BATCH_SIZE,
shuffle=True,
drop_last=True,
num_workers=2)
# train
train(layer, loader, loss_fn, adam)
# save
path = "example_model/linear"
paddle.jit.save(layer, path)
# example 2: save function
import paddle
from paddle.static import InputSpec
def save_function():
@paddle.jit.to_static
def fun(inputs):
return paddle.tanh(inputs)
path = 'test_jit_save_load_function_1/func'
inps = paddle.rand([3, 6])
origin = fun(inps)
paddle.jit.save(fun, path)
load_func = paddle.jit.load(path)
load_result = load_func(inps)
print((load_result - origin).abs().max() < 1e-10)
save_function()
"""
# 1. input build & check
prog_translator = ProgramTranslator()
is_prim_infer = core._is_fwd_prim_enabled() and core._is_bwd_prim_enabled()
if not prog_translator.enable_to_static:
raise RuntimeError(
"The paddle.jit.save doesn't work when setting 'paddle.jit.enable_to_static' to False."
)
if not (
isinstance(layer, (Layer, StaticFunction)) or inspect.isfunction(layer)
):
raise TypeError(
"The input of paddle.jit.save should be 'Layer' or 'Function', but received input type is %s."
% type(layer)
)
elif inspect.isfunction(layer) or isinstance(layer, StaticFunction):
warnings.warn(
'What you save is a function, and `jit.save` will generate the name of the model file according to `path` you specify. When loading these files with `jit.load`, you get a `TranslatedLayer` whose inference result is the same as the inference result of the function you saved.'
)
# NOTE(chenweihang): If the input layer be wrapped by DataParallel,
# the args and kwargs of forward method will can't be parsed by
# function_spec, so here we save DataParallel._layers instead
# DataParallel it self
# NOTE(chenweihang): using inner_layer, do not change input layer
if isinstance(layer, paddle.DataParallel):
inner_layer = layer._layers
else:
inner_layer = layer
# path check
file_prefix = os.path.basename(path)
if file_prefix == "":
raise ValueError(
"The input path MUST be format of dirname/file_prefix "
"[dirname\\file_prefix in Windows system], but received "
"file_prefix is empty string."
)
dirname = os.path.dirname(path)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
# avoid change user given input_spec
inner_input_spec = None
if input_spec is not None:
if isinstance(layer, Layer):
for attr_func in dir(inner_layer):
static_func = getattr(inner_layer, attr_func, None)
if (
isinstance(static_func, StaticFunction)
and 'forward' != attr_func
):
raise ValueError(
"If there are static functions other than 'forward' that need to be saved, the input 'input_spec' should be None, but received the type of 'input_spec' is %s."
% type(input_spec)
)
if not isinstance(input_spec, (list, tuple)):
raise TypeError(
"The input input_spec should be 'list', but received input_spec's type is %s."
% type(input_spec)
)
inner_input_spec = []
for var in paddle.utils.flatten(input_spec):
if isinstance(var, paddle.static.InputSpec):
inner_input_spec.append(var)
elif isinstance(var, (core.eager.Tensor, Variable)):
inner_input_spec.append(
paddle.static.InputSpec.from_tensor(var)
)
else:
# NOTE(Aurelius84): Support non-Tensor type in `input_spec`.