postprocess_ckpt.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import tensorflow as tf
  2. import numpy as np
  3. import argparse
  4. import os
  5. def process_checkpoint(input_ckpt, output_ckpt_path, dense_layer):
  6. """
  7. This function loads a RN50 checkpoint with Dense layer as the final layer
  8. and transforms the final dense layer into a 1x1 convolution layer. The weights
  9. of the dense layer are reshaped into weights of 1x1 conv layer.
  10. Args:
  11. input_ckpt: Path to the input RN50 ckpt which has dense layer as classification layer.
  12. Returns:
  13. None. New checkpoint with 1x1 conv layer as classification layer is generated.
  14. """
  15. with tf.Session() as sess:
  16. # Load all the variables
  17. all_vars = tf.train.list_variables(input_ckpt)
  18. # Capture the dense layer weights and reshape them to a 4D tensor which would be
  19. # the weights of a 1x1 convolution layer. This code replaces the dense (FC) layer
  20. # to a 1x1 conv layer.
  21. dense_layer_value=0.
  22. new_var_list=[]
  23. for var in all_vars:
  24. curr_var = tf.train.load_variable(input_ckpt, var[0])
  25. if var[0]==dense_layer:
  26. dense_layer_value = curr_var
  27. else:
  28. new_var_list.append(tf.Variable(curr_var, name=var[0]))
  29. dense_layer_shape = [1, 1, 2048, 1001]
  30. new_var_value = np.reshape(dense_layer_value, dense_layer_shape)
  31. new_var = tf.Variable(new_var_value, name=dense_layer)
  32. new_var_list.append(new_var)
  33. sess.run(tf.global_variables_initializer())
  34. tf.train.Saver(var_list=new_var_list).save(sess, output_ckpt_path, write_meta_graph=False, write_state=False)
  35. print ("Rewriting checkpoint completed")
  36. if __name__=='__main__':
  37. parser = argparse.ArgumentParser()
  38. parser.add_argument('--input', type=str, required=True, help='Path to pretrained RN50 checkpoint with dense layer')
  39. parser.add_argument('--dense_layer', type=str, default='resnet50/output/dense/kernel')
  40. parser.add_argument('--output', type=str, default='output_dir', help="Output directory to store new checkpoint")
  41. args = parser.parse_args()
  42. input_ckpt = args.input
  43. # Create an output directory
  44. os.mkdir(args.output)
  45. new_ckpt='new.ckpt'
  46. new_ckpt_path = os.path.join(args.output, new_ckpt)
  47. with open(os.path.join(args.output, "checkpoint"), 'w') as file:
  48. file.write("model_checkpoint_path: "+ "\"" + new_ckpt + "\"")
  49. # Process the input checkpoint, apply transforms and generate a new checkpoint.
  50. process_checkpoint(input_ckpt, new_ckpt_path, args.dense_layer)