model_parallel_utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # coding=utf-8
  2. # Copyright 2020 The HuggingFace Team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from math import ceil
  16. def assert_device_map(device_map, num_blocks):
  17. blocks = list(range(0, num_blocks))
  18. device_map_blocks = [item for sublist in list(device_map.values()) for item in sublist]
  19. # Duplicate check
  20. duplicate_blocks = []
  21. for i in device_map_blocks:
  22. if device_map_blocks.count(i) > 1 and i not in duplicate_blocks:
  23. duplicate_blocks.append(i)
  24. # Missing blocks
  25. missing_blocks = [i for i in blocks if i not in device_map_blocks]
  26. extra_blocks = [i for i in device_map_blocks if i not in blocks]
  27. if len(duplicate_blocks) != 0:
  28. raise ValueError(
  29. "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
  30. " These attention blocks were specified more than once: " + str(duplicate_blocks)
  31. )
  32. if len(missing_blocks) != 0:
  33. raise ValueError(
  34. "There are attention blocks for this model that are not specified in the device_map. Add these attention "
  35. "blocks to a device on the device_map: " + str(missing_blocks)
  36. )
  37. if len(extra_blocks) != 0:
  38. raise ValueError(
  39. "The device_map contains more attention blocks than this model has. Remove these from the device_map:"
  40. + str(extra_blocks)
  41. )
  42. def get_device_map(n_layers, devices):
  43. """Returns a dictionary of layers distributed evenly across all devices."""
  44. layers = list(range(n_layers))
  45. n_blocks = int(ceil(n_layers / len(devices)))
  46. layers_list = [layers[i : i + n_blocks] for i in range(0, n_layers, n_blocks)]
  47. return dict(zip(devices, layers_list))