applied-ai-018 commited on
Commit
2334d5a
·
verified ·
1 Parent(s): 179036e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. venv/lib/python3.10/site-packages/deepspeed/checkpoint/__pycache__/ds_to_universal.cpython-310.pyc +0 -0
  2. venv/lib/python3.10/site-packages/deepspeed/checkpoint/__pycache__/zero_checkpoint.cpython-310.pyc +0 -0
  3. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/__init__.cpython-310.pyc +0 -0
  4. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/basic_layer.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/compress.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/config.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/constants.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/helper.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/scheduler.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/utils.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/deepspeed/inference/__init__.py +7 -0
  12. venv/lib/python3.10/site-packages/deepspeed/inference/config.py +304 -0
  13. venv/lib/python3.10/site-packages/deepspeed/inference/engine.py +636 -0
  14. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__init__.py +4 -0
  15. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/__init__.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/layers.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/quantization.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/quantization_context.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/utils.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/layers.py +114 -0
  21. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/quantization.py +111 -0
  22. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/quantization_context.py +13 -0
  23. venv/lib/python3.10/site-packages/deepspeed/inference/quantization/utils.py +288 -0
  24. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__init__.py +7 -0
  25. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/__init__.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/allocator.cpython-310.pyc +0 -0
  27. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/config_v2.cpython-310.pyc +0 -0
  28. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/engine_factory.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/engine_v2.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/inference_parameter.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/inference_utils.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/logging.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/scheduling_utils.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/deepspeed/inference/v2/allocator.py +42 -0
  35. venv/lib/python3.10/site-packages/deepspeed/inference/v2/config_v2.py +43 -0
  36. venv/lib/python3.10/site-packages/deepspeed/inference/v2/engine_factory.py +129 -0
  37. venv/lib/python3.10/site-packages/deepspeed/inference/v2/engine_v2.py +268 -0
  38. venv/lib/python3.10/site-packages/deepspeed/inference/v2/inference_parameter.py +89 -0
  39. venv/lib/python3.10/site-packages/deepspeed/inference/v2/inference_utils.py +105 -0
  40. venv/lib/python3.10/site-packages/deepspeed/inference/v2/logging.py +26 -0
  41. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/__init__.py +8 -0
  42. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__init__.py +16 -0
  43. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/attention_configs.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/embedding_config.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/linear_config.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/norm_config.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/attention_configs.py +110 -0
  48. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/embedding_config.py +70 -0
  49. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/linear_config.py +43 -0
  50. venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/moe_config.py +56 -0
