sglang 0.1.14__py3-none-any.whl → 0.1.16__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 (61) hide show
  1. sglang/__init__.py +57 -2
  2. sglang/api.py +8 -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 +5 -1
  8. sglang/lang/chat_template.py +83 -2
  9. sglang/lang/interpreter.py +92 -35
  10. sglang/lang/ir.py +12 -9
  11. sglang/lang/tracer.py +6 -4
  12. sglang/launch_server_llavavid.py +31 -0
  13. sglang/srt/constrained/fsm_cache.py +1 -0
  14. sglang/srt/constrained/jump_forward.py +1 -0
  15. sglang/srt/conversation.py +2 -2
  16. sglang/srt/flush_cache.py +16 -0
  17. sglang/srt/hf_transformers_utils.py +10 -2
  18. sglang/srt/layers/context_flashattention_nopad.py +1 -0
  19. sglang/srt/layers/extend_attention.py +1 -0
  20. sglang/srt/layers/logits_processor.py +114 -54
  21. sglang/srt/layers/radix_attention.py +2 -1
  22. sglang/srt/layers/token_attention.py +1 -0
  23. sglang/srt/managers/detokenizer_manager.py +5 -1
  24. sglang/srt/managers/io_struct.py +27 -3
  25. sglang/srt/managers/router/infer_batch.py +97 -48
  26. sglang/srt/managers/router/manager.py +11 -8
  27. sglang/srt/managers/router/model_rpc.py +169 -90
  28. sglang/srt/managers/router/model_runner.py +110 -166
  29. sglang/srt/managers/router/radix_cache.py +89 -51
  30. sglang/srt/managers/router/scheduler.py +17 -28
  31. sglang/srt/managers/tokenizer_manager.py +110 -33
  32. sglang/srt/memory_pool.py +5 -14
  33. sglang/srt/model_config.py +11 -0
  34. sglang/srt/models/commandr.py +372 -0
  35. sglang/srt/models/dbrx.py +412 -0
  36. sglang/srt/models/dbrx_config.py +281 -0
  37. sglang/srt/models/gemma.py +24 -25
  38. sglang/srt/models/llama2.py +25 -26
  39. sglang/srt/models/llava.py +8 -10
  40. sglang/srt/models/llavavid.py +307 -0
  41. sglang/srt/models/mixtral.py +29 -33
  42. sglang/srt/models/qwen.py +34 -25
  43. sglang/srt/models/qwen2.py +25 -26
  44. sglang/srt/models/stablelm.py +26 -26
  45. sglang/srt/models/yivl.py +3 -5
  46. sglang/srt/openai_api_adapter.py +356 -0
  47. sglang/srt/{managers/openai_protocol.py → openai_protocol.py} +36 -20
  48. sglang/srt/sampling_params.py +2 -0
  49. sglang/srt/server.py +91 -456
  50. sglang/srt/server_args.py +79 -49
  51. sglang/srt/utils.py +212 -47
  52. sglang/srt/weight_utils.py +417 -0
  53. sglang/test/test_programs.py +8 -7
  54. sglang/test/test_utils.py +195 -7
  55. sglang/utils.py +77 -26
  56. {sglang-0.1.14.dist-info → sglang-0.1.16.dist-info}/METADATA +20 -18
  57. sglang-0.1.16.dist-info/RECORD +72 -0
  58. sglang-0.1.14.dist-info/RECORD +0 -64
  59. {sglang-0.1.14.dist-info → sglang-0.1.16.dist-info}/LICENSE +0 -0
  60. {sglang-0.1.14.dist-info → sglang-0.1.16.dist-info}/WHEEL +0 -0
  61. {sglang-0.1.14.dist-info → sglang-0.1.16.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,372 @@
1
+ # coding=utf-8
2
+ # Copyright 2024 Cohere and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ # This file is based on the LLama model definition file in transformers
22
+ """PyTorch Cohere model."""
23
+ from typing import Optional, Tuple
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn.parameter import Parameter
29
+ from transformers import PretrainedConfig
30
+ from vllm.distributed import (
31
+ get_tensor_model_parallel_rank,
32
+ get_tensor_model_parallel_world_size,
33
+ )
34
+ from vllm.model_executor.layers.activation import SiluAndMul
35
+ from vllm.model_executor.layers.linear import (
36
+ MergedColumnParallelLinear,
37
+ QKVParallelLinear,
38
+ RowParallelLinear,
39
+ )
40
+ from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
41
+ from vllm.model_executor.layers.rotary_embedding import get_rope
42
+ from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
43
+ from vllm.model_executor.utils import set_weight_attrs
44
+
45
+ from sglang.srt.layers.logits_processor import LogitsProcessor
46
+ from sglang.srt.layers.radix_attention import RadixAttention
47
+ from sglang.srt.managers.router.model_runner import InputMetadata
48
+ from sglang.srt.weight_utils import default_weight_loader, hf_model_weights_iterator
49
+
50
+
51
+ @torch.compile
52
+ def layer_norm_func(hidden_states, weight, variance_epsilon):
53
+ input_dtype = hidden_states.dtype
54
+ hidden_states = hidden_states.to(torch.float32)
55
+ mean = hidden_states.mean(-1, keepdim=True)
56
+ variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
57
+ hidden_states = (hidden_states - mean) * torch.rsqrt(variance + variance_epsilon)
58
+ hidden_states = weight.to(torch.float32) * hidden_states
59
+ return hidden_states.to(input_dtype)
60
+
61
+
62
+ class LayerNorm(nn.Module):
63
+ def __init__(self, param_shape=None, eps=1e-5):
64
+ super().__init__()
65
+ self.weight = nn.Parameter(torch.ones(param_shape))
66
+ self.variance_epsilon = eps
67
+ set_weight_attrs(self.weight, {"weight_loader": self.weight_loader})
68
+
69
+ def forward(self, hidden_states, residuals=None):
70
+ hidden_states = layer_norm_func(
71
+ hidden_states, self.weight, self.variance_epsilon
72
+ )
73
+ return hidden_states, residuals
74
+
75
+ def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor):
76
+ tp_rank = get_tensor_model_parallel_rank()
77
+ shard_dim = 0 if param.dim() != 1 else None
78
+ param_data = param.data
79
+ if shard_dim is not None:
80
+ shard_size = param_data.shape[shard_dim]
81
+ start_idx = tp_rank * shard_size
82
+ loaded_weight = loaded_weight.narrow(shard_dim, start_idx, shard_size)
83
+ assert param_data.shape == loaded_weight.shape
84
+ param_data.copy_(loaded_weight)
85
+
86
+
87
+ # Copied from transformers.models.llama.modeling_llama.LlamaMLP Llama->Cohere
88
+ class CohereMLP(nn.Module):
89
+ def __init__(
90
+ self,
91
+ config,
92
+ quant_config: Optional[QuantizationConfig] = None,
93
+ ):
94
+ super().__init__()
95
+ self.config = config
96
+ self.hidden_size = config.hidden_size
97
+ self.intermediate_size = config.intermediate_size
98
+ self.gate_up_proj = MergedColumnParallelLinear(
99
+ self.hidden_size,
100
+ [self.intermediate_size] * 2,
101
+ bias=False,
102
+ quant_config=quant_config,
103
+ )
104
+ self.down_proj = RowParallelLinear(
105
+ self.intermediate_size,
106
+ self.hidden_size,
107
+ bias=False,
108
+ quant_config=quant_config,
109
+ )
110
+ self.act_fn = SiluAndMul()
111
+
112
+ def forward(self, x):
113
+ gate_up, _ = self.gate_up_proj(x)
114
+ x = self.act_fn(gate_up)
115
+ x, _ = self.down_proj(x)
116
+ return x
117
+
118
+
119
+ class CohereAttention(nn.Module):
120
+ def __init__(
121
+ self,
122
+ config: PretrainedConfig,
123
+ layer_id: int = 0,
124
+ quant_config: Optional[QuantizationConfig] = None,
125
+ ):
126
+ super().__init__()
127
+ tp_size = get_tensor_model_parallel_world_size()
128
+ self.config = config
129
+ self.attention_dropout = config.attention_dropout
130
+ self.hidden_size = config.hidden_size
131
+ self.total_num_heads = config.num_attention_heads
132
+ self.num_heads = self.total_num_heads // tp_size
133
+ self.head_dim = self.hidden_size // self.total_num_heads
134
+ self.total_num_kv_heads = config.num_key_value_heads
135
+ if self.total_num_kv_heads >= tp_size:
136
+ # Number of KV heads is greater than TP size, so we partition
137
+ # the KV heads across multiple tensor parallel GPUs.
138
+ assert self.total_num_kv_heads % tp_size == 0
139
+ else:
140
+ # Number of KV heads is less than TP size, so we replicate
141
+ # the KV heads across multiple tensor parallel GPUs.
142
+ assert tp_size % self.total_num_kv_heads == 0
143
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
144
+ self.q_size = self.num_heads * self.head_dim
145
+ self.kv_size = self.num_kv_heads * self.head_dim
146
+ self.scaling = self.head_dim**-0.5
147
+ self.max_position_embeddings = getattr(
148
+ config, "model_max_length", None
149
+ ) or getattr(config, "max_position_embeddings", 8192)
150
+ self.rope_theta = config.rope_theta
151
+ self.rope_scaling = getattr(config, "rope_scaling", None)
152
+ self.use_qk_norm = getattr(config, "use_qk_norm", False)
153
+ self.qkv_proj = QKVParallelLinear(
154
+ self.hidden_size,
155
+ self.head_dim,
156
+ self.total_num_heads,
157
+ self.total_num_kv_heads,
158
+ bias=False,
159
+ quant_config=quant_config,
160
+ )
161
+ self.o_proj = RowParallelLinear(
162
+ self.total_num_heads * self.head_dim,
163
+ self.hidden_size,
164
+ bias=False,
165
+ quant_config=quant_config,
166
+ )
167
+ self.rotary_emb = get_rope(
168
+ self.head_dim,
169
+ rotary_dim=self.head_dim,
170
+ max_position=self.max_position_embeddings,
171
+ base=self.rope_theta,
172
+ rope_scaling=self.rope_scaling,
173
+ is_neox_style=False,
174
+ )
175
+ self.attn = RadixAttention(
176
+ self.num_heads,
177
+ self.head_dim,
178
+ self.scaling,
179
+ num_kv_heads=self.num_kv_heads,
180
+ layer_id=layer_id,
181
+ )
182
+ if self.use_qk_norm:
183
+ self.q_norm = LayerNorm(
184
+ param_shape=(self.num_heads, self.head_dim), eps=config.layer_norm_eps
185
+ )
186
+ self.k_norm = LayerNorm(
187
+ param_shape=(self.num_kv_heads, self.head_dim),
188
+ eps=config.layer_norm_eps,
189
+ )
190
+
191
+ def _apply_qk_norm(self, q, k):
192
+ q = q.view(*q.shape[:-1], -1, self.head_dim)
193
+ k = k.view(*k.shape[:-1], -1, self.head_dim)
194
+ q, _ = self.q_norm(q)
195
+ k, _ = self.k_norm(k)
196
+ q = q.view(*q.shape[:-2], -1)
197
+ k = k.view(*k.shape[:-2], -1)
198
+ return q, k
199
+
200
+ def forward(
201
+ self,
202
+ positions: torch.Tensor,
203
+ hidden_states: torch.Tensor,
204
+ input_metadata: InputMetadata,
205
+ ) -> torch.Tensor:
206
+ qkv, _ = self.qkv_proj(hidden_states)
207
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
208
+ if self.use_qk_norm:
209
+ q, k = self._apply_qk_norm(q, k)
210
+ q, k = self.rotary_emb(positions, q, k)
211
+ attn_output = self.attn(q, k, v, input_metadata)
212
+ output, _ = self.o_proj(attn_output)
213
+ return output
214
+
215
+
216
+ class CohereDecoderLayer(nn.Module):
217
+ def __init__(
218
+ self,
219
+ config: PretrainedConfig,
220
+ layer_id: int = 0,
221
+ quant_config: Optional[QuantizationConfig] = None,
222
+ ):
223
+ super().__init__()
224
+ self.hidden_size = config.hidden_size
225
+
226
+ self.self_attn = CohereAttention(
227
+ config, layer_id=layer_id, quant_config=quant_config
228
+ )
229
+
230
+ self.mlp = CohereMLP(config, quant_config=quant_config)
231
+ self.input_layernorm = LayerNorm(
232
+ param_shape=(config.hidden_size), eps=config.layer_norm_eps
233
+ )
234
+
235
+ def forward(
236
+ self,
237
+ positions: torch.Tensor,
238
+ hidden_states: torch.Tensor,
239
+ input_metadata: InputMetadata,
240
+ residual: Optional[torch.Tensor],
241
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
242
+ # Self Attention
243
+ residual = hidden_states
244
+ hidden_states, residual = self.input_layernorm(hidden_states, residual)
245
+ hidden_states_attention = self.self_attn(
246
+ positions=positions,
247
+ hidden_states=hidden_states,
248
+ input_metadata=input_metadata,
249
+ )
250
+ hidden_states_mlp = self.mlp(hidden_states)
251
+ # Add everything together
252
+ hidden_states = residual + hidden_states_attention + hidden_states_mlp
253
+
254
+ return hidden_states, residual
255
+
256
+
257
+ class CohereModel(nn.Module):
258
+ def __init__(
259
+ self,
260
+ config: PretrainedConfig,
261
+ quant_config: Optional[QuantizationConfig] = None,
262
+ ):
263
+ super().__init__()
264
+ self.config = config
265
+ self.vocab_size = config.vocab_size
266
+ self.embed_tokens = VocabParallelEmbedding(
267
+ config.vocab_size, config.hidden_size
268
+ )
269
+ self.layers = nn.ModuleList(
270
+ [
271
+ CohereDecoderLayer(config, i, quant_config=quant_config)
272
+ for i in range(config.num_hidden_layers)
273
+ ]
274
+ )
275
+ self.norm = LayerNorm(
276
+ param_shape=(config.hidden_size), eps=config.layer_norm_eps
277
+ )
278
+
279
+ def forward(
280
+ self,
281
+ input_ids: torch.Tensor,
282
+ positions: torch.Tensor,
283
+ input_metadata: InputMetadata,
284
+ ) -> torch.Tensor:
285
+ hidden_states = self.embed_tokens(input_ids)
286
+ residual = None
287
+ for i in range(len(self.layers)):
288
+ layer = self.layers[i]
289
+ hidden_states, residual = layer(
290
+ positions,
291
+ hidden_states,
292
+ input_metadata,
293
+ residual,
294
+ )
295
+ hidden_states, _ = self.norm(hidden_states, residual)
296
+ return hidden_states
297
+
298
+
299
+ class CohereForCausalLM(nn.Module):
300
+ def __init__(
301
+ self,
302
+ config: PretrainedConfig,
303
+ quant_config: Optional[QuantizationConfig] = None,
304
+ ) -> None:
305
+ super().__init__()
306
+ self.config = config
307
+ self.quant_config = quant_config
308
+ self.logits_processor = LogitsProcessor(config)
309
+ self.model = CohereModel(config, quant_config)
310
+
311
+ @torch.no_grad()
312
+ def forward(
313
+ self,
314
+ input_ids: torch.Tensor,
315
+ positions: torch.Tensor,
316
+ input_metadata: InputMetadata,
317
+ ) -> torch.Tensor:
318
+ hidden_states = self.model(
319
+ input_ids,
320
+ positions,
321
+ input_metadata,
322
+ )
323
+ return self.logits_processor(
324
+ input_ids, hidden_states, self.model.embed_tokens.weight, input_metadata
325
+ )
326
+
327
+ def load_weights(
328
+ self,
329
+ model_name_or_path: str,
330
+ cache_dir: Optional[str] = None,
331
+ load_format: str = "auto",
332
+ revision: Optional[str] = None,
333
+ ):
334
+ stacked_params_mapping = [
335
+ # (param_name, shard_name, shard_id)
336
+ ("qkv_proj", "q_proj", "q"),
337
+ ("qkv_proj", "k_proj", "k"),
338
+ ("qkv_proj", "v_proj", "v"),
339
+ ("gate_up_proj", "gate_proj", 0),
340
+ ("gate_up_proj", "up_proj", 1),
341
+ ]
342
+ params_dict = dict(self.named_parameters())
343
+ loaded_params = set()
344
+ for name, loaded_weight in hf_model_weights_iterator(
345
+ model_name_or_path, cache_dir, load_format, revision
346
+ ):
347
+ for param_name, shard_name, shard_id in stacked_params_mapping:
348
+ if shard_name not in name:
349
+ continue
350
+ name = name.replace(shard_name, param_name)
351
+ # Skip loading extra bias for GPTQ models.
352
+ if name.endswith(".bias") and name not in params_dict:
353
+ continue
354
+ param = params_dict[name]
355
+ weight_loader = param.weight_loader
356
+ weight_loader(param, loaded_weight, shard_id)
357
+ break
358
+ else:
359
+ # lm_head is not used in vllm as it is tied with embed_token.
360
+ # To prevent errors, skip loading lm_head.weight.
361
+ if "lm_head.weight" in name:
362
+ continue
363
+ # Skip loading extra bias for GPTQ models.
364
+ if name.endswith(".bias") and name not in params_dict:
365
+ continue
366
+ param = params_dict[name]
367
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
368
+ weight_loader(param, loaded_weight)
369
+ loaded_params.add(name)
370
+
371
+
372
+ EntryClass = CohereForCausalLM