sglang 0.1.14__py3-none-any.whl → 0.1.15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. sglang/__init__.py +55 -2
  2. sglang/api.py +3 -5
  3. sglang/backend/anthropic.py +18 -4
  4. sglang/backend/openai.py +2 -1
  5. sglang/backend/runtime_endpoint.py +18 -5
  6. sglang/backend/vertexai.py +1 -0
  7. sglang/global_config.py +1 -0
  8. sglang/lang/chat_template.py +74 -0
  9. sglang/lang/interpreter.py +40 -16
  10. sglang/lang/tracer.py +6 -4
  11. sglang/launch_server.py +2 -1
  12. sglang/srt/constrained/fsm_cache.py +1 -0
  13. sglang/srt/constrained/jump_forward.py +1 -0
  14. sglang/srt/conversation.py +2 -2
  15. sglang/srt/hf_transformers_utils.py +2 -1
  16. sglang/srt/layers/context_flashattention_nopad.py +1 -0
  17. sglang/srt/layers/extend_attention.py +1 -0
  18. sglang/srt/layers/logits_processor.py +114 -54
  19. sglang/srt/layers/radix_attention.py +2 -1
  20. sglang/srt/layers/token_attention.py +1 -0
  21. sglang/srt/managers/detokenizer_manager.py +5 -1
  22. sglang/srt/managers/io_struct.py +12 -0
  23. sglang/srt/managers/router/infer_batch.py +70 -33
  24. sglang/srt/managers/router/manager.py +7 -2
  25. sglang/srt/managers/router/model_rpc.py +116 -73
  26. sglang/srt/managers/router/model_runner.py +111 -167
  27. sglang/srt/managers/router/radix_cache.py +46 -38
  28. sglang/srt/managers/tokenizer_manager.py +56 -11
  29. sglang/srt/memory_pool.py +5 -14
  30. sglang/srt/model_config.py +7 -0
  31. sglang/srt/models/commandr.py +376 -0
  32. sglang/srt/models/dbrx.py +413 -0
  33. sglang/srt/models/dbrx_config.py +281 -0
  34. sglang/srt/models/gemma.py +22 -20
  35. sglang/srt/models/llama2.py +23 -21
  36. sglang/srt/models/llava.py +12 -10
  37. sglang/srt/models/mixtral.py +27 -25
  38. sglang/srt/models/qwen.py +23 -21
  39. sglang/srt/models/qwen2.py +23 -21
  40. sglang/srt/models/stablelm.py +20 -21
  41. sglang/srt/models/yivl.py +6 -5
  42. sglang/srt/openai_api_adapter.py +356 -0
  43. sglang/srt/{managers/openai_protocol.py → openai_protocol.py} +36 -20
  44. sglang/srt/sampling_params.py +2 -0
  45. sglang/srt/server.py +68 -447
  46. sglang/srt/server_args.py +76 -49
  47. sglang/srt/utils.py +88 -32
  48. sglang/srt/weight_utils.py +402 -0
  49. sglang/test/test_programs.py +8 -7
  50. sglang/test/test_utils.py +195 -7
  51. {sglang-0.1.14.dist-info → sglang-0.1.15.dist-info}/METADATA +12 -14
  52. sglang-0.1.15.dist-info/RECORD +69 -0
  53. sglang-0.1.14.dist-info/RECORD +0 -64
  54. {sglang-0.1.14.dist-info → sglang-0.1.15.dist-info}/LICENSE +0 -0
  55. {sglang-0.1.14.dist-info → sglang-0.1.15.dist-info}/WHEEL +0 -0
  56. {sglang-0.1.14.dist-info → sglang-0.1.15.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,413 @@
1
+ # Adapted from:
2
+ # https://github.com/vllm-project/vllm/blob/14ccd94c89d0ffd9da283545d93ab1dfea5da340/vllm/model_executor/models/dbrx.py
3
+ # coding=utf-8
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from vllm.model_executor.layers.fused_moe import fused_moe
9
+ from vllm.model_executor.layers.linear import (
10
+ QKVParallelLinear,
11
+ ReplicatedLinear,
12
+ RowParallelLinear,
13
+ )
14
+ from vllm.model_executor.layers.quantization.base_config import (
15
+ QuantizationConfig)
16
+ from vllm.model_executor.layers.rotary_embedding import get_rope
17
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
18
+ DEFAULT_VOCAB_PADDING_SIZE,
19
+ ParallelLMHead,
20
+ VocabParallelEmbedding,
21
+ )
22
+ from vllm.distributed import (
23
+ tensor_model_parallel_all_reduce,
24
+ )
25
+ from vllm.distributed import (
26
+ get_tensor_model_parallel_rank,
27
+ get_tensor_model_parallel_world_size,
28
+ )
29
+ from vllm.model_executor.utils import set_weight_attrs
30
+ from sglang.srt.weight_utils import (
31
+ default_weight_loader,
32
+ hf_model_weights_iterator,
33
+ )
34
+
35
+ from sglang.srt.layers.logits_processor import LogitsProcessor
36
+ from sglang.srt.layers.radix_attention import RadixAttention
37
+ from sglang.srt.managers.router.model_runner import InputMetadata
38
+ from sglang.srt.models.dbrx_config import DbrxConfig
39
+
40
+
41
+ class DbrxRouter(nn.Module):
42
+ """A Router implementation for DBRX that returns logits for each expert
43
+ per token.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ config: DbrxConfig,
49
+ params_dtype: Optional[torch.dtype] = None,
50
+ ):
51
+ super().__init__()
52
+ self.tp_size = get_tensor_model_parallel_world_size()
53
+ self.num_total_experts = config.ffn_config.moe_num_experts
54
+ self.d_model = config.d_model
55
+ self.layer = ReplicatedLinear(
56
+ self.d_model,
57
+ self.num_total_experts,
58
+ bias=False,
59
+ params_dtype=params_dtype,
60
+ quant_config=None,
61
+ )
62
+
63
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
64
+ router_logits, _ = self.layer(hidden_states)
65
+ return router_logits
66
+
67
+
68
+ class DbrxExperts(nn.Module):
69
+ """A tensor-parallel MoE implementation for DBRX.
70
+
71
+ Each expert's weights are sharded across all ranks and a fused MoE
72
+ kernel is used for the forward pass, and finally we reduce the outputs
73
+ across ranks.
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ config: DbrxConfig,
79
+ quant_config: Optional[QuantizationConfig] = None,
80
+ params_dtype: Optional[torch.dtype] = None,
81
+ ):
82
+ super().__init__()
83
+ self.tp_size = get_tensor_model_parallel_world_size()
84
+ self.num_total_experts = config.ffn_config.moe_num_experts
85
+ self.top_k = config.ffn_config.moe_top_k
86
+ self.d_model = config.d_model
87
+ self.intermediate_size = config.ffn_config.ffn_hidden_size // self.tp_size
88
+
89
+ if params_dtype is None:
90
+ params_dtype = torch.get_default_dtype()
91
+ self.params_dtype = params_dtype
92
+
93
+ self.router = DbrxRouter(config, self.params_dtype)
94
+ self.ws = nn.Parameter(
95
+ torch.empty(
96
+ self.num_total_experts,
97
+ 2 * self.intermediate_size,
98
+ self.d_model,
99
+ device="cuda",
100
+ dtype=self.params_dtype,
101
+ )
102
+ )
103
+ self.w2s = nn.Parameter(
104
+ torch.empty(
105
+ self.num_total_experts,
106
+ self.d_model,
107
+ self.intermediate_size,
108
+ device="cuda",
109
+ dtype=self.params_dtype,
110
+ )
111
+ )
112
+
113
+ set_weight_attrs(
114
+ self.ws,
115
+ {
116
+ "weight_loader": self.weight_loader,
117
+ },
118
+ )
119
+ set_weight_attrs(
120
+ self.w2s,
121
+ {
122
+ "weight_loader": self.weight_loader,
123
+ },
124
+ )
125
+
126
+ def weight_loader(
127
+ self, param: nn.Parameter, loaded_weight: torch.Tensor, weight_name: str
128
+ ):
129
+ tp_rank = get_tensor_model_parallel_rank()
130
+ param_data = param.data
131
+ shard_size = self.intermediate_size
132
+ shard = slice(tp_rank * shard_size, (tp_rank + 1) * shard_size)
133
+ # DBRX uses GLU for each experts.
134
+ # GLU has 3 linear layers: w1, v1 and w2.
135
+ if weight_name.endswith("w1"):
136
+ loaded_weight = torch.reshape(
137
+ loaded_weight,
138
+ [-1, self.intermediate_size * self.tp_size, self.d_model],
139
+ )
140
+ param_data[:, 0:shard_size, :] = loaded_weight[:, shard, :]
141
+ if weight_name.endswith("v1"):
142
+ loaded_weight = torch.reshape(
143
+ loaded_weight,
144
+ [-1, self.intermediate_size * self.tp_size, self.d_model],
145
+ )
146
+ param_data[:, shard_size : 2 * shard_size, :] = loaded_weight[:, shard, :]
147
+ if weight_name.endswith("w2"):
148
+ loaded_weight = torch.reshape(
149
+ loaded_weight,
150
+ [-1, self.intermediate_size * self.tp_size, self.d_model],
151
+ ).transpose(1, 2)
152
+ param_data[:] = loaded_weight[:, :, shard]
153
+
154
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
155
+ num_tokens, hidden_size = hidden_states.shape
156
+ hidden_states = hidden_states.view(-1, self.d_model)
157
+ # router_logits: (num_tokens, n_experts)
158
+ router_logits = self.router(hidden_states)
159
+ final_hidden_states = fused_moe(
160
+ hidden_states,
161
+ self.ws,
162
+ self.w2s,
163
+ router_logits,
164
+ self.top_k,
165
+ renormalize=True,
166
+ inplace=True,
167
+ )
168
+
169
+ if self.tp_size > 1:
170
+ final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
171
+
172
+ return final_hidden_states.view(num_tokens, hidden_size)
173
+
174
+
175
+ class DbrxAttention(nn.Module):
176
+ def __init__(
177
+ self,
178
+ config: DbrxConfig,
179
+ layer_id: int = 0,
180
+ quant_config: Optional[QuantizationConfig] = None,
181
+ ):
182
+ super().__init__()
183
+ self.d_model = config.d_model
184
+ self.total_num_heads = config.n_heads
185
+ self.head_dim = self.d_model // self.total_num_heads
186
+ self.total_num_kv_heads = config.attn_config.kv_n_heads
187
+ self.clip_qkv = config.attn_config.clip_qkv
188
+ self.rope_theta = config.attn_config.rope_theta
189
+ self.max_position = config.max_seq_len
190
+
191
+ # pylint: disable=invalid-name
192
+ self.Wqkv = QKVParallelLinear(
193
+ self.d_model,
194
+ self.head_dim,
195
+ self.total_num_heads,
196
+ self.total_num_kv_heads,
197
+ bias=False,
198
+ quant_config=quant_config,
199
+ )
200
+ self.out_proj = RowParallelLinear(
201
+ self.d_model,
202
+ self.d_model,
203
+ bias=False,
204
+ quant_config=quant_config,
205
+ )
206
+ self.rotary_emb = get_rope(
207
+ self.head_dim,
208
+ rotary_dim=self.head_dim,
209
+ max_position=self.max_position,
210
+ base=int(self.rope_theta),
211
+ is_neox_style=True,
212
+ )
213
+
214
+ tp_world_size = get_tensor_model_parallel_world_size()
215
+ self.tp_size = tp_world_size
216
+ assert self.total_num_heads % tp_world_size == 0
217
+ self.num_heads = self.total_num_heads // tp_world_size
218
+ if self.total_num_kv_heads >= tp_world_size:
219
+ # Number of KV heads is greater than TP size, so we partition
220
+ # the KV heads across multiple tensor parallel GPUs.
221
+ assert self.total_num_kv_heads % tp_world_size == 0
222
+ else:
223
+ # Number of KV heads is less than TP size, so we replicate
224
+ # the KV heads across multiple tensor parallel GPUs.
225
+ assert tp_world_size % self.total_num_kv_heads == 0
226
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_world_size)
227
+ self.q_size = self.num_heads * self.head_dim
228
+ self.kv_size = self.num_kv_heads * self.head_dim
229
+ self.scaling = self.head_dim**-0.5
230
+ self.attn = RadixAttention(
231
+ self.num_heads,
232
+ self.head_dim,
233
+ self.scaling,
234
+ num_kv_heads=self.num_kv_heads,
235
+ layer_id=layer_id,
236
+ )
237
+
238
+ def forward(
239
+ self,
240
+ position_ids: torch.Tensor,
241
+ hidden_states: torch.Tensor,
242
+ input_metadata: InputMetadata,
243
+ ) -> torch.Tensor:
244
+ qkv, _ = self.Wqkv(hidden_states)
245
+ if self.clip_qkv is not None:
246
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
247
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
248
+ q, k = self.rotary_emb(position_ids, q, k)
249
+ attn_output = self.attn(q, k, v, input_metadata)
250
+ hidden_states, _ = self.out_proj(attn_output)
251
+ return hidden_states
252
+
253
+
254
+ class DbrxFusedNormAttention(nn.Module):
255
+ def __init__(
256
+ self,
257
+ config: DbrxConfig,
258
+ layer_id: int = 0,
259
+ quant_config: Optional[QuantizationConfig] = None,
260
+ ):
261
+ super().__init__()
262
+ self.d_model = config.d_model
263
+ self.attn = DbrxAttention(config, layer_id, quant_config=quant_config)
264
+ self.norm_1 = nn.LayerNorm(self.d_model)
265
+ self.norm_2 = nn.LayerNorm(self.d_model)
266
+
267
+ def forward(
268
+ self,
269
+ position_ids: torch.Tensor,
270
+ hidden_states: torch.Tensor,
271
+ input_metadata: InputMetadata,
272
+ ) -> torch.Tensor:
273
+ residual = hidden_states
274
+ hidden_states = self.norm_1(hidden_states)
275
+ x = self.attn(
276
+ position_ids=position_ids,
277
+ hidden_states=hidden_states,
278
+ input_metadata=input_metadata,
279
+ )
280
+ hidden_states = residual + x
281
+ residual = hidden_states
282
+ hidden_states = self.norm_2(hidden_states)
283
+ return hidden_states, residual
284
+
285
+
286
+ class DbrxBlock(nn.Module):
287
+ def __init__(
288
+ self,
289
+ config: DbrxConfig,
290
+ layer_id: int = 0,
291
+ quant_config: Optional[QuantizationConfig] = None,
292
+ ):
293
+ super().__init__()
294
+ self.norm_attn_norm = DbrxFusedNormAttention(config, layer_id, quant_config=quant_config)
295
+ self.ffn = DbrxExperts(config, quant_config=quant_config)
296
+
297
+ def forward(
298
+ self,
299
+ position_ids: torch.Tensor,
300
+ hidden_states: torch.Tensor,
301
+ input_metadata: InputMetadata,
302
+ ) -> torch.Tensor:
303
+ hidden_states, residual = self.norm_attn_norm(
304
+ position_ids=position_ids,
305
+ hidden_states=hidden_states,
306
+ input_metadata=input_metadata,
307
+ )
308
+ hidden_states = self.ffn(hidden_states)
309
+ hidden_states = hidden_states + residual
310
+ return hidden_states
311
+
312
+
313
+ class DbrxModel(nn.Module):
314
+ def __init__(
315
+ self,
316
+ config: DbrxConfig,
317
+ quant_config: Optional[QuantizationConfig] = None,
318
+ ):
319
+ super().__init__()
320
+ self.wte = VocabParallelEmbedding(
321
+ config.vocab_size,
322
+ config.d_model,
323
+ )
324
+ self.blocks = nn.ModuleList(
325
+ [DbrxBlock(config, i, quant_config=quant_config) for i in range(config.n_layers)]
326
+ )
327
+ self.norm_f = nn.LayerNorm(config.d_model, eps=1e-5)
328
+ for module in self.modules():
329
+ if hasattr(module, "bias") and isinstance(module.bias, nn.Parameter):
330
+ # Remove the bias term in Linear and LayerNorm.
331
+ module.register_parameter("bias", None)
332
+
333
+ def forward(
334
+ self,
335
+ input_ids: torch.Tensor,
336
+ position_ids: torch.Tensor,
337
+ input_metadata: InputMetadata,
338
+ input_embeds: torch.Tensor = None,
339
+ ) -> torch.Tensor:
340
+ if input_embeds is None:
341
+ hidden_states = self.wte(input_ids)
342
+ else:
343
+ hidden_states = input_embeds
344
+ for i in range(len(self.blocks)):
345
+ block = self.blocks[i]
346
+ hidden_states = block(position_ids, hidden_states, input_metadata)
347
+ hidden_states = self.norm_f(hidden_states)
348
+ return hidden_states
349
+
350
+
351
+ class DbrxForCausalLM(nn.Module):
352
+ def __init__(
353
+ self,
354
+ config: DbrxConfig,
355
+ quant_config: Optional[QuantizationConfig] = None,
356
+ ):
357
+ super().__init__()
358
+ self.config = config
359
+ self.quant_config = quant_config
360
+ self.unpadded_vocab_size = config.vocab_size
361
+ self.transformer = DbrxModel(config, quant_config=quant_config)
362
+ self.lm_head = ParallelLMHead(
363
+ config.vocab_size,
364
+ config.d_model,
365
+ org_num_embeddings=config.vocab_size,
366
+ padding_size=DEFAULT_VOCAB_PADDING_SIZE,
367
+ )
368
+ self.logits_processor = LogitsProcessor(config)
369
+
370
+ def forward(
371
+ self,
372
+ input_ids: torch.Tensor,
373
+ positions: torch.Tensor,
374
+ input_metadata: InputMetadata,
375
+ ) -> torch.Tensor:
376
+ hidden_states = self.transformer(input_ids, positions, input_metadata)
377
+ return self.logits_processor(
378
+ input_ids, hidden_states, self.lm_head.weight, input_metadata
379
+ )
380
+
381
+ def load_weights(
382
+ self,
383
+ model_name_or_path: str,
384
+ cache_dir: Optional[str] = None,
385
+ load_format: str = "auto",
386
+ revision: Optional[str] = None,
387
+ ):
388
+ expert_params_mapping = [
389
+ (
390
+ "ws" if weight_name in ["w1", "v1"] else "w2s",
391
+ f"experts.mlp.{weight_name}",
392
+ )
393
+ for weight_name in ["w1", "v1", "w2"]
394
+ ]
395
+ params_dict = dict(self.named_parameters(remove_duplicate=False))
396
+ for name, loaded_weight in hf_model_weights_iterator(
397
+ model_name_or_path, cache_dir, load_format, revision
398
+ ):
399
+ for param_name, weight_name in expert_params_mapping:
400
+ if weight_name not in name:
401
+ continue
402
+ name = name.replace(weight_name, param_name)
403
+ param = params_dict[name]
404
+ weight_loader = param.weight_loader
405
+ weight_loader(param, loaded_weight, weight_name)
406
+ break
407
+ else:
408
+ param = params_dict[name]
409
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
410
+ weight_loader(param, loaded_weight)
411
+
412
+
413
+ EntryClass = DbrxForCausalLM
@@ -0,0 +1,281 @@
1
+ # Adapted from:
2
+ # https://github.com/vllm-project/vllm/blob/14ccd94c89d0ffd9da283545d93ab1dfea5da340/vllm/transformers_utils/configs/dbrx.py
3
+ # yapf: disable
4
+ # ruff: noqa: E501
5
+ # coding=utf-8
6
+ # Copied from
7
+ # https://huggingface.co/databricks/dbrx-base/blob/main/configuration_dbrx.py
8
+ """Dbrx configuration."""
9
+
10
+ # FIXME: remove this once vllm releases a new version
11
+
12
+ from typing import Any, Optional
13
+
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.utils import logging
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+ DBRX_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
20
+
21
+
22
+ class DbrxAttentionConfig(PretrainedConfig):
23
+ """Configuration class for Dbrx Attention.
24
+
25
+ [`DbrxAttention`] class. It is used to instantiate attention layers
26
+ according to the specified arguments, defining the layers architecture.
27
+
28
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PretrainedConfig`] for more information.
30
+
31
+ Args:
32
+ attn_pdrop (`float`, *optional*, defaults to 0.0):
33
+ The dropout probability for the attention layers.
34
+ clip_qkv (`float`, *optional*, defaults to None):
35
+ If not `None`, clip the queries, keys, and values in the attention layer to this value.
36
+ kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
37
+ rope_theta (float): The base frequency for rope.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ attn_pdrop: float = 0,
43
+ clip_qkv: Optional[float] = None,
44
+ kv_n_heads: int = 1,
45
+ rope_theta: float = 10000.0,
46
+ **kwargs: Any,
47
+ ):
48
+ super().__init__(**kwargs)
49
+ self.attn_pdrop = attn_pdrop
50
+ self.clip_qkv = clip_qkv
51
+ self.kv_n_heads = kv_n_heads
52
+ self.rope_theta = rope_theta
53
+
54
+ for k in ["model_type"]:
55
+ if k in kwargs:
56
+ kwargs.pop(k)
57
+ if len(kwargs) != 0:
58
+ raise ValueError(f"Found unknown {kwargs=}")
59
+
60
+ @classmethod
61
+ def from_pretrained(
62
+ cls, pretrained_model_name_or_path: str, **kwargs: Any
63
+ ) -> "PretrainedConfig":
64
+ cls._set_token_in_kwargs(kwargs)
65
+
66
+ config_dict, kwargs = cls.get_config_dict(
67
+ pretrained_model_name_or_path, **kwargs
68
+ )
69
+
70
+ if config_dict.get("model_type") == "dbrx":
71
+ config_dict = config_dict["attn_config"]
72
+
73
+ if (
74
+ "model_type" in config_dict
75
+ and hasattr(cls, "model_type")
76
+ and config_dict["model_type"] != cls.model_type
77
+ ):
78
+ logger.warning(
79
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
80
+ + f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
81
+ )
82
+
83
+ return cls.from_dict(config_dict, **kwargs)
84
+
85
+
86
+ class DbrxFFNConfig(PretrainedConfig):
87
+ """Configuration class for Dbrx FFN.
88
+
89
+ [`DbrxFFN`] class. It is used to instantiate feedforward layers according to
90
+ the specified arguments, defining the layers architecture.
91
+
92
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
93
+ documentation from [`PretrainedConfig`] for more information.
94
+
95
+ Args:
96
+ ffn_act_fn (dict, optional): A dict specifying activation function for the FFN.
97
+ The dict should have a key 'name' with the value being the name of
98
+ the activation function along with any additional keyword arguments.
99
+ ffn_hidden_size (int, optional): The hidden size of the feedforward network.
100
+ moe_num_experts (int, optional): The number of experts in the mixture of experts layer.
101
+ moe_top_k (int, optional): The number of experts to use in the mixture of experts layer.
102
+ moe_jitter_eps (float, optional): The jitter epsilon for the mixture of experts layer.
103
+ moe_loss_weight (float, optional): The loss weight for the mixture of experts layer.
104
+ moe_normalize_expert_weights (float, optional): The normalization factor for the expert weights.
105
+ uniform_expert_assignment (bool, optional): Whether to use uniform expert assignment.
106
+ This should only be used for benchmarking purposes.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ ffn_act_fn: Optional[dict] = None,
112
+ ffn_hidden_size: int = 3584,
113
+ moe_num_experts: int = 4,
114
+ moe_top_k: int = 1,
115
+ moe_jitter_eps: Optional[float] = None,
116
+ moe_loss_weight: float = 0.01,
117
+ moe_normalize_expert_weights: Optional[float] = 1,
118
+ uniform_expert_assignment: bool = False,
119
+ **kwargs: Any,
120
+ ):
121
+ super().__init__()
122
+ if ffn_act_fn is None:
123
+ ffn_act_fn = {"name": "silu"}
124
+ self.ffn_act_fn = ffn_act_fn
125
+ self.ffn_hidden_size = ffn_hidden_size
126
+ self.moe_num_experts = moe_num_experts
127
+ self.moe_top_k = moe_top_k
128
+ self.moe_jitter_eps = moe_jitter_eps
129
+ self.moe_loss_weight = moe_loss_weight
130
+ self.moe_normalize_expert_weights = moe_normalize_expert_weights
131
+ self.uniform_expert_assignment = uniform_expert_assignment
132
+
133
+ for k in ["model_type"]:
134
+ if k in kwargs:
135
+ kwargs.pop(k)
136
+ if len(kwargs) != 0:
137
+ raise ValueError(f"Found unknown {kwargs=}")
138
+
139
+ @classmethod
140
+ def from_pretrained(
141
+ cls, pretrained_model_name_or_path: str, **kwargs: Any
142
+ ) -> "PretrainedConfig":
143
+ cls._set_token_in_kwargs(kwargs)
144
+
145
+ config_dict, kwargs = cls.get_config_dict(
146
+ pretrained_model_name_or_path, **kwargs
147
+ )
148
+
149
+ if config_dict.get("model_type") == "dbrx":
150
+ config_dict = config_dict["ffn_config"]
151
+
152
+ if (
153
+ "model_type" in config_dict
154
+ and hasattr(cls, "model_type")
155
+ and config_dict["model_type"] != cls.model_type
156
+ ):
157
+ logger.warning(
158
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
159
+ + f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
160
+ )
161
+
162
+ return cls.from_dict(config_dict, **kwargs)
163
+
164
+
165
+ class DbrxConfig(PretrainedConfig):
166
+ """Configuration class for Dbrx.
167
+
168
+ [`DbrxModel`]. It is used to instantiate a Dbrx model according to the
169
+ specified arguments, defining the model architecture.
170
+
171
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
172
+ documentation from [`PretrainedConfig`] for more information.
173
+
174
+
175
+ Args:
176
+ d_model (`int`, *optional*, defaults to 6144):
177
+ Dimensionality of the embeddings and hidden states.
178
+ n_heads (`int`, *optional*, defaults to 48):
179
+ Number of attention heads for each attention layer in the Transformer encoder.
180
+ n_layers (`int`, *optional*, defaults to 40):
181
+ Number of hidden layers in the Transformer encoder.
182
+ max_seq_len (`int`, *optional*, defaults to 32768):
183
+ The maximum sequence length of the model.
184
+ vocab_size (`int`, *optional*, defaults to 100352):
185
+ Vocabulary size of the Dbrx model. Defines the maximum number of different tokens that can be represented by
186
+ the `inputs_ids` passed when calling [`DbrxModel`].
187
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
188
+ The dropout probability applied to the attention output before combining with residual.
189
+ emb_pdrop (`float`, *optional*, defaults to 0.0):
190
+ The dropout probability for the embedding layer.
191
+ attn_config (`dict`, *optional*):
192
+ A dictionary used to configure the model's attention module.
193
+ ffn_config (`dict`, *optional*):
194
+ A dictionary used to configure the model's FFN module.
195
+ use_cache (`bool`, *optional*, defaults to `False`):
196
+ Whether or not the model should return the last key/values attentions (not used by all models).
197
+ initializer_range (`float`, *optional*, defaults to 0.02):
198
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
199
+ output_router_logits (`bool`, *optional*, defaults to `False`):
200
+ Whether or not the router logits should be returned by the model. Enabling this will also
201
+ allow the model to output the auxiliary loss. See [here]() for more details
202
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
203
+ The aux loss factor for the total loss.
204
+
205
+
206
+ Example:
207
+ ```python
208
+ >>> from transformers import DbrxConfig, DbrxModel
209
+
210
+ >>> # Initializing a Dbrx configuration
211
+ >>> configuration = DbrxConfig()
212
+
213
+ >>> # Initializing a model (with random weights) from the configuration
214
+ >>> model = DbrxModel(configuration)
215
+
216
+ >>> # Accessing the model configuration
217
+ >>> configuration = model.config
218
+ ```
219
+ """
220
+
221
+ model_type = "dbrx"
222
+ attribute_map = {
223
+ "num_attention_heads": "n_heads",
224
+ "hidden_size": "d_model",
225
+ "num_hidden_layers": "n_layers",
226
+ "max_position_embeddings": "max_seq_len",
227
+ }
228
+
229
+ def __init__(
230
+ self,
231
+ d_model: int = 2048,
232
+ n_heads: int = 16,
233
+ n_layers: int = 24,
234
+ max_seq_len: int = 2048,
235
+ vocab_size: int = 32000,
236
+ resid_pdrop: float = 0.0,
237
+ emb_pdrop: float = 0.0,
238
+ attn_config: Optional[DbrxAttentionConfig] = None,
239
+ ffn_config: Optional[DbrxFFNConfig] = None,
240
+ use_cache: bool = True,
241
+ initializer_range: float = 0.02,
242
+ output_router_logits: bool = False,
243
+ router_aux_loss_coef: float = 0.05,
244
+ **kwargs: Any,
245
+ ):
246
+ if attn_config is None:
247
+ self.attn_config = DbrxAttentionConfig()
248
+ elif isinstance(attn_config, dict):
249
+ self.attn_config = DbrxAttentionConfig(**attn_config)
250
+ else:
251
+ self.attn_config = attn_config
252
+
253
+ if ffn_config is None:
254
+ self.ffn_config = DbrxFFNConfig()
255
+ elif isinstance(ffn_config, dict):
256
+ self.ffn_config = DbrxFFNConfig(**ffn_config)
257
+ else:
258
+ self.ffn_config = ffn_config
259
+
260
+ self.d_model = d_model
261
+ self.n_heads = n_heads
262
+ self.n_layers = n_layers
263
+ self.max_seq_len = max_seq_len
264
+ self.vocab_size = vocab_size
265
+ self.resid_pdrop = resid_pdrop
266
+ self.emb_pdrop = emb_pdrop
267
+ self.use_cache = use_cache
268
+ self.initializer_range = initializer_range
269
+ self.output_router_logits = output_router_logits
270
+ self.router_aux_loss_coef = router_aux_loss_coef
271
+
272
+ tie_word_embeddings = kwargs.pop("tie_word_embeddings", False)
273
+ if tie_word_embeddings:
274
+ raise ValueError(
275
+ "tie_word_embeddings is not supported for Dbrx models."
276
+ )
277
+
278
+ super().__init__(
279
+ tie_word_embeddings=tie_word_embeddings,
280
+ **kwargs,
281
+ )