checkpoint_utils.py 4.56 KB
Newer Older
Yeqing Li's avatar
Yeqing Li committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2
3
4
5
6
7
8
9
10
11
12
13
#
# 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.
Yeqing Li's avatar
Yeqing Li committed
14

Hongkun Yu's avatar
Hongkun Yu committed
15
16
17
"""Util functions for loading checkpoints.

Especially for loading Tensorflow 1.x
18
19
20
21
22
23
24
25
checkpoint to Tensorflow 2.x (keras) model.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import re
Hongkun Yu's avatar
Hongkun Yu committed
26

27
28
from absl import logging

29
import tensorflow as tf
30
31
32


def _build_assignment_map(keras_model,
Hongkun Yu's avatar
Hongkun Yu committed
33
34
35
                          prefix='',
                          skip_variables_regex=None,
                          var_to_shape_map=None):
36
  """Compute an assignment mapping for loading older checkpoints into a Keras
Hongkun Yu's avatar
Hongkun Yu committed
37

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  model. Variable names are remapped from the original TPUEstimator model to
  the new Keras name.

  Args:
    keras_model: tf.keras.Model object to provide variables to assign.
    prefix: prefix in the variable name to be remove for alignment with names in
      the checkpoint.
    skip_variables_regex: regular expression to math the names of variables that
      do not need to be assign.
    var_to_shape_map: variable name to shape mapping from the checkpoint.

  Returns:
    The variable assignment map.
  """
  assignment_map = {}

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
54
  checkpoint_names = []
55
  if var_to_shape_map:
Hongkun Yu's avatar
Hongkun Yu committed
56
57
58
59
    checkpoint_names = list(
        filter(
            lambda x: not x.endswith('Momentum') and not x.endswith(
                'global_step'), var_to_shape_map.keys()))
60

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
61
62
63
  logging.info('Number of variables in the checkpoint %d',
               len(checkpoint_names))

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
  for var in keras_model.variables:
    var_name = var.name

    if skip_variables_regex and re.match(skip_variables_regex, var_name):
      continue
    # Trim the index of the variable.
    if ':' in var_name:
      var_name = var_name[:var_name.rindex(':')]
    if var_name.startswith(prefix):
      var_name = var_name[len(prefix):]

    if not var_to_shape_map:
      assignment_map[var_name] = var
      continue

    # Match name with variables in the checkpoint.
    match_names = list(filter(lambda x: x.endswith(var_name), checkpoint_names))
    try:
      if match_names:
        assert len(match_names) == 1, 'more then on matches for {}: {}'.format(
            var_name, match_names)
        checkpoint_names.remove(match_names[0])
        assignment_map[match_names[0]] = var
      else:
        logging.info('Error not found var name: %s', var_name)
    except Exception as e:
      logging.info('Error removing the match_name: %s', match_names)
      logging.info('Exception: %s', e)
      raise
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
93
  logging.info('Found matching variable in checkpoint: %d', len(assignment_map))
94
95
96
97
98
99
100
101
102
103
  return assignment_map


def _get_checkpoint_map(checkpoint_path):
  reader = tf.train.load_checkpoint(checkpoint_path)
  return reader.get_variable_to_shape_map()


def make_restore_checkpoint_fn(checkpoint_path, prefix='', skip_regex=None):
  """Returns scaffold function to restore parameters from v1 checkpoint.
Hongkun Yu's avatar
Hongkun Yu committed
104

105
106
107
108
109
110
  Args:
    checkpoint_path: path of the checkpoint folder or file.
      Example 1: '/path/to/model_dir/'
      Example 2: '/path/to/model.ckpt-22500'
    prefix: prefix in the variable name to be remove for alignment with names in
      the checkpoint.
Hongkun Yu's avatar
Hongkun Yu committed
111
112
    skip_regex: regular expression to math the names of variables that do not
      need to be assign.
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134

  Returns:
    Callable[tf.kears.Model] -> void. Fn to load v1 checkpoint to keras model.
  """

  def _restore_checkpoint_fn(keras_model):
    """Loads pretrained model through scaffold function."""
    if not checkpoint_path:
      logging.info('checkpoint_path is empty')
      return
    var_prefix = prefix
    if prefix and not prefix.endswith('/'):
      var_prefix += '/'
    var_to_shape_map = _get_checkpoint_map(checkpoint_path)
    assert var_to_shape_map, 'var_to_shape_map should not be empty'
    vars_to_load = _build_assignment_map(
        keras_model,
        prefix=var_prefix,
        skip_variables_regex=skip_regex,
        var_to_shape_map=var_to_shape_map)
    if not vars_to_load:
      raise ValueError('Variables to load is empty.')
Hongkun Yu's avatar
Hongkun Yu committed
135
    tf.compat.v1.train.init_from_checkpoint(checkpoint_path, vars_to_load)
136
137

  return _restore_checkpoint_fn