venv/lib/python3.10/site-packages/deepspeed/checkpoint/__pycache__/ds_to_universal.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/checkpoint/__pycache__/zero_checkpoint.cpython-310.pyc ADDED
Binary file (5.49 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (375 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/basic_layer.cpython-310.pyc ADDED
Binary file (22.8 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/compress.cpython-310.pyc ADDED
Binary file (6.61 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/config.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/constants.cpython-310.pyc ADDED
Binary file (5.02 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/helper.cpython-310.pyc ADDED
Binary file (9.93 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/scheduler.cpython-310.pyc ADDED
Binary file (4.63 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/compression/__pycache__/utils.cpython-310.pyc ADDED
Binary file (6.09 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+ from .v2 import RaggedInferenceEngineConfig, DeepSpeedTPConfig
6
+ from .v2.engine_v2 import InferenceEngineV2
7
+ from .v2 import build_hf_engine, build_engine_from_ds_checkpoint
venv/lib/python3.10/site-packages/deepspeed/inference/config.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import torch
7
+ import deepspeed
8
+ from deepspeed.pydantic_v1 import Field, validator
9
+ from deepspeed.runtime.config_utils import DeepSpeedConfigModel
10
+ from deepspeed.runtime.zero.config import DeepSpeedZeroConfig
11
+ from typing import Dict, Union
12
+ from enum import Enum
13
+
14
+
15
+ class DtypeEnum(Enum):
16
+ # The torch dtype must always be the first value (so we return torch.dtype)
17
+ fp16 = torch.float16, "torch.float16", "fp16", "float16", "half"
18
+ fp32 = torch.float32, "torch.float32", "fp32", "float32", "float"
19
+ bf16 = torch.bfloat16, "torch.bfloat16", "bf16", "bfloat16", "bfloat"
20
+ int8 = torch.int8, "torch.int8", "int8"
21
+
22
+ # Copied from https://stackoverflow.com/a/43210118
23
+ # Allows us to use multiple values for each Enum index and returns first
24
+ # listed value when Enum is called
25
+ def __new__(cls, *values):
26
+ obj = object.__new__(cls)
27
+ # first value is canonical value
28
+ obj._value_ = values[0]
29
+ for other_value in values[1:]:
30
+ cls._value2member_map_[other_value] = obj
31
+ obj._all_values = values
32
+ return obj
33
+
34
+ def __repr__(self):
35
+ return "<%s.%s: %s>" % (
36
+ self.__class__.__name__,
37
+ self._name_,
38
+ ", ".join([repr(v) for v in self._all_values]),
39
+ )
40
+
41
+
42
+ class MoETypeEnum(str, Enum):
43
+ residual = "residual"
44
+ standard = "standard"
45
+
46
+
47
+ class DeepSpeedTPConfig(DeepSpeedConfigModel):
48
+ """ Configure tensor parallelism settings """
49
+
50
+ enabled: bool = True
51
+ """ Turn tensor parallelism on/off. """
52
+
53
+ tp_size: int = 1
54
+ """ Number of devices to split the model across using tensor parallelism. """
55
+
56
+ mpu: object = None
57
+ """
58
+ A model parallelism unit object that implements
59
+ ``get_{model,data}_parallel_{rank,group,world_size}()``.
60
+ """
61
+
62
+ tp_group: object = None
63
+
64
+
65
+ class DeepSpeedMoEConfig(DeepSpeedConfigModel):
66
+ """ Sets parameters for MoE """
67
+
68
+ enabled: bool = True
69
+ ep_size: int = 1
70
+ """
71
+ The expert-parallelism size which is used for partitioning the experts
72
+ across the GPUs in the expert-parallel group.
73
+ """
74
+
75
+ moe_experts: list = Field([1], alias="num_experts")
76
+ """ The global number of experts used in an MoE layer. """
77
+
78
+ type: MoETypeEnum = MoETypeEnum.standard
79
+ """
80
+ Specify the type of MoE layer. We have two types of MoE layer: 'Standard'
81
+ and 'Residual'.
82
+ """
83
+
84
+ ep_mp_group: object = None
85
+ ep_group: object = Field(None, alias="expert_group")
86
+
87
+
88
+ class QuantTypeEnum(str, Enum):
89
+ asym = "asymmetric"
90
+ sym = "symmetric"
91
+
92
+
93
+ class BaseQuantConfig(DeepSpeedConfigModel):
94
+ enabled = True
95
+ num_bits = 8
96
+ q_type: QuantTypeEnum = QuantTypeEnum.sym
97
+ q_groups: int = 1
98
+
99
+
100
+ class WeightQuantConfig(BaseQuantConfig):
101
+ enabled = True
102
+ quantized_initialization: Dict = {}
103
+ post_init_quant: Dict = {}
104
+
105
+
106
+ class ActivationQuantConfig(BaseQuantConfig):
107
+ enabled = True
108
+
109
+
110
+ class QKVQuantConfig(DeepSpeedConfigModel):
111
+ enabled = True
112
+
113
+
114
+ class QuantizationConfig(DeepSpeedConfigModel):
115
+ enabled: bool = True
116
+ activation: ActivationQuantConfig = ActivationQuantConfig()
117
+ weight: WeightQuantConfig = WeightQuantConfig()
118
+ qkv: QKVQuantConfig = QKVQuantConfig()
119
+
120
+
121
+ # todo: brainstorm on how to do ckpt loading for DS inference
122
+ class InferenceCheckpointConfig(DeepSpeedConfigModel):
123
+ checkpoint_dir: str = None
124
+ save_mp_checkpoint_path: str = None
125
+ base_dir: str = None
126
+
127
+
128
+ class DeepSpeedInferenceConfig(DeepSpeedConfigModel):
129
+ """ Sets parameters for DeepSpeed Inference Engine. """
130
+
131
+ replace_with_kernel_inject: bool = Field(False, alias="kernel_inject")
132
+ """
133
+ Set to true to inject inference kernels for models such as, Bert, GPT2,
134
+ GPT-Neo and GPT-J. Otherwise, the injection_dict provides the names of two
135
+ linear layers as a tuple:
136
+ `(attention_output projection, transformer output projection)`
137
+ """
138
+
139
+ dtype: DtypeEnum = torch.float16
140
+ """
141
+ Desired model data type, will convert model to this type.
142
+ Supported target types: `torch.half`, `torch.int8`, `torch.float`
143
+ """
144
+
145
+ tensor_parallel: DeepSpeedTPConfig = Field({}, alias="tp")
146
+ """
147
+ Configuration for tensor parallelism used to split the model across several
148
+ GPUs. Expects a dictionary containing values for :any:`DeepSpeedTPConfig`.
149
+ """
150
+
151
+ enable_cuda_graph: bool = False
152
+ """
153
+ Use this flag for capturing the CUDA-Graph of the inference ops, so that it
154
+ can run faster using the graph replay method.
155
+ """
156
+
157
+ use_triton: bool = False
158
+ """
159
+ Use this flag to use triton kernels for inference ops.
160
+ """
161
+
162
+ triton_autotune: bool = False
163
+ """
164
+ Use this flag to enable triton autotuning.
165
+ Turning it on is better for performance but increase the 1st runtime for
166
+ autotuning.
167
+ """
168
+
169
+ zero: DeepSpeedZeroConfig = {}
170
+ """
171
+ ZeRO configuration to use with the Inference Engine. Expects a dictionary
172
+ containing values for :any:`DeepSpeedZeroConfig`.
173
+ """
174
+
175
+ triangular_masking: bool = Field(True, alias="tm")
176
+ """
177
+ Controls the type of masking for attention scores in transformer layer.
178
+ Note that the masking is application specific.
179
+ """
180
+
181
+ moe: Union[bool, DeepSpeedMoEConfig] = {}
182
+ """
183
+ Specify if the type of Transformer is MoE. Expects a dictionary containing
184
+ values for :any:`DeepSpeedMoEConfig`.
185
+ """
186
+
187
+ quant: QuantizationConfig = {}
188
+ """
189
+ NOTE: only works for int8 dtype.
190
+ Quantization settings used for quantizing your model using the MoQ. The
191
+ setting can be one element or a tuple. If one value is passed in, we
192
+ consider it as the number of groups used in quantization. A tuple is passed
193
+ in if we want to mention that there is extra-grouping for the MLP part of a
194
+ Transformer layer (e.g. (True, 8) shows we quantize the model using 8
195
+ groups for all the network except the MLP part that we use 8 extra
196
+ grouping). Expects a dictionary containing values for
197
+ :any:`QuantizationConfig`.
198
+ """
199
+
200
+ #todo: refactor the following 3 into the new checkpoint_config
201
+ checkpoint: Union[str, Dict] = None
202
+ """
203
+ Path to deepspeed compatible checkpoint or path to JSON with load policy.
204
+ """
205
+
206
+ base_dir: str = ""
207
+ """
208
+ This shows the root directory under which all the checkpoint files exists.
209
+ This can be passed through the json config too.
210
+ """
211
+
212
+ set_empty_params: bool = False
213
+ """
214
+ specifying whether the inference-module is created with empty or real Tensor
215
+ """
216
+
217
+ save_mp_checkpoint_path: str = None
218
+ """
219
+ The path for which we want to save the loaded model with a checkpoint. This
220
+ feature is used for adjusting the parallelism degree to help alleviate the
221
+ model loading overhead. It does not save any new checkpoint if no path is
222
+ passed.
223
+ """
224
+
225
+ checkpoint_config: InferenceCheckpointConfig = Field({}, alias="ckpt_config")
226
+ """
227
+ TODO: Add docs. Expects a dictionary containing values for
228
+ :any:`InferenceCheckpointConfig`.
229
+ """
230
+
231
+ return_tuple: bool = True
232
+ """
233
+ Specify whether or not the transformer layers need to return a tuple or a
234
+ Tensor.
235
+ """
236
+
237
+ training_mp_size: int = 1
238
+ """
239
+ If loading a checkpoint this is the mp size that it was trained with, it
240
+ may be different than what the mp size that you want to use during
241
+ inference.
242
+ """
243
+
244
+ replace_method: str = Field(
245
+ "auto",
246
+ deprecated=True,
247
+ deprecated_msg="This parameter is no longer needed, please remove from your call to DeepSpeed-inference")
248
+
249
+ injection_policy: Dict = Field(None, alias="injection_dict")
250
+ """
251
+ Dictionary mapping a client nn.Module to its corresponding injection
252
+ policy. e.g., `{BertLayer : deepspeed.inference.HFBertLayerPolicy}`
253
+ """
254
+
255
+ injection_policy_tuple: tuple = None
256
+ """ TODO: Add docs """
257
+
258
+ config: Dict = Field(None, alias="args") # todo: really no need for this field if we can refactor
259
+
260
+ max_out_tokens: int = Field(1024, alias="max_tokens")
261
+ """
262
+ This argument shows the maximum number of tokens inference-engine can work
263
+ with, including the input and output tokens. Please consider increasing it
264
+ to the required token-length required for your use-case.
265
+ """
266
+
267
+ min_out_tokens: int = Field(1, alias="min_tokens")
268
+ """
269
+ This argument communicates to the runtime the minimum number of tokens you
270
+ expect you will need to generate. This will cause the runtime to error
271
+ if it unable to provide this and provide context on the memory pressure
272
+ rather than seg-faulting or providing corrupted output.
273
+ """
274
+
275
+ transposed_mode: bool = Field(False, alias="transposed_mode")
276
+
277
+ mp_size: int = Field(1, deprecated=True, new_param="tensor_parallel.tp_size")
278
+ """
279
+ Desired model parallel size, default is 1 meaning no model parallelism.
280
+ Deprecated, please use the ``tensor_parallel` config to control model
281
+ parallelism.
282
+ """
283
+ mpu: object = Field(None, deprecated=True, new_param="tensor_parallel.mpu")
284
+ ep_size: int = Field(1, deprecated=True, new_param="moe.ep_size")
285
+ ep_group: object = Field(None, alias="expert_group", deprecated=True, new_param="moe.ep_group")
286
+ ep_mp_group: object = Field(None, alias="expert_mp_group", deprecated=True, new_param="moe.ep_mp_group")
287
+ moe_experts: list = Field([1], deprecated=True, new_param="moe.moe_experts")
288
+ moe_type: MoETypeEnum = Field(MoETypeEnum.standard, deprecated=True, new_param="moe.type")
289
+
290
+ @validator("moe")
291
+ def moe_backward_compat(cls, field_value, values):
292
+ if isinstance(field_value, bool):
293
+ return DeepSpeedMoEConfig(moe=field_value)
294
+ return field_value
295
+
296
+ @validator("use_triton")
297
+ def has_triton(cls, field_value, values):
298
+ if field_value and not deepspeed.HAS_TRITON:
299
+ raise ValueError('Triton needs to be installed to use deepspeed with triton kernels')
300
+ return field_value
301
+
302
+ class Config:
303
+ # Get the str representation of the datatype for serialization
304
+ json_encoders = {torch.dtype: lambda x: str(x)}
venv/lib/python3.10/site-packages/deepspeed/inference/engine.py ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import torch
7
+ import time
8
+ import os
9
+ from deepspeed import comm as dist
10
+ from deepspeed.utils.logging import log_dist
11
+
12
+ from torch.nn.modules import Module
13
+ from packaging import version as pkg_version
14
+ from deepspeed.runtime.checkpoint_engine.torch_checkpoint_engine import TorchCheckpointEngine
15
+ from deepspeed.utils.timer import SynchronizedWallClockTimer
16
+
17
+ from ..runtime.state_dict_factory import SDLoaderFactory
18
+ from ..runtime.weight_quantizer import WeightQuantization
19
+ from ..module_inject import replace_transformer_layer, generic_injection
20
+ from ..comm.comm import init_distributed
21
+ from ..pipe import PipelineModule
22
+ from ..moe.utils import has_moe_layers
23
+ from ..module_inject import LinearAllreduce, LinearLayer, Normalize, ReplaceWithTensorSlicing
24
+ from deepspeed.accelerator import get_accelerator
25
+ from ..module_inject.policy import TransformerPolicy
26
+ from ..module_inject.auto_tp import AutoTP
27
+
28
+ from ..module_inject.replace_policy import generic_policies
29
+ from ..module_inject.auto_tp_model_utils import build_bloom_alibi_tensor, build_mpt_atten_bias_tensor, build_mpt_alibi_tensor, get_alibi_mask
30
+ from ..ops.transformer.inference.ds_attention import DeepSpeedSelfAttention
31
+ from ..model_implementations.transformers.ds_transformer import DeepSpeedTransformerInference
32
+
33
+ DS_INFERENCE_ENABLED = False
34
+ from torch import nn
35
+
36
+ INFERENCE_MODEL_TIMER = "model-forward-inference"
37
+
38
+
39
+ class InferenceEngine(Module):
40
+ inference_mp_group = None
41
+ inference_ep_group = None
42
+ expert_mp_group = None
43
+
44
+ def __init__(self, model, config):
45
+ """
46
+ Args:
47
+ model: torch.nn.Module
48
+ config: DeepSpeedInferenceConfig
49
+ """
50
+ global DS_INFERENCE_ENABLED
51
+ DS_INFERENCE_ENABLED = True
52
+
53
+ super().__init__()
54
+
55
+ # Have to import here because inference_module is a global, but python
56
+ # globals only work at the module level and will not be updated unless
57
+ # we import it each time we init a new inference engine.
58
+ from ..model_implementations.transformers.ds_transformer import inference_module
59
+ if inference_module is not None:
60
+ self.destroy()
61
+
62
+ self.module = model
63
+ self._config = config
64
+
65
+ self._get_model_config_generate(config) # keep for weird backward compatibility
66
+
67
+ # patch model generate with ours if model uses it
68
+ if hasattr(self.module, "generate"):
69
+ self.generate = self._generate
70
+
71
+ if hasattr(self.module, "config"):
72
+ TransformerPolicy.hf_model_config = self.module.config
73
+
74
+ if config.dtype == torch.half and not get_accelerator().is_fp16_supported():
75
+ raise ValueError("Type fp16 is not supported.")
76
+
77
+ # todo: keep this self.injection_dict because we don't use to change config.injection_policy API
78
+ # todo: this will get changed when Molly's PR on auto injection dict is merged
79
+ self.injection_dict = config.injection_policy
80
+
81
+ # todo: refactor the mp_group and mp_size related in the next refactor
82
+ self.mp_group = config.tensor_parallel.tp_group
83
+ self.mpu = config.tensor_parallel.mpu
84
+
85
+ #self._validate_args(self.mpu, config.replace_with_kernel_inject)
86
+ self.quantize_merge_count = 1
87
+ self.quantization_scales = None
88
+
89
+ # these are not needed in the config as we are creating them ourselves in the inference engine
90
+ self.ep_group = None # config.moe.ep_group
91
+ self.expert_mp_group = None # config.moe.ep_mp_group
92
+
93
+ self.cuda_graph_created = False
94
+ self.checkpoint_engine = TorchCheckpointEngine()
95
+ quantization_setting = None
96
+ self._init_quantization_setting(
97
+ quantization_setting) # todo: update with the new quant config for weight quant
98
+ self.model_profile_enabled = False
99
+ self._model_times = []
100
+
101
+ if not self.injection_dict and config.replace_with_kernel_inject:
102
+ # This is a hack to remove the prepare_mask function on HF side for BLOOM architecture
103
+ self.remove_mask_prepare_for_bloom()
104
+
105
+ if self.injection_dict or not config.replace_with_kernel_inject:
106
+ # This is a hack to redefine the alibi func due to TP
107
+ if config.tensor_parallel.tp_size > 1:
108
+ self.build_alibi_tensor()
109
+ self.build_attn_bias()
110
+
111
+ if get_accelerator().device_name() == 'cuda' and config.enable_cuda_graph:
112
+ assert pkg_version.parse(torch.__version__) >= pkg_version.parse("1.10"), \
113
+ "If you want to use cuda graph, please upgrade torch to at least v1.10"
114
+
115
+ # convert model to intended dtype
116
+ if config.dtype:
117
+ self._convert_to_dtype(config)
118
+
119
+ if self.mpu:
120
+ config.tensor_parallel.tp_size = dist.get_world_size(group=self.mpu.get_model_parallel_group())
121
+ self.mp_group = self.mpu.get_model_parallel_group()
122
+ elif config.tensor_parallel.tp_size > 1:
123
+ self._create_model_parallel_group(config)
124
+ config.tensor_parallel.tp_group = self.mp_group
125
+
126
+ if isinstance(self.module, torch.nn.Module):
127
+ moe, _ = has_moe_layers(self.module)
128
+ else:
129
+ moe = False
130
+
131
+ if moe and dist.get_world_size() > 1:
132
+ self._create_ep_parallel_group(config.moe.moe_experts)
133
+
134
+ # We only support three modes: 1) user specified policy for tensor-parallelism, 2) kernel injection (replace_with_kernel_inject), and 3) automatic tensor parallelism if tp_size > 1.
135
+ if self.injection_dict:
136
+ # 1. User specified Tensor Parallelism
137
+ assert not config.replace_with_kernel_inject, "Cannot use both user specified injection policy and kernel injection"
138
+ for client_module, injection_policy in self.injection_dict.items():
139
+
140
+ assert issubclass(client_module,
141
+ torch.nn.Module), f"{client_module} is not a subclass of torch.nn.Module"
142
+
143
+ # construct the tuple and pass that instead of a string or dict.
144
+ if isinstance(injection_policy, str):
145
+ config.injection_policy_tuple = (injection_policy, )
146
+ else:
147
+ config.injection_policy_tuple = injection_policy
148
+
149
+ layer_names = [name for name, _ in self.module.named_modules()]
150
+ for policy in config.injection_policy_tuple:
151
+ if not any(name.endswith(policy) for name in layer_names):
152
+ raise ValueError(f"Injection policy layer'{policy}' not valid.")
153
+
154
+ self._apply_injection_policy(config, client_module)
155
+ else:
156
+ if config.replace_with_kernel_inject:
157
+ # 2. DeepSpeed Kernel Injection
158
+ self._apply_injection_policy(config)
159
+ elif config.tensor_parallel.tp_size > 1:
160
+ # 3. Automatic Tensor Parallelism
161
+ parser_dict = AutoTP.tp_parser(model)
162
+ print("AutoTP: ", parser_dict)
163
+ for client_module, injection_policy in parser_dict:
164
+ if isinstance(injection_policy, str):
165
+ config.injection_policy_tuple = (injection_policy, )
166
+ else:
167
+ config.injection_policy_tuple = injection_policy
168
+ self._apply_injection_policy(config, client_module)
169
+
170
+ device = get_accelerator().current_device_name()
171
+ # NOTE: This check assumes a Hugging Face hierarchy for the device type i.e. module.device.type
172
+ is_meta_device = hasattr(self.module, "device") and self.module.device.type == 'meta'
173
+ if is_meta_device:
174
+ self.module.to_empty(device=device)
175
+ else:
176
+ self.module.to(device)
177
+
178
+ if config.tensor_parallel.tp_size > 1:
179
+ _rng_state = get_accelerator().get_rng_state().to(get_accelerator().current_device_name())
180
+ dist.broadcast(_rng_state, 0)
181
+ get_accelerator().set_rng_state(_rng_state.cpu())
182
+
183
+ if config.tensor_parallel.tp_size > 1:
184
+ assert not config.enable_cuda_graph, "Cuda graph is not supported for model parallelism"
185
+
186
+ # Check if local CUDA graphs can be created in replacement modules
187
+ self.local_cuda_graph = self._local_cuda_graph_used(self.module)
188
+
189
+ def destroy(self):
190
+ # Have to import here because inference_module is a global, but python
191
+ # globals only work at the module level and will not be updated unless
192
+ # we import it each time we init a new inference engine.
193
+ from ..model_implementations.transformers.ds_transformer import inference_module
194
+ DeepSpeedTransformerInference.layer_id = 0
195
+ DeepSpeedSelfAttention.num_layers = 0
196
+ if inference_module is not None:
197
+ inference_module.release_workspace()
198
+ inference_module = None
199
+
200
+ def profile_model_time(self, use_cuda_events=True):
201
+ if not self.model_profile_enabled and not self._config.enable_cuda_graph:
202
+ self.module.register_forward_pre_hook(self._pre_forward_hook)
203
+ self.module.register_forward_hook(self._post_forward_hook)
204
+ self.model_profile_enabled = True
205
+ self.use_cuda_events = use_cuda_events
206
+ if self.use_cuda_events:
207
+ self.timers = SynchronizedWallClockTimer()
208
+
209
+ # todo: remove this once all the config dicts are centralized from top level pydantic config
210
+ def _get_model_config_generate(self, config):
211
+ # this is being passed to replace_transformer_layer(config=self.user_model_config_dict)
212
+ self.config = getattr(self.module, 'config', None) if config.config is None else config.config
213
+
214
+ def remove_mask_prepare_for_bloom(self):
215
+ if hasattr(self.module, 'transformer'):
216
+ if hasattr(self.module.transformer, '_prepare_attn_mask'):
217
+ self.module.transformer._prepare_attn_mask = lambda attention_mask, *args, **kwargs: attention_mask
218
+
219
+ def build_alibi_tensor(self):
220
+ if hasattr(self.module, 'transformer'):
221
+ if hasattr(self.module.transformer, 'build_alibi_tensor'):
222
+ self.module.transformer.build_alibi_tensor = build_bloom_alibi_tensor
223
+ if hasattr(self.module.transformer, 'build_mpt_alibi_tensor'):
224
+ self.module.transformer.build_mpt_alibi_tensor_orig = self.module.transformer.build_mpt_alibi_tensor
225
+ self.module.transformer.__class__.build_mpt_alibi_tensor = build_mpt_alibi_tensor
226
+ if hasattr(self.module, 'model'):
227
+ if hasattr(self.module.model, 'get_alibi_mask'):
228
+ self.module.model.get_alibi_mask_orig = self.module.model.get_alibi_mask
229
+ self.module.model.__class__.get_alibi_mask = get_alibi_mask
230
+
231
+ def build_attn_bias(self):
232
+ if hasattr(self.module, 'transformer'):
233
+ if hasattr(self.module.transformer, '_attn_bias'):
234
+ self.module.transformer._attn_bias_orig = self.module.transformer._attn_bias
235
+ self.module.transformer.__class__._attn_bias = build_mpt_atten_bias_tensor
236
+
237
+ def _pre_forward_hook(self, module, *inputs, **kwargs):
238
+ if self.use_cuda_events:
239
+ self.timers(INFERENCE_MODEL_TIMER).start()
240
+ else:
241
+ get_accelerator().synchronize()
242
+ self._start = time.time()
243
+
244
+ def _post_forward_hook(self, module, input, output):
245
+ if self.use_cuda_events:
246
+ self.timers(INFERENCE_MODEL_TIMER).stop()
247
+ elapsed_time = self.timers(INFERENCE_MODEL_TIMER).elapsed(reset=True)
248
+ else:
249
+ get_accelerator().synchronize()
250
+ self._end = time.time()
251
+ elapsed_time = (self._end - self._start) * 1e3 # convert seconds to ms
252
+ self._model_times.append(elapsed_time)
253
+
254
+ def _create_model_parallel_group(self, config):
255
+ # Call the init process
256
+ if InferenceEngine.inference_mp_group is None:
257
+ init_distributed()
258
+ local_rank = int(os.getenv('LOCAL_RANK', '0'))
259
+ get_accelerator().set_device(local_rank)
260
+
261
+ ranks = [i for i in range(config.tensor_parallel.tp_size)]
262
+ self.mp_group = dist.new_group(ranks)
263
+ InferenceEngine.inference_mp_group = self.mp_group
264
+ else:
265
+ self.mp_group = InferenceEngine.inference_mp_group
266
+
267
+ def _create_ep_parallel_group(self, moe_experts):
268
+ # Call the init process
269
+ self.ep_group = {}
270
+ self.expert_mp_group = {}
271
+ moe_experts = moe_experts if type(moe_experts) is list else [moe_experts]
272
+ for e in moe_experts:
273
+ self.ep_group.update({e: None})
274
+ self.expert_mp_group.update({e: None})
275
+ for moe_ep_size in self.ep_group.keys():
276
+ num_ep_groups = dist.get_world_size() // moe_ep_size
277
+ for i in range(num_ep_groups):
278
+ ep_cnt = i * moe_ep_size
279
+ size = dist.get_world_size() if moe_ep_size > dist.get_world_size() else moe_ep_size
280
+ ranks = list(range(ep_cnt, ep_cnt + size))
281
+ _ep_group = dist.new_group(ranks)
282
+ if dist.get_rank() in ranks:
283
+ self.ep_group.update({moe_ep_size: _ep_group})
284
+
285
+ if dist.get_world_size() > moe_ep_size:
286
+ num_expert_mp_groups = dist.get_world_size() // num_ep_groups
287
+ expert_mp_size = dist.get_world_size() // moe_ep_size
288
+ for i in range(num_expert_mp_groups):
289
+ expert_mp_comm_ranks = [i + nr * moe_ep_size for nr in range(expert_mp_size)]
290
+ _expert_mp_group = dist.new_group(expert_mp_comm_ranks)
291
+ if dist.get_rank() in expert_mp_comm_ranks:
292
+ self.expert_mp_group.update({moe_ep_size: _expert_mp_group})
293
+
294
+ def _init_quantization_setting(self, quantization_setting):
295
+ self.quantize_bits = 8
296
+ self.mlp_extra_grouping = False
297
+ self.quantize_groups = 1
298
+ if type(quantization_setting) is tuple:
299
+ self.mlp_extra_grouping, \
300
+ self.quantize_groups = quantization_setting
301
+ elif quantization_setting is not None:
302
+ self.quantize_groups = quantization_setting
303
+ log_dist(
304
+ f"quantize_bits = {self.quantize_bits} "
305
+ f"mlp_extra_grouping = {self.mlp_extra_grouping}, "
306
+ f"quantize_groups = {self.quantize_groups}", [0])
307
+
308
+ # TODO: remove this function and add this functionality to pydantic config checking
309
+ def _validate_args(self, mpu, replace_with_kernel_inject):
310
+ # TODO: to support SD pipeline we need to avoid this check for now
311
+ if replace_with_kernel_inject and not isinstance(self.module, Module):
312
+ raise ValueError(f"model must be a torch.nn.Module, got {type(self.module)}")
313
+ if not isinstance(self._config.tensor_parallel.tp_size, int) or self._config.tensor_parallel.tp_size < 1:
314
+ raise ValueError(f"mp_size must be an int >= 1, got {self._config.tensor_parallel.tp_size}")
315
+
316
+ if mpu:
317
+ methods = ["get_model_parallel_group", "get_data_parallel_group"]
318
+ for method in methods:
319
+ if not hasattr(mpu, method):
320
+ raise ValueError(f"mpu is missing {method}")
321
+ if self._config.checkpoint is not None and not isinstance(self._config.checkpoint, (str, dict)):
322
+ raise ValueError(f"checkpoint must be None, str or dict, got {type(self._config.checkpoint)}")
323
+
324
+ supported_dtypes = [None, torch.half, torch.int8, torch.float]
325
+ if self._config.dtype not in supported_dtypes:
326
+ raise ValueError(f"{self._config.dtype} not supported, valid dtype: {supported_dtypes}")
327
+
328
+ if self.injection_dict is not None and not isinstance(self.injection_dict, dict):
329
+ raise ValueError(f"injection_dict must be None or a dict, got: {self.injection_dict}")
330
+
331
+ def load_model_with_checkpoint(self, r_module):
332
+ self.mp_replace = ReplaceWithTensorSlicing(
333
+ mp_group=self.mp_group, mp_size=self._config.tensor_parallel.tp_size) #, out_dim=0, in_dim=1)
334
+ error_msgs = []
335
+
336
+ def load(module, state_dict, prefix):
337
+ args = (state_dict, prefix, {}, True, [], [], error_msgs)
338
+ if hasattr(module, 'weight'):
339
+ if module.weight.data.is_meta:
340
+ # meta tensor cannot be casted or copied to, so we need to replace it with a normal tensor here
341
+ module.weight = torch.nn.parameter.Parameter(data=torch.empty_like(module.weight.data,
342
+ device="cpu"),
343
+ requires_grad=module.weight.data.requires_grad)
344
+ if 'query_key_value' in prefix:
345
+ module.weight = self.mp_replace.strided_copy(module.weight.data,
346
+ state_dict[prefix + 'weight'],
347
+ num_splits=3)
348
+ else:
349
+ module.weight = self.mp_replace.copy(module.weight.data, state_dict[prefix + 'weight'])
350
+ else:
351
+ if module.norm.weight.data.is_meta:
352
+ # meta tensor cannot be casted or copied to, so we need to replace it with a normal tensor here
353
+ module.norm.weight = torch.nn.parameter.Parameter(
354
+ data=torch.empty_like(module.norm.weight.data, device="cpu"),
355
+ requires_grad=module.norm.weight.data.requires_grad)
356
+ module.norm.weight = self.mp_replace.copy(module.norm.weight.data, state_dict[prefix + 'weight'])
357
+ if prefix + 'bias' in self.key_list:
358
+ if hasattr(module, 'norm'):
359
+ if module.norm.bias.data.is_meta:
360
+ # meta tensor cannot be casted or copied to, so we need to replace it with a normal tensor here
361
+ module.norm.bias = torch.nn.parameter.Parameter(
362
+ data=torch.empty_like(module.norm.bias.data, device="cpu"),
363
+ requires_grad=module.norm.bias.data.requires_grad)
364
+ module.norm.bias = self.mp_replace.copy(module.norm.bias, state_dict[prefix + 'bias'])
365
+ else:
366
+ if module.bias.data.is_meta:
367
+ # meta tensor cannot be casted or copied to, so we need to replace it with a normal tensor here
368
+ module.bias = torch.nn.parameter.Parameter(data=torch.empty_like(module.bias.data,
369
+ device="cpu"),
370
+ requires_grad=module.bias.data.requires_grad)
371
+ data = state_dict[prefix + 'bias']
372
+ data = data.to(get_accelerator().current_device_name())
373
+ module.bias = self.mp_replace.copy(module.bias, data)
374
+
375
+ layer_policies = {
376
+ nn.Linear: load,
377
+ nn.Embedding: load,
378
+ nn.LayerNorm: load,
379
+ LinearLayer: load,
380
+ LinearAllreduce: load
381
+ }
382
+
383
+ def load_module_recursive(module, prefix='', level=0):
384
+ for name, child in module.named_children():
385
+ if child.__class__ in layer_policies:
386
+ checking_key = prefix + name + '.'
387
+ if not any(checking_key in item for item in self.key_list):
388
+ continue
389
+ if len(list(child.parameters())) > 0 and list(child.parameters())[0].numel() == 0:
390
+ if len(child.weight.ds_shape) == 1:
391
+ child = Normalize(dim=child.weight.ds_shape[-1], dtype=child.weight.dtype, eps=child.eps)
392
+ setattr(module, name, child)
393
+ load(child, self.sd, prefix + name + '.')
394
+ else:
395
+ load_module_recursive(child, prefix if level == 0 else prefix + name + '.', level + 1)
396
+
397
+ load_module_recursive(r_module)
398
+
399
+ embedding_weight = None
400
+
401
+ for n, p in r_module.named_parameters():
402
+ if "word_embeddings." in n or "embed_tokens." in n or "wte." in n:
403
+ embedding_weight = p
404
+ if embedding_weight is not None and hasattr(r_module, "lm_head") and hasattr(
405
+ r_module.lm_head, "weight") and r_module.lm_head.weight.is_meta:
406
+ r_module.lm_head.weight = embedding_weight
407
+
408
+ def _apply_injection_policy(self, config, client_module=None):
409
+ # client_module is only passed when using the injection_dict method.
410
+ checkpoint_dir = config.checkpoint
411
+ checkpoint = SDLoaderFactory.get_sd_loader_json(checkpoint_dir,
412
+ self.checkpoint_engine) if checkpoint_dir is not None else None
413
+
414
+ generic_injection(self.module, dtype=config.dtype, enable_cuda_graph=config.enable_cuda_graph)
415
+
416
+ if isinstance(self.module, torch.nn.Module):
417
+ # config is our DeepSpeedInferenceConfig and self.config is the HF model config
418
+ replace_transformer_layer(client_module, self.module, checkpoint, config, self.config)
419
+
420
+ def _get_all_ckpt_names(self, checkpoints_path, tag):
421
+ ckpt_file_pattern = self._get_ckpt_name(checkpoints_path, tag, mp_placeholder="*")
422
+ import glob
423
+
424
+ ckpt_files = glob.glob(ckpt_file_pattern)
425
+ ckpt_files.sort()
426
+ return ckpt_files
427
+
428
+ def _get_ckpt_name(self, checkpoints_path, tag, mp_placeholder=None):
429
+ if mp_placeholder is not None:
430
+ mp_rank_str = mp_placeholder
431
+ else:
432
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
433
+ mp_rank_str = "{:02d}".format(mp_rank)
434
+
435
+ ckpt_name = os.path.join(
436
+ checkpoints_path,
437
+ "mp_rank_" + mp_rank_str + "_model_states.pt",
438
+ )
439
+ return ckpt_name
440
+
441
+ def _load_checkpoint(self, load_dir, load_module_strict=True, tag=None):
442
+ is_pipe_parallel = isinstance(self.module, PipelineModule)
443
+ if is_pipe_parallel:
444
+ raise RuntimeError('pipeline parallelism is currently not supported in inference.')
445
+ if not isinstance(load_dir, dict) and os.path.isdir(load_dir):
446
+ if tag is None:
447
+ latest_path = os.path.join(load_dir, "latest")
448
+ if os.path.isfile(latest_path):
449
+ with open(latest_path, "r") as fd:
450
+ tag = fd.read().strip()
451
+
452
+ ckpt_list = self._get_all_ckpt_names(load_dir, tag)
453
+ sd_loader = SDLoaderFactory.get_sd_loader(ckpt_list, self.checkpoint_engine)
454
+ else:
455
+ sd_loader = SDLoaderFactory.get_sd_loader_json(load_dir, self.checkpoint_engine)
456
+
457
+ checkpoint = sd_loader['checkpoints']
458
+
459
+ if type(checkpoint) is list:
460
+ self.sd = torch.load(checkpoint[0], map_location='cpu')
461
+ self.key_list = list(self.sd.keys())
462
+
463
+ self.load_model_with_checkpoint(self.module)
464
+
465
+ for i in range(1, len(checkpoint)):
466
+ if not dist.is_initialized() or dist.get_rank() == 0:
467
+ print(f"loading checkpoint ({i})")
468
+ self.sd = torch.load(checkpoint[i], map_location=get_accelerator().device_name())
469
+ self.key_list = list(self.sd.keys())
470
+ self.load_model_with_checkpoint(self.module)
471
+ else:
472
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
473
+
474
+ load_path, checkpoint, quantize_config = sd_loader.load(self._config.tensor_parallel.tp_size,
475
+ mp_rank,
476
+ is_pipe_parallel=is_pipe_parallel,
477
+ quantize=(self._config.dtype is torch.int8),
478
+ quantize_groups=self.quantize_groups,
479
+ mlp_extra_grouping=self.mlp_extra_grouping)
480
+
481
+ self.quantization_scales, self.quantize_merge_count = quantize_config
482
+
483
+ moe, _ = has_moe_layers(self.module)
484
+ if moe:
485
+ from deepspeed.runtime.engine import DeepSpeedEngine
486
+ old_moe_load = False
487
+ if not isinstance(checkpoint['num_experts'], list):
488
+ old_moe_load = True
489
+ DeepSpeedEngine.load_moe_state_dict(load_dir,
490
+ tag,
491
+ state_dict=checkpoint[self._choose_module_key(checkpoint)],
492
+ old_moe_load=old_moe_load,
493
+ model=self.module,
494
+ mpu=self.mpu,
495
+ checkpoint_engine=self.checkpoint_engine)
496
+
497
+ self.module.load_state_dict(state_dict=checkpoint[self._choose_module_key(checkpoint)],
498
+ strict=load_module_strict)
499
+
500
+ def _choose_module_key(self, sd):
501
+ assert not ('module' in sd
502
+ and 'model' in sd), "checkpoint has both 'model' and 'module' keys, not sure how to proceed"
503
+ assert 'module' in sd or 'model' in sd, "checkpoint contains neither 'model' or 'module' keys, not sure how to proceed"
504
+ if 'module' in sd:
505
+ return 'module'
506
+ elif 'model' in sd:
507
+ return 'model'
508
+
509
+ def _convert_to_dtype(self, config):
510
+ if not isinstance(self.module, torch.nn.Module):
511
+ return
512
+
513
+ if False: #config.dtype is torch.int8 and self.quantization_scales is None:
514
+ quantizer = WeightQuantization(mlp_extra_grouping=self.mlp_extra_grouping)
515
+ model, self.quantization_scales = quantizer.model_quantize(self.module, self.injection_dict,
516
+ self.quantize_bits, self.quantize_groups)
517
+ elif config.dtype == torch.half:
518
+ self.module.half()
519
+ elif config.dtype == torch.bfloat16:
520
+ self.module.bfloat16()
521
+ elif config.dtype == torch.float:
522
+ self.module.float()
523
+
524
+ def _create_cuda_graph(self, *inputs, **kwargs):
525
+ # warmup to create the workspace and cublas handle
526
+ cuda_stream = get_accelerator().Stream()
527
+ cuda_stream.wait_stream(get_accelerator().current_stream())
528
+ with get_accelerator().stream(cuda_stream):
529
+ for i in range(3):
530
+ ret = self.module(*inputs, **kwargs)
531
+ get_accelerator().current_stream().wait_stream(cuda_stream)
532
+
533
+ # create cuda_graph and assign static_inputs and static_outputs
534
+ self._cuda_graphs = get_accelerator().create_graph()
535
+ self.static_inputs = inputs
536
+ self.static_kwargs = kwargs
537
+
538
+ with get_accelerator().capture_to_graph(self._cuda_graphs):
539
+ self.static_output = self.module(*self.static_inputs, **self.static_kwargs)
540
+
541
+ self.cuda_graph_created = True
542
+
543
+ def _graph_replay(self, *inputs, **kwargs):
544
+ for i in range(len(inputs)):
545
+ if torch.is_tensor(inputs[i]):
546
+ self.static_inputs[i].copy_(inputs[i])
547
+ for k in kwargs:
548
+ if torch.is_tensor(kwargs[k]):
549
+ self.static_kwargs[k].copy_(kwargs[k])
550
+ get_accelerator().replay_graph(self._cuda_graphs)
551
+ return self.static_output
552
+
553
+ def model_times(self):
554
+ assert self.model_profile_enabled, "model profiling is not enabled"
555
+ model_times = self._model_times
556
+ if self._config.enable_cuda_graph and len(self._model_times) == 0:
557
+ raise ValueError("Model times are empty and cuda graph is enabled. If "
558
+ "this is a GPT-style model this combo is not supported. If this is a "
559
+ "BERT-style model this is a bug, please report it. "
560
+ f"Model type is: {type(self.module)}")
561
+ self._model_times = []
562
+ return model_times
563
+
564
+ def _module_match(self, module):
565
+ for policy in generic_policies:
566
+ policy = policy()
567
+ if policy.match_replaced(module):
568
+ return True
569
+ return False
570
+
571
+ def _local_cuda_graph_used(self, module):
572
+ if isinstance(module, torch.nn.Module):
573
+ return False
574
+ else:
575
+ sub_module_cuda_graph = False
576
+ for name in module.__dict__.keys():
577
+ sub_module = getattr(module, name)
578
+
579
+ if self._module_match(sub_module) and hasattr(sub_module, "enable_cuda_graph"):
580
+ sub_module_cuda_graph = True
581
+
582
+ return sub_module_cuda_graph
583
+
584
+ def forward(self, *inputs, **kwargs):
585
+ """Execute forward propagation
586
+
587
+ Arguments:
588
+ *inputs: Variable length input list
589
+ **kwargs: variable length keyword arguments
590
+ """
591
+ start = None
592
+ if self.model_profile_enabled and get_accelerator().device_name() == 'cuda' and self._config.enable_cuda_graph:
593
+ get_accelerator().synchronize()
594
+ start = time.time()
595
+
596
+ if get_accelerator().device_name() == 'cuda' and self._config.enable_cuda_graph and not self.local_cuda_graph:
597
+ if self.cuda_graph_created:
598
+ outputs = self._graph_replay(*inputs, **kwargs)
599
+ else:
600
+ self._create_cuda_graph(*inputs, **kwargs)
601
+ outputs = self._graph_replay(*inputs, **kwargs)
602
+
603
+ else:
604
+ outputs = self.module(*inputs, **kwargs)
605
+
606
+ if self.model_profile_enabled and self._config.enable_cuda_graph:
607
+ get_accelerator().synchronize()
608
+ duration = (time.time() - start) * 1e3 # convert seconds to ms
609
+ self._model_times.append(duration)
610
+
611
+ return outputs
612
+
613
+ def _generate(self, *inputs, **kwargs):
614
+ # Reset KV-cache at the beginning of generate
615
+ if hasattr(self.module, 'reset_cache'):
616
+ self.module.reset_cache()
617
+ num_beams = 1
618
+ if "generation_config" in kwargs:
619
+ gen_config = kwargs["generation_config"]
620
+ num_beams = getattr(gen_config, "num_beams", 1)
621
+ if "num_beams" in kwargs:
622
+ num_beams = kwargs["num_beams"]
623
+
624
+ if num_beams > 1:
625
+ raise NotImplementedError("DeepSpeed does not support `num_beams` > 1, if this is important to you please "
626
+ "add your request to: https://github.com/microsoft/DeepSpeed/issues/2506")
627
+
628
+ if ("input_ids" in kwargs) and (kwargs["input_ids"].dim() == 2):
629
+ for input_tensor in kwargs["input_ids"]:
630
+ tensor_length = input_tensor.shape[-1]
631
+ if tensor_length > self._config.max_out_tokens:
632
+ raise RuntimeError(
633
+ f"Input with size {tensor_length} exceeds maximum length of {self._config.max_out_tokens}. Please increase `max_tokens` in the DeepSpeed Inference Config."
634
+ )
635
+
636
+ return self.module.generate(*inputs, **kwargs)
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (200 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/layers.cpython-310.pyc ADDED
Binary file (3.61 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/quantization.cpython-310.pyc ADDED
Binary file (3.16 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/quantization_context.cpython-310.pyc ADDED
Binary file (835 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/__pycache__/utils.cpython-310.pyc ADDED
Binary file (9.19 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/layers.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import torch
7
+
8
+ from torch import nn
9
+ from torch import Tensor
10
+ from torch.nn import functional as F
11
+ from .utils import Quantizer, DeQuantizer, concat_to_compat_param
12
+ from typing import Tuple, Callable, Dict
13
+ from deepspeed.runtime.zero import register_external_parameter
14
+
15
+ quantized_weight_registry = {}
16
+ is_zero3_enabled = False
17
+
18
+
19
+ # deal with weight sharing
20
+ def get_quantized_weight_wrapper(model, pre_quant_weight: nn.Parameter, quantize_weight_fn: Callable) -> nn.Parameter:
21
+ if id(pre_quant_weight) in quantized_weight_registry:
22
+ compat_tensor = quantized_weight_registry[id(pre_quant_weight)]
23
+ if is_zero3_enabled:
24
+ register_external_parameter(model, compat_tensor)
25
+
26
+ return quantized_weight_registry[id(pre_quant_weight)]
27
+ else:
28
+ quantized_weights, quant_scale, quant_min = quantize_weight_fn()
29
+ quantized_weight_registry[id(pre_quant_weight)] = concat_to_compat_param(quantized_weights, quant_scale,
30
+ quant_min)
31
+ return quantized_weight_registry[id(pre_quant_weight)]
32
+
33
+
34
+ def get_quantize_weight_fn(quantizer: Quantizer, pre_quant_weight: nn.Parameter) -> Callable:
35
+
36
+ def func() -> Tuple[nn.Parameter, Tensor, Tensor]:
37
+ quantized_weights, quant_scale, quant_min = quantizer.quantize(pre_quant_weight.data)
38
+ # A temporary hack as zero Zero3 assume all model weights has the same type. in all_gather_coalesced.get_only_unique_item
39
+ quantized_weights = quantized_weights.view(pre_quant_weight.dtype)
40
+ quant_scale = quant_scale.type(pre_quant_weight.dtype)
41
+ quant_min = quant_min.type(pre_quant_weight.dtype)
42
+ return quantized_weights, quant_scale, quant_min
43
+
44
+ return func
45
+
46
+
47
+ class QuantizedLinear(nn.Linear):
48
+
49
+ def __init__(self, config: Dict, pre_quant_layer: nn.Linear) -> None:
50
+ super(QuantizedLinear, self).__init__(in_features=pre_quant_layer.in_features,
51
+ out_features=pre_quant_layer.out_features,
52
+ bias=pre_quant_layer.bias is not None,
53
+ device=pre_quant_layer.weight.device,
54
+ dtype=pre_quant_layer.weight.dtype)
55
+ self.config = config
56
+
57
+ self.quantizer = Quantizer(config=config)
58
+ self.bias = pre_quant_layer.bias
59
+ self.weight = get_quantized_weight_wrapper(self, pre_quant_layer.weight,
60
+ get_quantize_weight_fn(self.quantizer, pre_quant_layer.weight))
61
+
62
+ self.weight.dequantizer = DeQuantizer(config, pre_quant_layer.weight.dtype)
63
+
64
+ def forward(self, input: Tensor) -> Tensor:
65
+ quantized_weight, quant_scale, quant_min = self.weight.deconcat(self.weight)
66
+ temp_dequantized_weight = self.weight.dequantizer.dequantize(quantized_weight.view(torch.uint8), quant_scale,
67
+ quant_min)
68
+
69
+ # !!! Do not use torch.functional.linear(input, temp_dequantized_weight, self.bias) here as in zero3 torch.functional.linear is
70
+ # replaced by LinearFunctionForZeroStage3. Which assume weight is non-temporary.
71
+ # If weight is temp buffer there will be memory leak.
72
+ return torch._C._nn.linear(input, temp_dequantized_weight, self.bias)
73
+
74
+
75
+ class QuantizedEmbedding(nn.Embedding):
76
+
77
+ def __init__(self, config: Dict, pre_quant_layer: nn.Embedding) -> None:
78
+ super(QuantizedEmbedding, self).__init__(num_embeddings=pre_quant_layer.num_embeddings,
79
+ embedding_dim=pre_quant_layer.embedding_dim,
80
+ padding_idx=pre_quant_layer.padding_idx,
81
+ max_norm=pre_quant_layer.max_norm,
82
+ norm_type=pre_quant_layer.norm_type,
83
+ scale_grad_by_freq=pre_quant_layer.scale_grad_by_freq,
84
+ sparse=pre_quant_layer.sparse,
85
+ _weight=pre_quant_layer.weight,
86
+ device=pre_quant_layer.weight.device,
87
+ dtype=pre_quant_layer.weight.dtype)
88
+
89
+ assert pre_quant_layer.max_norm is None, 'Not supported'
90
+ assert pre_quant_layer.norm_type == 2, 'Not supported'
91
+ assert pre_quant_layer.scale_grad_by_freq == False, 'Not supported'
92
+ assert pre_quant_layer.sparse == False, 'Not supported'
93
+
94
+ self.config = config
95
+ quantizer = Quantizer(config=config)
96
+
97
+ self.weight = get_quantized_weight_wrapper(self, pre_quant_layer.weight,
98
+ get_quantize_weight_fn(quantizer, pre_quant_layer.weight))
99
+
100
+ self.weight.dequantizer = DeQuantizer(config, pre_quant_layer.weight.dtype)
101
+
102
+ def forward(self, input: Tensor) -> Tensor:
103
+ quantized_weight, quant_scale, quant_min = self.weight.deconcat(self.weight)
104
+ temp_dequantized_weight = self.weight.dequantizer.dequantize(quantized_weight.view(torch.uint8), quant_scale,
105
+ quant_min)
106
+
107
+ return F.embedding(input, temp_dequantized_weight, self.padding_idx, self.max_norm, self.norm_type,
108
+ self.scale_grad_by_freq, self.sparse)
109
+
110
+
111
+ QUANTIZATION_LAYER_MAPPINGS = {
112
+ nn.Linear: QuantizedLinear,
113
+ nn.Embedding: QuantizedEmbedding,
114
+ }
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/quantization.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import torch
7
+ from torch import nn
8
+ from typing import Dict
9
+ import gc
10
+ from deepspeed.inference.quantization import layers
11
+ from .layers import QUANTIZATION_LAYER_MAPPINGS
12
+ from .utils import get_AsyncPartitionedParameterSwapper, recursive_setattr
13
+ from deepspeed.utils.logging import logger
14
+ from collections import deque
15
+ from transformers.utils.generic import ContextManagers
16
+ from .quantization_context import QuantizationContext
17
+ import contextlib
18
+
19
+
20
+ def _init_group_wise_weight_quantization(model: nn.Module, ds_config: Dict) -> nn.Module:
21
+ """[Experimental] Apply group-wise weight quantization to model. Replace layers module according to config_list
22
+
23
+ Args:
24
+ model (nn.Module): A nn.Module
25
+ ds_config (Dict, optional): The ds_config dictionary. use None for non-deepspeed managed model.
26
+
27
+ Returns:
28
+ nn.Module: Quantized nn.Module
29
+ """
30
+
31
+ # global quantized_weight_registry
32
+
33
+ matched_module_list_by_key = {}
34
+ matched_module_count = 0
35
+
36
+ assert 'weight_quantization' in ds_config, 'Please provide quantization config in ds_config'
37
+ quantization_config = ds_config['weight_quantization']['post_init_quant']
38
+
39
+ # Return nvme swapper if exists, else return None.
40
+ # For nvme offloading we must use the same swapper here as model initialized.
41
+ nvme_swapper = get_AsyncPartitionedParameterSwapper(model)
42
+ is_zero3_enabled = 'zero_optimization' in ds_config and \
43
+ 'stage' in ds_config['zero_optimization'] and \
44
+ ds_config['zero_optimization']['stage'] == 3
45
+ is_offloading_enabled = 'zero_optimization' in ds_config and \
46
+ 'offload_param' in ds_config['zero_optimization']
47
+
48
+ layers.is_zero3_enabled = is_zero3_enabled
49
+
50
+ context_mgr = ContextManagers([QuantizationContext(config_dict_or_path=ds_config, param_swapper=nvme_swapper)]) \
51
+ if is_zero3_enabled else contextlib.suppress()
52
+ with context_mgr:
53
+ module_list = list(
54
+ filter(lambda named_module: type(named_module[1]) in QUANTIZATION_LAYER_MAPPINGS, model.named_modules()))
55
+
56
+ # Quantize small weight first then large.
57
+ if not is_offloading_enabled:
58
+ module_list.sort(key=lambda named_module: named_module[1].weight.ds_tensor.numel()
59
+ if is_zero3_enabled else named_module[1].weight.numel())
60
+ module_list = deque(module_list)
61
+
62
+ while len(module_list) > 0:
63
+ # Use popleft to timely release module's memory of replaced module after each loop iteration
64
+ module_name, module = module_list.popleft()
65
+
66
+ matched_key = None
67
+ matched_quantization_config = None
68
+
69
+ for key, config in quantization_config.items():
70
+ if key in module_name:
71
+ assert matched_key is None, f'{module_name} matched multiple quantization key word {matched_key} and {key}'
72
+ matched_key = key
73
+ matched_quantization_config = config
74
+
75
+ if matched_key is None:
76
+ continue
77
+
78
+ if is_zero3_enabled:
79
+ module.weight.all_gather()
80
+
81
+ assert module.weight.dtype == torch.float16, 'Model weight is expected in half.'
82
+
83
+ new_module = QUANTIZATION_LAYER_MAPPINGS[type(module)](matched_quantization_config, module)
84
+
85
+ if is_zero3_enabled:
86
+ module.weight.partition()
87
+
88
+ recursive_setattr(model, module_name, new_module)
89
+
90
+ if matched_key not in matched_module_list_by_key:
91
+ matched_module_list_by_key[matched_key] = []
92
+ matched_module_list_by_key[matched_key].append(module_name)
93
+ matched_module_count += 1
94
+
95
+ # Timely recycle memory to prevent OOM on large models
96
+ gc.collect()
97
+
98
+ # Clear registry after model construction.
99
+ layers.quantized_weight_registry.clear()
100
+
101
+ logger.info(
102
+ f'Group-wise weight quantization summary: convert {matched_module_count} node(s) to quantized implementation')
103
+ summary_str = '\n'
104
+
105
+ for key, module_list in matched_module_list_by_key.items():
106
+ summary_str += f'Key: {key}, matched modules:\n'
107
+ for module_name in module_list:
108
+ summary_str += f'\t{module_name}\n'
109
+ logger.info(summary_str)
110
+
111
+ return model
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/quantization_context.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from deepspeed.runtime.zero import partition_parameters
7
+ from deepspeed.runtime.swap_tensor.partitioned_param_swapper import AsyncPartitionedParameterSwapper
8
+
9
+
10
+ class QuantizationContext(partition_parameters.Init):
11
+
12
+ def __init__(self, config_dict_or_path, param_swapper: AsyncPartitionedParameterSwapper = None) -> None:
13
+ super().__init__(config_dict_or_path=config_dict_or_path, param_swapper=param_swapper)
venv/lib/python3.10/site-packages/deepspeed/inference/quantization/utils.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import torch
7
+ import deepspeed
8
+ from torch import Tensor
9
+ from typing import Tuple
10
+ import torch.nn as nn
11
+ from typing import Dict, Callable, Union
12
+ from deepspeed.accelerator import get_accelerator
13
+ import functools
14
+
15
+ device = get_accelerator().device_name() if get_accelerator().is_available() else 'cpu'
16
+
17
+ quantizer_cuda_module = None
18
+
19
+
20
+ def get_quantizer_cuda_module():
21
+ global quantizer_cuda_module
22
+ if quantizer_cuda_module is None:
23
+ quantizer_cuda_module = deepspeed.ops.op_builder.QuantizerBuilder().load()
24
+ return quantizer_cuda_module
25
+
26
+
27
+ def tensor_clamp(tensor: Tensor, min, max) -> Tensor:
28
+ if tensor.device.type == 'cpu' and tensor.dtype == torch.float16:
29
+ # CPU does not support FP16 clamp
30
+ return tensor.to(dtype=torch.float32).clamp_(min, max).to(dtype=torch.float16)
31
+ else:
32
+ return tensor.clamp_(min, max)
33
+
34
+
35
+ def tensor_round(tensor: Tensor) -> Tensor:
36
+ if tensor.device.type == 'cpu' and tensor.dtype == torch.float16:
37
+ # CPU does not support FP16 round
38
+ return tensor.to(dtype=torch.float32).round_().to(dtype=torch.float16)
39
+ else:
40
+ return tensor.round_()
41
+
42
+
43
+ class Quantizer:
44
+
45
+ def __init__(self, config: Dict) -> None:
46
+ self.config = config
47
+ assert self.config['num_bits'] == 4 or self.config[
48
+ 'num_bits'] == 8, 'Only INT4 and INT8 quantization is supported.'
49
+ assert self.config['symmetric'] == False, 'Only asymmetric quantization is supported at this moment.'
50
+
51
+ def quantize(self, tensor: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
52
+ assert tensor.shape[self.config['group_dim']] % self.config['group_size'] == 0 \
53
+ , f'Tensor shape: {tensor.shape} quantization config {self.config}'
54
+
55
+ tensor = torch.clone(tensor)
56
+
57
+ shape = tensor.shape
58
+ num_groups = shape[self.config['group_dim']] // self.config['group_size']
59
+ new_shape = (shape[:self.config['group_dim']] + (num_groups, self.config['group_size']) +
60
+ shape[self.config['group_dim'] + 1:])
61
+ tensor = tensor.view(new_shape)
62
+
63
+ quantized_tensor, scale, min_value = self._quantize_int8(tensor)
64
+ quantized_tensor = quantized_tensor.view(shape)
65
+
66
+ if self.config['num_bits'] == 4:
67
+ return self._compress_uint8_to_uint4(quantized_tensor), scale, min_value
68
+ if self.config['num_bits'] == 8:
69
+ return quantized_tensor, scale, min_value
70
+
71
+ assert False, 'Unsupported quantization bits {}'.format(self.config['num_bits'])
72
+
73
+ def _quantize_int8(self, tensor: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
74
+ q_range = 2**self.config['num_bits'] - 1
75
+ min_value = tensor.amin(dim=self.config['group_dim'] + 1, keepdim=True)
76
+ max_value = tensor.amax(dim=self.config['group_dim'] + 1, keepdim=True)
77
+
78
+ scale = q_range / (max_value - min_value)
79
+
80
+ tensor = tensor.sub_(min_value).mul_(scale)
81
+ tensor = tensor_round(tensor_clamp(tensor, 0, q_range)).to(torch.uint8)
82
+ return tensor, scale, min_value
83
+
84
+ def _compress_uint8_to_uint4(self, tensor: Tensor) -> Tensor:
85
+ assert tensor.shape[-1] % 2 == 0
86
+
87
+ new_data_shape = list(tensor.shape)
88
+ new_data_shape[-1] = new_data_shape[-1] // 2
89
+
90
+ data = torch.empty(new_data_shape, dtype=torch.uint8, device=tensor.device)
91
+ data = torch.bitwise_or(tensor[..., 0::2].bitwise_left_shift(4), tensor[..., 1::2])
92
+
93
+ return data
94
+
95
+
96
+ class DeQuantizer:
97
+
98
+ def __init__(self, config: Dict, dtype: torch.dtype) -> None:
99
+ self.config = config
100
+ self.dtype = dtype
101
+ assert self.config['num_bits'] == 4 or self.config[
102
+ 'num_bits'] == 8, 'Only INT4 and INT8 quantization is supported.'
103
+ assert self.config['symmetric'] == False, 'Only asymmetric quantization is supported at this moment.'
104
+
105
+ def dequantize(self, tensor: Tensor, quant_scale: Tensor, quant_min: Tensor) -> Tensor:
106
+ # Use customized CUDA quantization kernel if possible.
107
+ if self.config['group_size'] % 8 == 0 and \
108
+ (self.config['num_bits'] == 4 or self.config['num_bits'] == 8) and \
109
+ self.config['group_dim'] == len(tensor.shape) - 1 and \
110
+ self.dtype == torch.float16 and device == 'cuda':
111
+
112
+ last_dimension_size = self.config['group_size']
113
+ if self.config['num_bits'] == 4:
114
+ last_dimension_size = last_dimension_size // 2
115
+ quantized_tensor = get_quantizer_cuda_module().dequantize_int4_to_half_experimental(
116
+ tensor.reshape(-1, last_dimension_size), quant_scale, quant_min,
117
+ tensor.numel() // last_dimension_size, self.config['group_size'])
118
+ shape = list(tensor.shape)
119
+ shape[-1] = shape[-1] * 2
120
+ elif self.config['num_bits'] == 8:
121
+ # last_dimension_size = last_dimension_size // 2
122
+ quantized_tensor = get_quantizer_cuda_module().dequantize_int8_to_half_experimental(
123
+ tensor.reshape(-1, last_dimension_size), quant_scale, quant_min,
124
+ tensor.numel() // last_dimension_size, self.config['group_size'])
125
+ shape = list(tensor.shape)
126
+
127
+ return quantized_tensor.reshape(shape)
128
+
129
+ if self.config['num_bits'] == 4:
130
+ tensor = self._decompress_uint4_to_uint8(tensor)
131
+ elif self.config['num_bits'] != 8:
132
+ assert False, 'Unsupported quantization bits {}'.format(self.config['num_bits'])
133
+
134
+ shape = tensor.shape
135
+ num_groups = shape[self.config['group_dim']] // self.config['group_size']
136
+ new_shape = (shape[:self.config['group_dim']] + (num_groups, self.config['group_size']) +
137
+ shape[self.config['group_dim'] + 1:])
138
+ tensor = tensor.view(new_shape)
139
+
140
+ dequantized_tensor = self._dequantize_int8(tensor, quant_scale, quant_min).view(shape)
141
+ return dequantized_tensor
142
+
143
+ def _dequantize_int8(self, tensor: Tensor, quant_scale: Tensor, quant_min: Tensor) -> Tensor:
144
+ assert tensor.dtype == torch.uint8
145
+ data = torch.zeros_like(tensor, dtype=self.dtype, device=tensor.device)
146
+ data = data.copy_(tensor)
147
+ data = data.div_(quant_scale).add_(quant_min)
148
+
149
+ return data
150
+
151
+ def _decompress_uint4_to_uint8(self, tensor: Tensor) -> Tensor:
152
+ new_data_shape = list(tensor.shape)
153
+ new_data_shape[-1] = new_data_shape[-1] * 2
154
+ data = torch.empty(new_data_shape, dtype=torch.uint8, device=tensor.device)
155
+ data[..., 0::2] = tensor.bitwise_right_shift(4)
156
+ data[..., 1::2] = tensor.bitwise_and(0xF)
157
+
158
+ return data
159
+
160
+
161
+ def get_AsyncPartitionedParameterSwapper(model: nn.Module):
162
+ for param_name, param in model.named_parameters():
163
+ if hasattr(param, 'nvme_swapper') and param.nvme_swapper is not None:
164
+ return param.nvme_swapper
165
+ return None
166
+
167
+
168
+ def recursive_setattr(model, module_name, module):
169
+ """
170
+ Recursively set the attribute of a module.
171
+ Args:
172
+ model (`torch.nn.Module`)
173
+ The model to set the attribute in.
174
+ module_name (`str`)
175
+ The name of the module to set the attribute in.
176
+ module (`torch.nn.Module`)
177
+ The module to set the attribute to.
178
+ """
179
+ split_list = module_name.split('.')
180
+ output = model
181
+ for name in split_list[:-1]:
182
+ output = getattr(output, name)
183
+ output.__setattr__(split_list[-1], module)
184
+
185
+
186
+ def concat_to_compat_param(quantized_weight: Tensor,
187
+ quant_scale: Tensor,
188
+ quant_min: Tensor,
189
+ return_param: bool = True) -> Union[nn.Parameter, Tensor]:
190
+ shape_wieght = quantized_weight.shape
191
+ shape_scale = quant_scale.shape
192
+ shape_min = quant_min.shape
193
+
194
+ quantized_weight = torch.flatten(quantized_weight)
195
+ quant_scale = torch.flatten(quant_scale)
196
+ quant_min = torch.flatten(quant_min)
197
+
198
+ def deconcat_individual_tensors(shape_wieght: torch.Size, shape_scale: torch.Size,
199
+ shape_min: torch.Size) -> Callable:
200
+
201
+ def fn(compat_tensor: nn.Parameter) -> Tuple[Tensor, Tensor, Tensor]:
202
+ weight = torch.narrow(compat_tensor, 0, 0, shape_wieght.numel()).view(shape_wieght)
203
+ scale = torch.narrow(compat_tensor, 0, shape_wieght.numel(), shape_scale.numel()).view(shape_scale)
204
+ min_val = torch.narrow(compat_tensor, 0,
205
+ shape_wieght.numel() + shape_scale.numel(), shape_min.numel()).view(shape_min)
206
+
207
+ return weight, scale, min_val
208
+
209
+ return fn
210
+
211
+ compat_tensor = torch.concat([quantized_weight, quant_scale, quant_min])
212
+ if return_param:
213
+ compat_tensor = nn.Parameter(compat_tensor, requires_grad=False)
214
+ compat_tensor.deconcat = deconcat_individual_tensors(shape_wieght, shape_scale, shape_min)
215
+
216
+ return compat_tensor
217
+
218
+
219
+ def _quantize_param(param: nn.Parameter, quant_config: Dict):
220
+ assert not hasattr(param, 'weight_quantized'), 'Parameter has already been quantized.'
221
+ quantizer = Quantizer(quant_config)
222
+ dequantizer = DeQuantizer(quant_config, param.dtype)
223
+
224
+ quantized_weight, quant_scale, quant_min = quantizer.quantize(param.data)
225
+
226
+ quantized_weight = quantized_weight.view(param.dtype)
227
+ quant_scale = quant_scale.view(param.dtype)
228
+ quant_min = quant_min.view(param.dtype)
229
+
230
+ quantized_compat_tensor = concat_to_compat_param(quantized_weight, quant_scale, quant_min)
231
+ param.data = quantized_compat_tensor
232
+ param.deconcat = quantized_compat_tensor.deconcat
233
+
234
+ param.quantizer = quantizer
235
+ param.dequantizer = dequantizer
236
+ setattr(param, 'weight_quantized', True)
237
+
238
+
239
+ def wrap_quantized_functional(f):
240
+
241
+ @functools.wraps(f)
242
+ def wrapper(input: Tensor, weight: nn.Parameter, *args, **kwargs) -> Tensor:
243
+ if hasattr(weight, 'weight_quantized') and getattr(weight, 'weight_quantized'):
244
+ quantized_weight, quant_scale, quant_min = weight.deconcat(weight)
245
+ temp_dequantized_weight = weight.dequantizer.dequantize(quantized_weight.view(torch.uint8), quant_scale,
246
+ quant_min)
247
+ return f(input, temp_dequantized_weight, *args, **kwargs)
248
+ else:
249
+ return f(input, weight, *args, **kwargs)
250
+
251
+ return wrapper
252
+
253
+
254
+ def wrap_load_from_state_dict(f):
255
+
256
+ @functools.wraps(f)
257
+ def wrapper(model, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
258
+ replaced_old_value = None
259
+ key = None
260
+ # We may have nested wrappers if we launch multiple initialization context.
261
+ # Use state_dict_quantized flag to quantize state_dict only once
262
+ if hasattr(model.weight, 'weight_quantized') and getattr(
263
+ model.weight, 'weight_quantized') and not hasattr(model.weight, 'state_dict_quantized'):
264
+ setattr(model.weight, 'state_dict_quantized', True)
265
+ key = prefix + 'weight'
266
+ if key in state_dict:
267
+ quantized_weight, quant_scale, quant_min = model.weight.quantizer.quantize(state_dict[key])
268
+ quantized_weight = quantized_weight.view(model.weight.dtype)
269
+ quant_scale = quant_scale.view(model.weight.dtype)
270
+ quant_min = quant_min.view(model.weight.dtype)
271
+
272
+ replaced_old_value = state_dict[key]
273
+
274
+ state_dict[key] = concat_to_compat_param(quantized_weight, quant_scale, quant_min)
275
+
276
+ f(model, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
277
+
278
+ if replaced_old_value is not None:
279
+ state_dict[key] = replaced_old_value
280
+ delattr(model.weight, 'state_dict_quantized')
281
+
282
+ return wrapper
283
+
284
+
285
+ WEIGHT_QUANTIZATION_LAYERS = (
286
+ nn.Linear,
287
+ nn.Embedding,
288
+ )
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+ from .config_v2 import RaggedInferenceEngineConfig, DeepSpeedTPConfig
6
+ from .engine_v2 import InferenceEngineV2
7
+ from .engine_factory import build_hf_engine, build_engine_from_ds_checkpoint
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (426 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/allocator.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/config_v2.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/engine_factory.cpython-310.pyc ADDED
Binary file (4.05 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/engine_v2.cpython-310.pyc ADDED
Binary file (8.93 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/inference_parameter.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/inference_utils.cpython-310.pyc ADDED
Binary file (2.87 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/logging.cpython-310.pyc ADDED
Binary file (889 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/__pycache__/scheduling_utils.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/allocator.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from functools import reduce
7
+ from typing import Iterable
8
+ from collections import defaultdict
9
+ import torch
10
+
11
+ from deepspeed.accelerator import get_accelerator
12
+
13
+
14
+ class Allocator:
15
+ cache = defaultdict(dict)
16
+
17
+ def empty_from(tensor: torch.Tensor, shape: Iterable[int]) -> torch.Tensor:
18
+ try:
19
+ return Allocator.cache[tensor][shape]
20
+ except KeyError:
21
+ shape_size = reduce(lambda x, y: x * y, shape)
22
+ if shape_size == 0:
23
+ raise ValueError("Cannot create empty tensor with size 0")
24
+ Allocator.cache[tensor][shape] = tensor.flatten()[:shape_size].view(shape)
25
+ return Allocator.cache[tensor][shape]
26
+
27
+
28
+ empty_from = Allocator.empty_from
29
+
30
+
31
+ def on_device(method) -> torch.Tensor:
32
+ """
33
+ Wraps a method to ensure the returned tensor is on the current device.
34
+ """
35
+
36
+ def wrapped(self, *args, **kwargs):
37
+ tensor = method(self, *args, **kwargs)
38
+ if isinstance(tensor, torch.Tensor):
39
+ return tensor.to(get_accelerator().current_device())
40
+ return tensor
41
+
42
+ return wrapped
venv/lib/python3.10/site-packages/deepspeed/inference/v2/config_v2.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from typing import Optional
7
+ from deepspeed.pydantic_v1 import Field
8
+ from deepspeed.runtime.config_utils import DeepSpeedConfigModel
9
+ from .ragged import DSStateManagerConfig
10
+
11
+
12
+ class DeepSpeedTPConfig(DeepSpeedConfigModel):
13
+ """ Configure tensor parallelism settings """
14
+
15
+ tp_size: int = 1
16
+ """ Number of devices to split the model across using tensor parallelism. """
17
+
18
+
19
+ class QuantizationConfig(DeepSpeedConfigModel):
20
+ """ Configure tensor parallelism settings """
21
+
22
+ quantization_mode: Optional[str] = None
23
+ """ The quantization mode in string format. The supported modes are as follows:
24
+ - 'wf6af16', weight-only quantization with FP6 weight and FP16 activation.
25
+ """
26
+ # TODO: may reuse the constants in deepspeed/compression/constants.py
27
+
28
+
29
+ class RaggedInferenceEngineConfig(DeepSpeedConfigModel):
30
+ """ Sets parameters for DeepSpeed Inference Engine. """
31
+
32
+ tensor_parallel: DeepSpeedTPConfig = Field({}, alias="tp")
33
+ """
34
+ Configuration for tensor parallelism used to split the model across several
35
+ GPUs. Expects a dictionary containing values for :any:`DeepSpeedTPConfig`.
36
+ """
37
+
38
+ state_manager: DSStateManagerConfig = Field({}, alias="manager")
39
+ """
40
+ Configuration for managing persistent state
41
+ """
42
+
43
+ quantization: QuantizationConfig = {}
venv/lib/python3.10/site-packages/deepspeed/inference/v2/engine_factory.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import json
7
+ import logging
8
+ import os
9
+ import pickle
10
+ from packaging import version
11
+
12
+ from .engine_v2 import InferenceEngineV2
13
+ from .config_v2 import RaggedInferenceEngineConfig
14
+ from .checkpoint import HuggingFaceCheckpointEngine
15
+ from .logging import inference_logger
16
+ from .model_implementations import (
17
+ OPTPolicy,
18
+ Llama2Policy,
19
+ MistralPolicy,
20
+ MixtralPolicy,
21
+ FalconPolicy,
22
+ PhiPolicy,
23
+ QwenPolicy,
24
+ Qwen2Policy,
25
+ )
26
+ from .model_implementations.inference_policy_base import POLICIES, InferenceV2Policy
27
+ from .model_implementations.flat_model_helpers import make_metadata_filename, ModelMetadata
28
+
29
+
30
+ def build_engine_from_ds_checkpoint(path: str,
31
+ engine_config: RaggedInferenceEngineConfig,
32
+ debug_level: int = logging.INFO) -> InferenceEngineV2:
33
+ """
34
+ Creates an engine from a checkpoint saved by ``InferenceEngineV2``.
35
+
36
+ Arguments:
37
+ path: Path to the checkpoint. This does not need to point to any files in particular,
38
+ just the directory containing the checkpoint.
39
+ engine_config: Engine configuration. See ``RaggedInferenceEngineConfig`` for details.
40
+ debug_level: Logging level to use. Unless you are actively seeing issues, the recommended
41
+ value is ``logging.INFO``.
42
+
43
+ Returns:
44
+ Fully initialized inference engine ready to serve queries.
45
+ """
46
+
47
+ inference_logger(level=debug_level)
48
+ # Load metadata, for grabbing the policy name we'll have all ranks just check for
49
+ # rank 0.
50
+ metadata_filename = make_metadata_filename(path, 0, engine_config.tensor_parallel.tp_size)
51
+ metadata = json.load(open(metadata_filename, "r"))
52
+ metadata = ModelMetadata.parse_raw(metadata)
53
+
54
+ # Get the policy
55
+ try:
56
+ policy_cls: InferenceV2Policy = POLICIES[metadata.policy]
57
+ except KeyError:
58
+ raise ValueError(f"Unknown policy {metadata.policy} for model {path}")
59
+
60
+ # Load the model config
61
+ model_config = pickle.load(open(os.path.join(path, "ds_model_config.pkl"), "rb"))
62
+ policy = policy_cls(model_config, inf_checkpoint_path=path)
63
+
64
+ return InferenceEngineV2(policy, engine_config)
65
+
66
+
67
+ def build_hf_engine(path: str,
68
+ engine_config: RaggedInferenceEngineConfig,
69
+ debug_level: int = logging.INFO) -> InferenceEngineV2:
70
+ """
71
+ Build an InferenceV2 engine for HuggingFace models. This can accept both a HuggingFace
72
+ model name or a path to an Inference-V2 checkpoint.
73
+
74
+ Arguments:
75
+ path: Path to the checkpoint. This does not need to point to any files in particular,
76
+ just the directory containing the checkpoint.
77
+ engine_config: Engine configuration. See ``RaggedInferenceEngineConfig`` for details.
78
+ debug_level: Logging level to use. Unless you are actively seeing issues, the recommended
79
+ value is ``logging.INFO``.
80
+
81
+ Returns:
82
+ Fully initialized inference engine ready to serve queries.
83
+ """
84
+
85
+ if os.path.exists(os.path.join(path, "ds_model_config.pkl")):
86
+ return build_engine_from_ds_checkpoint(path, engine_config, debug_level=debug_level)
87
+ else:
88
+ # Set up logging
89
+ inference_logger(level=debug_level)
90
+ # get HF checkpoint engine
91
+ checkpoint_engine = HuggingFaceCheckpointEngine(path)
92
+
93
+ # get model config from HF AutoConfig
94
+ model_config = checkpoint_engine.model_config
95
+
96
+ # get the policy
97
+ # TODO: generalize this to other models
98
+ if model_config.model_type == "opt":
99
+ if not model_config.do_layer_norm_before:
100
+ raise ValueError(
101
+ "Detected OPT-350m model. This model is not currently supported. If this is not the 350m model, please open an issue: https://github.com/microsoft/DeepSpeed-MII/issues"
102
+ )
103
+ policy = OPTPolicy(model_config, checkpoint_engine=checkpoint_engine)
104
+ elif model_config.model_type == "llama":
105
+ policy = Llama2Policy(model_config, checkpoint_engine=checkpoint_engine)
106
+ elif model_config.model_type == "mistral":
107
+ # Ensure we're using the correct version of transformers for mistral
108
+ import transformers
109
+ assert version.parse(transformers.__version__) >= version.parse("4.34.0"), \
110
+ f"Mistral requires transformers >= 4.34.0, you have version {transformers.__version__}"
111
+ policy = MistralPolicy(model_config, checkpoint_engine=checkpoint_engine)
112
+ elif model_config.model_type == "mixtral":
113
+ # Ensure we're using the correct version of transformers for mistral
114
+ import transformers
115
+ assert version.parse(transformers.__version__) >= version.parse("4.36.1"), \
116
+ f"Mistral requires transformers >= 4.36.1, you have version {transformers.__version__}"
117
+ policy = MixtralPolicy(model_config, checkpoint_engine=checkpoint_engine)
118
+ elif model_config.model_type == "falcon":
119
+ policy = FalconPolicy(model_config, checkpoint_engine=checkpoint_engine)
120
+ elif model_config.model_type == "phi":
121
+ policy = PhiPolicy(model_config, checkpoint_engine=checkpoint_engine)
122
+ elif model_config.model_type == "qwen":
123
+ policy = QwenPolicy(model_config, checkpoint_engine=checkpoint_engine)
124
+ elif model_config.model_type == "qwen2":
125
+ policy = Qwen2Policy(model_config, checkpoint_engine=checkpoint_engine)
126
+ else:
127
+ raise ValueError(f"Unsupported model type {model_config.model_type}")
128
+
129
+ return InferenceEngineV2(policy, engine_config)
venv/lib/python3.10/site-packages/deepspeed/inference/v2/engine_v2.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import os
7
+ import json
8
+ import pickle
9
+ from typing import Iterable, Tuple
10
+
11
+ import torch
12
+
13
+ import deepspeed.comm as dist
14
+
15
+ from deepspeed.accelerator import get_accelerator
16
+ from deepspeed.comm.comm import init_distributed
17
+
18
+ from .model_implementations import InferenceV2Policy
19
+ from .logging import inference_logger
20
+ from .ragged import DSStateManager, RaggedBatchWrapper, PlaceholderSequenceDescriptor
21
+ from .scheduling_utils import SchedulingError, SchedulingResult
22
+ from .model_implementations.flat_model_helpers import make_param_filename, make_metadata_filename
23
+ from .model_implementations.inference_model_base import DSInferenceModelBase
24
+
25
+ from .config_v2 import RaggedInferenceEngineConfig
26
+
27
+ INFERENCE_MODEL_TIMER = "model-forward-inference"
28
+
29
+
30
+ class InferenceEngineV2:
31
+
32
+ _config: RaggedInferenceEngineConfig
33
+ """
34
+ Configuration of the inference engine.
35
+ """
36
+
37
+ _model: DSInferenceModelBase
38
+ """
39
+ Inference model supporting ragged inference.
40
+ """
41
+
42
+ _state_manager: DSStateManager
43
+ """
44
+ Persistent state manager for sequences and KV-cache.
45
+ """
46
+
47
+ @property
48
+ def free_blocks(self) -> torch.Tensor:
49
+ """
50
+ Number of free KV blocks. This is a tensor of shape [n_kv_cache_groups] where each
51
+ element is the number of free blocks in the corresponding KV cache group.
52
+ """
53
+ return self._state_manager.free_blocks
54
+
55
+ @property
56
+ def n_kv_cache_groups(self) -> int:
57
+ """
58
+ Number of KV cache groups.
59
+ """
60
+ return self._state_manager.n_kv_cache_groups
61
+
62
+ def model(self) -> DSInferenceModelBase:
63
+ """
64
+ The model implementation.
65
+ """
66
+ return self._model
67
+
68
+ def __init__(self, policy: InferenceV2Policy, engine_config: RaggedInferenceEngineConfig) -> None:
69
+ """
70
+ Create the Inference V2 engine.
71
+
72
+ Arguments:
73
+ policy (InferenceV2Policy): Policy for the model implementation. This policy object
74
+ will be used to build the model and load the checkpoint associated with it.
75
+ engine_config (RaggedInferenceEngineConfig): Configuration for the inference engine.
76
+ """
77
+ self._config = engine_config
78
+ self._policy = policy
79
+ self._base_mp_group = self._initialize_tp_group()
80
+
81
+ # Build model from policy
82
+ inference_logger().info("Building model...")
83
+ self._model = self._policy.build_model(self._config, self._base_mp_group)
84
+ inference_logger().info("Model built.")
85
+
86
+ # Create state manager
87
+ self._batch = RaggedBatchWrapper(self._config.state_manager)
88
+ self._state_manager = DSStateManager(self._config.state_manager,
89
+ self._model.kv_cache_config(),
90
+ base_mp_group=self._base_mp_group)
91
+ self._model.set_state_manager(self._state_manager)
92
+
93
+ def _initialize_tp_group(self):
94
+ """
95
+ Implementation of our TP group initialization.
96
+ """
97
+ init_distributed()
98
+ local_rank = int(os.getenv("LOCAL_RANK", 0))
99
+ get_accelerator().set_device(local_rank)
100
+
101
+ if local_rank >= self._config.tensor_parallel.tp_size:
102
+ raise RuntimeError("Local rank is greater than TP size, ensure that the TP config is correct.")
103
+
104
+ ranks = list(range(self._config.tensor_parallel.tp_size))
105
+ return dist.new_group(ranks=ranks)
106
+
107
+ def put(self,
108
+ batch_uids: Iterable[int],
109
+ batch_tokens: Iterable[torch.Tensor],
110
+ do_checks: bool = True) -> torch.Tensor:
111
+ """
112
+ Put a ragged batch onto the inference engine. This will perform one forward and return
113
+ a Tensor of the shape [len(batch_uids), *output_shape]. Logits for the non-final tokens
114
+ are not calculated.
115
+
116
+ Arguments:
117
+ batch_uids: Iterable of uids for the batch on the host
118
+ batch_tokens: Iterable of token tensors for the batch on the host
119
+ do_checks: Check schedulability when it is set to True. You can skip this check for better performance when it has already been completed.
120
+ """
121
+
122
+ if do_checks:
123
+ token_lens = [len(tokens) for tokens in batch_tokens]
124
+ schedule_check = self.can_schedule(batch_uids, token_lens)
125
+ if schedule_check != SchedulingResult.Success:
126
+ raise SchedulingError(schedule_check)
127
+
128
+ self._batch.clear()
129
+ for uid, tokens in zip(batch_uids, batch_tokens):
130
+
131
+ host_seq_desc = self._state_manager.get_or_create_sequence(uid)
132
+ self._model.maybe_allocate_kv(host_seq_desc, tokens.numel())
133
+ host_seq_desc.pre_forward(tokens.numel())
134
+
135
+ # We can disable checks since we already validated schedulability.
136
+ self._batch.insert_sequence(host_seq_desc, tokens, do_checks=do_checks)
137
+
138
+ # Send all metadata to the device
139
+ self._batch.finalize()
140
+
141
+ # Prep all data structures for the actual forward (in anticipation of CG in the future)
142
+ # and also to amortize some of the costs in a more straightforward way.
143
+ self._model.prepare_batch(self._batch)
144
+
145
+ # Model implementation will pick up in the forward.
146
+ logits = self._model.forward(self._batch)
147
+
148
+ # We return one set of logits per sequence in the batch (saves cost on unembedding)
149
+ assert logits.shape[0] == self._batch.current_sequences
150
+
151
+ for uid in batch_uids:
152
+ host_seq_desc = self._state_manager.get_sequence(uid)
153
+ host_seq_desc.post_forward() # Updates sequence metadata.
154
+ self._model.maybe_free_kv(host_seq_desc)
155
+
156
+ return logits
157
+
158
+ def query(self, uid: int, max_request_tokens: int, max_request_blocks) -> Tuple[int, torch.Tensor]:
159
+ """
160
+ Determine the number of tokens and KV blocks to reserve for a given request. Given a UID
161
+ (this UID may not be recognized by the model yet), this will return the number of tokens
162
+ and blocks to reserve for the request.
163
+
164
+ Arguments:
165
+ uid (int): The UID of the sequence (as tracked by the scheduling entity). If
166
+ this is a new sequence (with a UID unknown to the inference engine), then
167
+ an empty placeholder is created to pass to the occupancy logic.
168
+ n_tokens (int): The number of tokens to hypothetically send.
169
+
170
+ Returns:
171
+ Tuple[int, Optional[int]]: Tuple of free kv blocks and the number of blocks
172
+ required to schedule the sequence.
173
+ """
174
+ seq_desc = self._state_manager.get_sequence(uid)
175
+ if seq_desc is None:
176
+ if (self._state_manager.n_tracked_sequences == self._config.state_manager.max_tracked_sequences):
177
+ return (0, 0)
178
+ seq_desc = PlaceholderSequenceDescriptor()
179
+
180
+ req_tokens, req_blocks = self._model.get_kv_requirements(seq_desc, max_request_tokens, max_request_blocks)
181
+
182
+ return (req_tokens, req_blocks)
183
+
184
+ def can_schedule(self, uids: Iterable[int], lengths: Iterable[int]) -> SchedulingResult:
185
+ """
186
+ Dry run a batch to determine if it can be scheduled. Placeholder sequences will be
187
+ created for any UIDs that are unknown to the inference engine.
188
+
189
+ Arguments:
190
+ uids (Iterable[int]): Iterable of UIDs for the batch
191
+ lengths (Iterable[int]): Iterable of lengths for each sequence of the batch. This lengths
192
+ corresponds to the number of tokens to send in the hypothetical forward; history
193
+ tokens will be determined via UID lookup and future tokens are disregarded.
194
+
195
+ Returns:
196
+ bool: True if the batch can be scheduled, False otherwise.
197
+ """
198
+
199
+ cur_seqs = self._state_manager.n_tracked_sequences
200
+ free_blocks = self._state_manager.free_blocks
201
+ req_blocks = 0
202
+ batch_len = 0
203
+
204
+ if len(uids) > self._config.state_manager.max_ragged_sequence_count:
205
+ # Can only compose a batch from a limited number of sequences
206
+ return SchedulingResult.BatchSequenceLimitExceeded
207
+
208
+ for uid, length in zip(uids, lengths):
209
+ seq_desc = self._state_manager.get_sequence(uid)
210
+ if seq_desc is None:
211
+ cur_seqs += 1
212
+ seq_desc = PlaceholderSequenceDescriptor()
213
+
214
+ sched_len, sched_blocks = self._model.get_kv_requirements(seq_desc, length, free_blocks)
215
+
216
+ if sched_len != length:
217
+ # We ran out of KV cache
218
+ return SchedulingResult.KVCacheLimitExceeded
219
+
220
+ batch_len += length
221
+ free_blocks -= sched_blocks
222
+
223
+ if cur_seqs > self._config.state_manager.max_tracked_sequences:
224
+ # Would run out of tracking metadata
225
+ return SchedulingResult.EngineSequenceLimitExceeded
226
+
227
+ if batch_len > self._config.state_manager.max_ragged_batch_size:
228
+ # Would exceed the maximum batch size
229
+ return SchedulingResult.BatchTokenLimitExceeded
230
+
231
+ return SchedulingResult.Success
232
+
233
+ def get_remaining_block_capacity(self, uid: int) -> int:
234
+ """
235
+ Get the remaining capacity of the last block already allocated.
236
+ """
237
+ seq_desc = self._state_manager.get_sequence(uid)
238
+ if seq_desc is None:
239
+ return 0
240
+ return self._model.get_remaining_block_capacity(seq_desc)
241
+
242
+ def flush(self, uid: int) -> None:
243
+ """
244
+ Remove all state associated with a sequence from the inference engine.
245
+
246
+ Arguments:
247
+ uid (int): The UID of the sequence to flush.
248
+ """
249
+ self._state_manager.flush_sequence(uid)
250
+
251
+ def serialize(self, save_path: str) -> None:
252
+ """
253
+ Serialize the model to a file.
254
+
255
+ Arguments:
256
+ path (str): Path to the file to serialize to.
257
+ """
258
+ param_file_name = make_param_filename(save_path, self._model.tp_rank, self._model.tp_size)
259
+ metadata_file_name = make_metadata_filename(save_path, self._model.tp_rank, self._model.tp_size)
260
+
261
+ # Save the flattened parameters
262
+
263
+ torch.save(self._model.flattened_params, param_file_name)
264
+
265
+ json.dump(self._model.flattened_param_metadata.json(), open(metadata_file_name, "w"))
266
+
267
+ if self._model.tp_rank == 0:
268
+ pickle.dump(self._model._config, open(os.path.join(save_path, "ds_model_config.pkl"), "wb"))
venv/lib/python3.10/site-packages/deepspeed/inference/v2/inference_parameter.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from typing import Dict
7
+
8
+ import torch
9
+
10
+ CORE_PARAM = "_ds_core_param_key"
11
+
12
+ STR_TO_DTYPE = {
13
+ "torch.float32": torch.float32,
14
+ "torch.float64": torch.float64,
15
+ "torch.float16": torch.float16,
16
+ "torch.bfloat16": torch.bfloat16,
17
+ "torch.int64": torch.int64,
18
+ "torch.int32": torch.int32,
19
+ "torch.int16": torch.int16,
20
+ "torch.int8": torch.int8,
21
+ "torch.uint8": torch.uint8,
22
+ "torch.bool": torch.bool,
23
+ }
24
+
25
+
26
+ class InferenceParameter(torch.Tensor):
27
+ """
28
+ An extension of the torch.Tensor class to support our inference focused features. One important
29
+ thing to note here is that an InferenceParam can be used a torch.Tensor, but outputs of
30
+ torch.Tensor operations will not be InferenceParams.
31
+ """
32
+
33
+ @staticmethod
34
+ def __new__(cls, tensor, *args, **kwargs):
35
+ new_tensor = super().__new__(cls, tensor, *args, **kwargs)
36
+ if hasattr(tensor, "_aux_attrs"):
37
+ setattr(new_tensor, "_aux_attrs", tensor.aux_attrs)
38
+ return new_tensor
39
+
40
+ def to(self, *args, **kwargs):
41
+ new_tensor = super().to(*args, **kwargs)
42
+ if hasattr(self, "_aux_attrs"):
43
+ setattr(new_tensor, "_aux_attrs", self.aux_attrs)
44
+ try:
45
+ _ = torch.device(args[0])
46
+ for name, attr in new_tensor.aux_attrs.items():
47
+ new_attr = attr.to(*args, **kwargs)
48
+ setattr(new_tensor, name, new_attr)
49
+ new_tensor.aux_attrs[name] = new_attr
50
+ except:
51
+ pass
52
+
53
+ return new_tensor
54
+
55
+ @classmethod
56
+ def initialize(cls, core_param: torch.Tensor, **kwargs) -> 'InferenceParameter':
57
+ """
58
+ Create the inference parameter.
59
+ """
60
+ param = InferenceParameter(core_param)
61
+ setattr(param, "_aux_attrs", kwargs)
62
+
63
+ for attr_name, attr in kwargs.items():
64
+ if hasattr(param, attr_name):
65
+ raise ValueError(f"Attribute {attr_name} already exists on param.")
66
+
67
+ if not isinstance(attr, torch.Tensor):
68
+ raise ValueError(f"Attribute {attr_name} must be a tensor.")
69
+
70
+ setattr(param, attr_name, attr)
71
+
72
+ return param
73
+
74
+ @classmethod
75
+ def initialize_raw(self, **kwargs) -> 'InferenceParameter':
76
+ """
77
+ All kwargs must be torch.Tensors and must include the core parameter.
78
+ """
79
+ if CORE_PARAM not in kwargs:
80
+ raise ValueError(f"Must provide core parameter, with key {CORE_PARAM}.")
81
+
82
+ return InferenceParameter.initialize(kwargs[CORE_PARAM], **kwargs)
83
+
84
+ @property
85
+ def aux_attrs(self) -> Dict[str, torch.Tensor]:
86
+ """
87
+ Dictionary of auxiliary attributes.
88
+ """
89
+ return self._aux_attrs
venv/lib/python3.10/site-packages/deepspeed/inference/v2/inference_utils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from typing import Dict
7
+
8
+ import torch
9
+
10
+ from enum import Enum, IntEnum
11
+
12
+
13
+ class NormTypeEnum(Enum):
14
+ LayerNorm: str = "layer_norm"
15
+ RMSNorm: str = "rms_norm"
16
+
17
+
18
+ class DtypeEnum(Enum):
19
+ # The torch dtype must always be the first value (so we return torch.dtype)
20
+ fp16 = torch.float16, "torch.float16", "fp16", "float16", "half"
21
+ fp32 = torch.float32, "torch.float32", "fp32", "float32", "float"
22
+ bf16 = torch.bfloat16, "torch.bfloat16", "bf16", "bfloat16", "bfloat"
23
+ int8 = torch.int8, "torch.int8", "int8"
24
+
25
+ # Copied from https://stackoverflow.com/a/43210118
26
+ # Allows us to use multiple values for each Enum index and returns first
27
+ # listed value when Enum is called
28
+ def __new__(cls, *values):
29
+ obj = object.__new__(cls)
30
+ # first value is canonical value
31
+ obj._value_ = values[0]
32
+ for other_value in values[1:]:
33
+ cls._value2member_map_[other_value] = obj
34
+ obj._all_values = values
35
+ return obj
36
+
37
+ def __repr__(self):
38
+ return "<%s.%s: %s>" % (
39
+ self.__class__.__name__,
40
+ self._name_,
41
+ ", ".join([repr(v) for v in self._all_values]),
42
+ )
43
+
44
+
45
+ ELEM_SIZES: Dict[torch.dtype, int] = {
46
+ torch.float16: 2,
47
+ torch.bfloat16: 2,
48
+ torch.float32: 4,
49
+ torch.float64: 8,
50
+ torch.int8: 1,
51
+ torch.uint8: 1,
52
+ torch.int16: 2,
53
+ torch.int32: 4,
54
+ torch.int64: 8,
55
+ torch.bool: 1,
56
+ }
57
+
58
+
59
+ class ActivationType(IntEnum):
60
+ """
61
+ Types of activations supported by DS-Inference
62
+ """
63
+
64
+ GELU = 0
65
+
66
+ RELU = 1
67
+
68
+ SILU = 2
69
+
70
+ GEGLU = 3
71
+
72
+ ReGLU = 4
73
+
74
+ SiGLU = 5
75
+
76
+ IDENTITY = 6
77
+
78
+ InvalidType = -1
79
+
80
+
81
+ def is_gated(act_fn: ActivationType) -> bool:
82
+ """
83
+ Return True if the given activation function is gated.
84
+ """
85
+ if not isinstance(act_fn, ActivationType):
86
+ act_fn = ActivationType(act_fn)
87
+
88
+ return act_fn in [ActivationType.GEGLU, ActivationType.ReGLU, ActivationType.SiGLU]
89
+
90
+
91
+ def elem_size(dtype: torch.dtype) -> int:
92
+ """
93
+ Return size in bytes of the given dtype.
94
+ """
95
+ try:
96
+ return ELEM_SIZES[dtype]
97
+ except KeyError:
98
+ raise ValueError("Unknown dtype size for {}".format(dtype))
99
+
100
+
101
+ def ceil_div(a: int, b: int) -> int:
102
+ """
103
+ Return ceil(a / b).
104
+ """
105
+ return -(-a // b)
venv/lib/python3.10/site-packages/deepspeed/inference/v2/logging.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ import logging
7
+
8
+ from deepspeed.utils.logging import LoggerFactory
9
+
10
+ inf_logger = None
11
+
12
+
13
+ def inference_logger(level: int = logging.INFO) -> logging.Logger:
14
+ """
15
+ Create the inference logger. NOTE: Logging is not cost free. On a 3960X,
16
+ there is a cost of about 6 us per call to a no-op logger, so this should
17
+ be used during setup only and not during the inference loop.
18
+
19
+ Args:
20
+ level (int, optional): The logging level. Defaults to logging.INFO.
21
+ """
22
+ global inf_logger
23
+ if inf_logger is None:
24
+ inf_logger = LoggerFactory.create_logger(name="DS-Inference", level=level)
25
+ inf_logger.debug("Inference logger created.")
26
+ return inf_logger
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from . import implementations
7
+ from . import interfaces
8
+ from .module_registry import ConfigBundle
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from .attention_configs import (
7
+ DSSelfAttentionConfig,
8
+ PositionalEmbeddingType,
9
+ MaskingType,
10
+ RotateHalfConfig,
11
+ )
12
+ from .embedding_config import DSEmbeddingsConfig
13
+ from .linear_config import DSLinearConfig
14
+ from .moe_config import DSMoEConfig
15
+ from .norm_config import DSNormConfig, NormTypeEnum
16
+ from .unembed_config import DSUnembedConfig
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/attention_configs.cpython-310.pyc ADDED
Binary file (1.93 kB). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/embedding_config.cpython-310.pyc ADDED
Binary file (914 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/linear_config.cpython-310.pyc ADDED
Binary file (778 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/__pycache__/norm_config.cpython-310.pyc ADDED
Binary file (790 Bytes). View file
 
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/attention_configs.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from enum import Enum
7
+ from typing import Dict, Optional
8
+
9
+ from ...inference_utils import DtypeEnum
10
+ from ...modules.ds_module import DSModuleConfig
11
+ from deepspeed.runtime.config_utils import DeepSpeedConfigModel
12
+
13
+
14
+ class PositionalEmbeddingType(Enum):
15
+
16
+ # No positional embeddings
17
+ none = "none"
18
+
19
+ # Rotary positional embeddings - every half
20
+ rotate_half = "rotate_half"
21
+
22
+ # Rotary positional embeddings - every other
23
+ rotate_every_other = "rotate_every_other"
24
+
25
+ # Alibi
26
+ alibi = "alibi"
27
+
28
+
29
+ class RotateHalfConfig(DeepSpeedConfigModel):
30
+
31
+ use_trained_freqs: bool = False
32
+ """
33
+ Whether to use a passed `trained_freqs` tensor for the attention implementation
34
+ or to use default synthesized frequencies.
35
+ """
36
+
37
+ theta_base: float = 10_000.0
38
+ """
39
+ Base for theta. This will only be used if `use_trained_freqs` is False.
40
+ """
41
+
42
+ rotate_dim: Optional[int] = None
43
+ """
44
+ How many neurons to rotate. If None, then all neurons will be rotated. Many external configs
45
+ will set this number to half the head dimension and then internally multiply by 2. To make it
46
+ more clear to understand what is happening (rotate_dim < head_dim -> then only partial rotation),
47
+ we do not do this multiplication internally.
48
+ """
49
+
50
+
51
+ class MaskingType(Enum):
52
+
53
+ # No masking
54
+ none = "none"
55
+
56
+ # Causal masking
57
+ causal = "causal"
58
+
59
+ # Local masking
60
+ local = "local"
61
+
62
+ # Symmetric masking (this is a 1D tensor mask)
63
+ symmetric = "symmetric"
64
+
65
+ # Arbitrary masking (this would correspond to a 2D tensor mask)
66
+ asymmetric = "asymmetric"
67
+
68
+
69
+ class DSSelfAttentionConfig(DSModuleConfig):
70
+ """
71
+ Config class for attention.
72
+ """
73
+
74
+ # Number of query attention heads on this shard
75
+ n_heads_q: int
76
+
77
+ # Number of KV attention heads on this shard
78
+ n_heads_kv: int
79
+
80
+ # Size of each attention head
81
+ head_size: int
82
+
83
+ # Max number of sequences that may compose a ragged batch
84
+ max_sequences: int
85
+
86
+ # Scale factor for attention scores
87
+ scale_factor: float = 1.0
88
+
89
+ # Input data type
90
+ input_dtype: DtypeEnum = DtypeEnum.fp16
91
+
92
+ # Output data type
93
+ output_dtype: DtypeEnum = DtypeEnum.fp16
94
+
95
+ # Masking type
96
+ masking_type: MaskingType = MaskingType.causal
97
+
98
+ # Masking args
99
+ masking_args: Dict = {}
100
+
101
+ # Positional embedding type
102
+ positional_embedding_type: PositionalEmbeddingType = PositionalEmbeddingType.none
103
+
104
+ # Positional embedding args
105
+ positional_embedding_config: Optional[RotateHalfConfig] = None
106
+ """
107
+ To extend this for the other positional embedding types, we would need to add
108
+ new configs for each type (as necessary) and annotate this with the
109
+ Union[RotateHalfConfig, OtherConfig, ...] type.
110
+ """
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/embedding_config.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from typing import Optional
7
+
8
+ from ...inference_utils import DtypeEnum, NormTypeEnum
9
+ from ...modules.ds_module import DSModuleConfig
10
+ """
11
+ Trying to define the space we need to support here right now:
12
+
13
+ Types of embeddings I've found so far:
14
+ 1. Token embedding
15
+ 2. Position embedding
16
+ 3. Token type embedding
17
+ 4. LN
18
+
19
+ GPTNeo: 1, 2, 3 (shared with 1)
20
+ GPTNeoX: 1
21
+ GPTJ: 1, 3
22
+ LLaMA: 1
23
+ BERT: 1, 2, 3, 4
24
+ GPT2: 1, 2, 3 (shared with 1)
25
+
26
+ Sidebar for OPT:
27
+ OPT: 1, 2
28
+ 1 may not actually project to the actual hidden dimension according to the raw
29
+ code, but for the model configs we care about it does.
30
+ 2 has a weird offset associated with it that the others do not.
31
+ """
32
+
33
+
34
+ class DSEmbeddingsConfig(DSModuleConfig):
35
+ """
36
+ Config class for DSEmbeddings.
37
+ """
38
+
39
+ residual_dtype: DtypeEnum = DtypeEnum.fp16
40
+ """
41
+ Data type the module should use for its output.
42
+ """
43
+
44
+ embedding_dim: int
45
+ """
46
+ Dimensionality of the embedding projections.
47
+ """
48
+
49
+ positional_embedding: bool = False
50
+ """
51
+ Whether the module should expect a positional embedding matrix. The shape of this
52
+ matrix should be of shape [max_seq_len + positional_offset, embedding_dim]
53
+ """
54
+
55
+ positional_offset: int = 0
56
+ """
57
+ Whether the linearized token IDs should be offset by a certain amount. For an example
58
+ of this, see the OPT model implementation.
59
+ """
60
+
61
+ use_token_type: bool = False
62
+ """
63
+ Whether the module should expect a token type embedding matrix.
64
+ """
65
+
66
+ output_normalization: Optional[NormTypeEnum] = None
67
+ """
68
+ If a the output of the embedding module should be normalized, specify here. See
69
+ ``inference.inference_utils.NormTypeEnum`` for supported values.
70
+ """
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/linear_config.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from ...inference_utils import ActivationType, DtypeEnum
7
+ from ...modules.ds_module import DSModuleConfig
8
+
9
+
10
+ class DSLinearConfig(DSModuleConfig):
11
+ """
12
+ Config class for DSLinearBase.
13
+ """
14
+
15
+ in_channels: int
16
+ """
17
+ Number of input channels
18
+ """
19
+
20
+ out_channels: int
21
+ """
22
+ Number of output channels. NOTE: If this linear layer is using a gated activation function,
23
+ the value for ``out_channels`` passed here should refer to the number of channels after
24
+ gating (i.e., the expected weight shape before transformations will be ``[out_channels * 2, in_channels]``).
25
+ """
26
+
27
+ activation: ActivationType = ActivationType.IDENTITY
28
+ """
29
+ The activation function for this layer. See :class:`deepspeed.inference.inference_utils.ActivationType` for
30
+ supported activation functions.
31
+ """
32
+
33
+ input_dtype: DtypeEnum = DtypeEnum.fp16
34
+ """
35
+ The data type of the input tensor. See :class:`deepspeed.inference.inference_utils.DtypeEnum` for supported
36
+ data types.
37
+ """
38
+
39
+ output_dtype: DtypeEnum = DtypeEnum.fp16
40
+ """
41
+ The data type of the output tensor. See :class:`deepspeed.inference.inference_utils.DtypeEnum` for supported
42
+ data types.
43
+ """
venv/lib/python3.10/site-packages/deepspeed/inference/v2/modules/configs/moe_config.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # DeepSpeed Team
5
+
6
+ from ...inference_utils import ActivationType, DtypeEnum
7
+ from ...modules.ds_module import DSModuleConfig
8
+
9
+
10
+ class DSMoEConfig(DSModuleConfig):
11
+ """
12
+ Config class for DSMoEBase
13
+ """
14
+
15
+ model_dim: int
16
+ """
17
+ Size of input activation.
18
+ """
19
+
20
+ intermediate_features: int
21
+ """
22
+ Size of intermediate activation. Specifically, this is the number of input features
23
+ in the second linear layer. Depending on the activation function, the output of the first
24
+ linear layer may have increased dimensionality.
25
+ """
26
+
27
+ n_experts: int
28
+ """
29
+ Number of experts.
30
+ """
31
+
32
+ top_k: int = 1
33
+ """
34
+ top-k gating function (like top-1 or top-2)
35
+ """
36
+
37
+ input_dtype: DtypeEnum = DtypeEnum.fp16
38
+ """
39
+ Data type for the input activations.
40
+ """
41
+
42
+ output_dtype: DtypeEnum = DtypeEnum.fp16
43
+ """
44
+ Data type for the output activations.
45
+ """
46
+
47
+ activation: ActivationType = ActivationType.IDENTITY
48
+ """
49
+ Activation function of the first MLP1
50
+ """
51
+
52
+ normalize_scores: bool = False
53
+ """
54
+ Whether normalization is applied to the selected scores. If true, the module
55
+ should rescale the scores such that their sum is 1.0.
56
+ """