test_average_checkpoints.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # Copyright (c) Facebook, Inc. and its affiliates.
  2. #
  3. # This source code is licensed under the MIT license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import collections
  6. import os
  7. import shutil
  8. import tempfile
  9. import unittest
  10. import numpy as np
  11. import torch
  12. from scripts.average_checkpoints import average_checkpoints
  13. from torch import nn
  14. class ModelWithSharedParameter(nn.Module):
  15. def __init__(self):
  16. super(ModelWithSharedParameter, self).__init__()
  17. self.embedding = nn.Embedding(1000, 200)
  18. self.FC1 = nn.Linear(200, 200)
  19. self.FC2 = nn.Linear(200, 200)
  20. # tie weight in FC2 to FC1
  21. self.FC2.weight = nn.Parameter(self.FC1.weight)
  22. self.FC2.bias = nn.Parameter(self.FC1.bias)
  23. self.relu = nn.ReLU()
  24. def forward(self, input):
  25. return self.FC2(self.ReLU(self.FC1(input))) + self.FC1(input)
  26. class TestAverageCheckpoints(unittest.TestCase):
  27. def test_average_checkpoints(self):
  28. params_0 = collections.OrderedDict(
  29. [
  30. ("a", torch.DoubleTensor([100.0])),
  31. ("b", torch.FloatTensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])),
  32. ("c", torch.IntTensor([7, 8, 9])),
  33. ]
  34. )
  35. params_1 = collections.OrderedDict(
  36. [
  37. ("a", torch.DoubleTensor([1.0])),
  38. ("b", torch.FloatTensor([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])),
  39. ("c", torch.IntTensor([2, 2, 2])),
  40. ]
  41. )
  42. params_avg = collections.OrderedDict(
  43. [
  44. ("a", torch.DoubleTensor([50.5])),
  45. ("b", torch.FloatTensor([[1.0, 1.5, 2.0], [2.5, 3.0, 3.5]])),
  46. # We expect truncation for integer division
  47. ("c", torch.IntTensor([4, 5, 5])),
  48. ]
  49. )
  50. fd_0, path_0 = tempfile.mkstemp()
  51. fd_1, path_1 = tempfile.mkstemp()
  52. torch.save(collections.OrderedDict([("model", params_0)]), path_0)
  53. torch.save(collections.OrderedDict([("model", params_1)]), path_1)
  54. output = average_checkpoints([path_0, path_1])["model"]
  55. os.close(fd_0)
  56. os.remove(path_0)
  57. os.close(fd_1)
  58. os.remove(path_1)
  59. for (k_expected, v_expected), (k_out, v_out) in zip(
  60. params_avg.items(), output.items()
  61. ):
  62. self.assertEqual(
  63. k_expected,
  64. k_out,
  65. "Key mismatch - expected {} but found {}. "
  66. "(Expected list of keys: {} vs actual list of keys: {})".format(
  67. k_expected, k_out, params_avg.keys(), output.keys()
  68. ),
  69. )
  70. np.testing.assert_allclose(
  71. v_expected.numpy(),
  72. v_out.numpy(),
  73. err_msg="Tensor value mismatch for key {}".format(k_expected),
  74. )
  75. def test_average_checkpoints_with_shared_parameters(self):
  76. def _construct_model_with_shared_parameters(path, value):
  77. m = ModelWithSharedParameter()
  78. nn.init.constant_(m.FC1.weight, value)
  79. torch.save({"model": m.state_dict()}, path)
  80. return m
  81. tmpdir = tempfile.mkdtemp()
  82. paths = []
  83. path = os.path.join(tmpdir, "m1.pt")
  84. m1 = _construct_model_with_shared_parameters(path, 1.0)
  85. paths.append(path)
  86. path = os.path.join(tmpdir, "m2.pt")
  87. m2 = _construct_model_with_shared_parameters(path, 2.0)
  88. paths.append(path)
  89. path = os.path.join(tmpdir, "m3.pt")
  90. m3 = _construct_model_with_shared_parameters(path, 3.0)
  91. paths.append(path)
  92. new_model = average_checkpoints(paths)
  93. self.assertTrue(
  94. torch.equal(
  95. new_model["model"]["embedding.weight"],
  96. (m1.embedding.weight + m2.embedding.weight + m3.embedding.weight) / 3.0,
  97. )
  98. )
  99. self.assertTrue(
  100. torch.equal(
  101. new_model["model"]["FC1.weight"],
  102. (m1.FC1.weight + m2.FC1.weight + m3.FC1.weight) / 3.0,
  103. )
  104. )
  105. self.assertTrue(
  106. torch.equal(
  107. new_model["model"]["FC2.weight"],
  108. (m1.FC2.weight + m2.FC2.weight + m3.FC2.weight) / 3.0,
  109. )
  110. )
  111. shutil.rmtree(tmpdir)
  112. if __name__ == "__main__":
  113. unittest.main()