config.py 9.9 KB

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