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