config.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. import torch
  5. import deepspeed
  6. from deepspeed.runtime.config_utils import DeepSpeedConfigModel
  7. from deepspeed.runtime.zero.config import DeepSpeedZeroConfig
  8. from pydantic import Field
  9. from pydantic import validator
  10. from typing import Dict, Union
  11. from enum import Enum
  12. class DtypeEnum(Enum):
  13. # The torch dtype must always be the first value (so we return torch.dtype)
  14. fp16 = torch.float16, "torch.float16", "fp16", "float16", "half"
  15. fp32 = torch.float32, "torch.float32", "fp32", "float32", "float"
  16. bf16 = torch.bfloat16, "torch.bfloat16", "bf16", "bfloat16", "bfloat"
  17. int8 = torch.int8, "torch.int8", "int8"
  18. # Copied from https://stackoverflow.com/a/43210118
  19. # Allows us to use multiple values for each Enum index and returns first
  20. # listed value when Enum is called
  21. def __new__(cls, *values):
  22. obj = object.__new__(cls)
  23. # first value is canonical value
  24. obj._value_ = values[0]
  25. for other_value in values[1:]:
  26. cls._value2member_map_[other_value] = obj
  27. obj._all_values = values
  28. return obj
  29. def __repr__(self):
  30. return "<%s.%s: %s>" % (
  31. self.__class__.__name__,
  32. self._name_,
  33. ", ".join([repr(v) for v in self._all_values]),
  34. )
  35. class MoETypeEnum(str, Enum):
  36. residual = "residual"
  37. standard = "standard"
  38. class DeepSpeedTPConfig(DeepSpeedConfigModel):
  39. """ Configure tensor parallelism settings """
  40. enabled: bool = True
  41. """ Turn tensor parallelism on/off. """
  42. tp_size: int = 1
  43. """ Number of devices to split the model across using tensor parallelism. """
  44. mpu: object = None
  45. """
  46. A model parallelism unit object that implements
  47. ``get_{model,data}_parallel_{rank,group,world_size}()``.
  48. """
  49. tp_group: object = None
  50. class DeepSpeedMoEConfig(DeepSpeedConfigModel):
  51. """ Sets parameters for MoE """
  52. enabled: bool = True
  53. ep_size: int = 1
  54. """
  55. The expert-parallelism size which is used for partitioning the experts
  56. across the GPUs in the expert-parallel group.
  57. """
  58. moe_experts: list = Field([1], alias="num_experts")
  59. """ The global number of experts used in an MoE layer. """
  60. type: MoETypeEnum = MoETypeEnum.standard
  61. """
  62. Specify the type of MoE layer. We have two types of MoE layer: 'Standard'
  63. and 'Residual'.
  64. """
  65. ep_mp_group: object = None
  66. ep_group: object = Field(None, alias="expert_group")
  67. class QuantTypeEnum(str, Enum):
  68. asym = "asymmetric"
  69. sym = "symmetric"
  70. class BaseQuantConfig(DeepSpeedConfigModel):
  71. enabled = True
  72. num_bits = 8
  73. q_type: QuantTypeEnum = QuantTypeEnum.sym
  74. q_groups: int = 1
  75. class WeightQuantConfig(BaseQuantConfig):
  76. enabled = True
  77. quantized_initialization: Dict = {}
  78. post_init_quant: Dict = {}
  79. class ActivationQuantConfig(BaseQuantConfig):
  80. enabled = True
  81. class QKVQuantConfig(DeepSpeedConfigModel):
  82. enabled = True
  83. class QuantizationConfig(DeepSpeedConfigModel):
  84. enabled: bool = True
  85. activation: ActivationQuantConfig = ActivationQuantConfig()
  86. weight: WeightQuantConfig = WeightQuantConfig()
  87. qkv: QKVQuantConfig = QKVQuantConfig()
  88. # todo: brainstorm on how to do ckpt loading for DS inference
  89. class InferenceCheckpointConfig(DeepSpeedConfigModel):
  90. checkpoint_dir: str = None
  91. save_mp_checkpoint_path: str = None
  92. base_dir: str = None
  93. class DeepSpeedInferenceConfig(DeepSpeedConfigModel):
  94. """ Sets parameters for DeepSpeed Inference Engine. """
  95. replace_with_kernel_inject: bool = Field(False, alias="kernel_inject")
  96. """
  97. Set to true to inject inference kernels for models such as, Bert, GPT2,
  98. GPT-Neo and GPT-J. Otherwise, the injection_dict provides the names of two
  99. linear layers as a tuple:
  100. `(attention_output projection, transformer output projection)`
  101. """
  102. dtype: DtypeEnum = torch.float16
  103. """
  104. Desired model data type, will convert model to this type.
  105. Supported target types: `torch.half`, `torch.int8`, `torch.float`
  106. """
  107. tensor_parallel: DeepSpeedTPConfig = Field({}, alias="tp")
  108. """
  109. Configuration for tensor parallelism used to split the model across several
  110. GPUs. Expects a dictionary containing values for :any:`DeepSpeedTPConfig`.
  111. """
  112. enable_cuda_graph: bool = False
  113. """
  114. Use this flag for capturing the CUDA-Graph of the inference ops, so that it
  115. can run faster using the graph replay method.
  116. """
  117. use_triton: bool = False
  118. """
  119. Use this flag to use triton kernels for inference ops.
  120. """
  121. triton_autotune: bool = False
  122. """
  123. Use this flag to enable triton autotuning.
  124. Turning it on is better for performance but increase the 1st runtime for
  125. autotuning.
  126. """
  127. zero: DeepSpeedZeroConfig = {}
  128. """
  129. ZeRO configuration to use with the Inference Engine. Expects a dictionary
  130. containing values for :any:`DeepSpeedZeroConfig`.
  131. """
  132. triangular_masking: bool = Field(True, alias="tm")
  133. """
  134. Controls the type of masking for attention scores in transformer layer.
  135. Note that the masking is application specific.
  136. """
  137. moe: Union[bool, DeepSpeedMoEConfig] = {}
  138. """
  139. Specify if the type of Transformer is MoE. Expects a dictionary containing
  140. values for :any:`DeepSpeedMoEConfig`.
  141. """
  142. quant: QuantizationConfig = {}
  143. """
  144. NOTE: only works for int8 dtype.
  145. Quantization settings used for quantizing your model using the MoQ. The
  146. setting can be one element or a tuple. If one value is passed in, we
  147. consider it as the number of groups used in quantization. A tuple is passed
  148. in if we want to mention that there is extra-grouping for the MLP part of a
  149. Transformer layer (e.g. (True, 8) shows we quantize the model using 8
  150. groups for all the network except the MLP part that we use 8 extra
  151. grouping). Expects a dictionary containing values for
  152. :any:`QuantizationConfig`.
  153. """
  154. #todo: refactor the following 3 into the new checkpoint_config
  155. checkpoint: Union[str, Dict] = None
  156. """
  157. Path to deepspeed compatible checkpoint or path to JSON with load policy.
  158. """
  159. base_dir: str = ""
  160. """
  161. This shows the root directory under which all the checkpoint files exists.
  162. This can be passed through the json config too.
  163. """
  164. set_empty_params: bool = False
  165. """
  166. specifying whether the inference-module is created with empty or real Tensor
  167. """
  168. save_mp_checkpoint_path: str = None
  169. """
  170. The path for which we want to save the loaded model with a checkpoint. This
  171. feature is used for adjusting the parallelism degree to help alleviate the
  172. model loading overhead. It does not save any new checkpoint if no path is
  173. passed.
  174. """
  175. checkpoint_config: InferenceCheckpointConfig = Field({}, alias="ckpt_config")
  176. """
  177. TODO: Add docs. Expects a dictionary containing values for
  178. :any:`InferenceCheckpointConfig`.
  179. """
  180. return_tuple: bool = True
  181. """
  182. Specify whether or not the transformer layers need to return a tuple or a
  183. Tensor.
  184. """
  185. training_mp_size: int = 1
  186. """
  187. If loading a checkpoint this is the mp size that it was trained with, it
  188. may be different than what the mp size that you want to use during
  189. inference.
  190. """
  191. replace_method: str = Field(
  192. "auto",
  193. deprecated=True,
  194. deprecated_msg="This parameter is no longer needed, please remove from your call to DeepSpeed-inference")
  195. injection_policy: Dict = Field(None, alias="injection_dict")
  196. """
  197. Dictionary mapping a client nn.Module to its corresponding injection
  198. policy. e.g., `{BertLayer : deepspeed.inference.HFBertLayerPolicy}`
  199. """
  200. injection_policy_tuple: tuple = None
  201. """ TODO: Add docs """
  202. config: Dict = Field(None, alias="args") # todo: really no need for this field if we can refactor
  203. max_out_tokens: int = Field(1024, alias="max_tokens")
  204. """
  205. This argument shows the maximum number of tokens inference-engine can work
  206. with, including the input and output tokens. Please consider increasing it
  207. to the required token-length required for your use-case.
  208. """
  209. min_out_tokens: int = Field(1, alias="min_tokens")
  210. """
  211. This argument communicates to the runtime the minimum number of tokens you
  212. expect you will need to generate. This will cause the runtime to error
  213. if it unable to provide this and provide context on the memory pressure
  214. rather than seg-faulting or providing corrupted output.
  215. """
  216. transposed_mode: bool = Field(False, alias="transposed_mode")
  217. mp_size: int = Field(1, deprecated=True, new_param="tensor_parallel.tp_size")
  218. """
  219. Desired model parallel size, default is 1 meaning no model parallelism.
  220. Deprecated, please use the ``tensor_parallel` config to control model
  221. parallelism.
  222. """
  223. mpu: object = Field(None, deprecated=True, new_param="tensor_parallel.mpu")
  224. ep_size: int = Field(1, deprecated=True, new_param="moe.ep_size")
  225. ep_group: object = Field(None, alias="expert_group", deprecated=True, new_param="moe.ep_group")
  226. ep_mp_group: object = Field(None, alias="expert_mp_group", deprecated=True, new_param="moe.ep_mp_group")
  227. moe_experts: list = Field([1], deprecated=True, new_param="moe.moe_experts")
  228. moe_type: MoETypeEnum = Field(MoETypeEnum.standard, deprecated=True, new_param="moe.type")
  229. @validator("moe")
  230. def moe_backward_compat(cls, field_value, values):
  231. if isinstance(field_value, bool):
  232. return DeepSpeedMoEConfig(moe=field_value)
  233. return field_value
  234. @validator("use_triton")
  235. def has_triton(cls, field_value, values):
  236. if field_value and not deepspeed.HAS_TRITON:
  237. raise ValueError('Triton needs to be installed to use deepspeed with triton kernels')
  238. return field_value
  239. class Config:
  240. # Get the str representation of the datatype for serialization
  241. json_encoders = {torch.dtype: lambda x: str(x)}