MCPcopy Index your code
hub / github.com/tensorpack/tensorpack / DictRestore

Class DictRestore

tensorpack/tfutils/sessinit.py:196–241  ·  view source on GitHub ↗

Restore variables from a dictionary.

Source from the content-addressed store, hash-verified

194
195
196class DictRestore(SessionInit):
197 """
198 Restore variables from a dictionary.
199 """
200
201 def __init__(self, variable_dict, ignore_mismatch=False):
202 """
203 Args:
204 variable_dict (dict): a dict of {name: value}
205 ignore_mismatch (bool): ignore failures when the value and the
206 variable does not match in their shapes.
207 If False, it will throw exception on such errors.
208 If True, it will only print a warning.
209 """
210 assert isinstance(variable_dict, dict), type(variable_dict)
211 # use varname (with :0) for consistency
212 self._prms = {get_op_tensor_name(n)[1]: v for n, v in six.iteritems(variable_dict)}
213 self._ignore_mismatch = ignore_mismatch
214
215 def _run_init(self, sess):
216 variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
217 variable_names_list = [k.name for k in variables]
218
219 variable_names = set(variable_names_list)
220 param_names = set(six.iterkeys(self._prms))
221
222 # intersect has the original ordering of variables
223 intersect = [v for v in variable_names_list if v in param_names]
224
225 # use opname (without :0) for clarity in logging
226 logger.info("Variables to restore from dict: {}".format(
227 ', '.join(get_op_tensor_name(x)[0] for x in intersect)))
228
229 mismatch = MismatchLogger('graph', 'dict')
230 for k in sorted(variable_names - param_names):
231 if not is_training_name(k):
232 mismatch.add(k)
233 mismatch.log()
234 mismatch = MismatchLogger('dict', 'graph')
235 for k in sorted(param_names - variable_names):
236 mismatch.add(k)
237 mismatch.log()
238
239 upd = SessionUpdate(sess, [v for v in variables if v.name in intersect], ignore_mismatch=self._ignore_mismatch)
240 logger.info("Restoring {} variables from dict ...".format(len(intersect)))
241 upd.update({name: value for name, value in six.iteritems(self._prms) if name in intersect})
242
243
244class ChainInit(SessionInit):

Callers 1

SmartInitFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…