cal_flops.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # coding=utf-8
  2. # Copyright 2024 Microsoft Corporation and the LlamaFactory team.
  3. #
  4. # This code is inspired by the Microsoft's DeepSpeed library.
  5. # https://www.deepspeed.ai/tutorials/flops-profiler/
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import fire
  19. import torch
  20. from deepspeed.accelerator import get_accelerator # type: ignore
  21. from deepspeed.profiling.flops_profiler import get_model_profile # type: ignore
  22. from llamafactory.chat import ChatModel
  23. def calculate_flops(
  24. model_name_or_path: str,
  25. batch_size: int = 1,
  26. seq_length: int = 512,
  27. flash_attn: str = "auto",
  28. ):
  29. r"""
  30. Calculates the flops of pre-trained models.
  31. Usage: python cal_flops.py --model_name_or_path path_to_model --batch_size 1 --seq_length 512
  32. """
  33. with get_accelerator().device(0):
  34. chat_model = ChatModel(dict(model_name_or_path=model_name_or_path, template="empty", flash_attn=flash_attn))
  35. fake_input = torch.ones((batch_size, seq_length), dtype=torch.long, device=chat_model.engine.model.device)
  36. input_dict = {"input_ids": fake_input, "labels": fake_input.clone()}
  37. flops, macs, params = get_model_profile(
  38. chat_model.engine.model, kwargs=input_dict, print_profile=True, detailed=True
  39. )
  40. print("FLOPs:", flops)
  41. print("MACs:", macs)
  42. print("Params:", params)
  43. if __name__ == "__main__":
  44. fire.Fire(calculate_flops)