sglang 0.1.21__py3-none-any.whl → 0.1.22__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 (72) hide show
  1. sglang/__init__.py +8 -8
  2. sglang/api.py +1 -1
  3. sglang/backend/vertexai.py +5 -4
  4. sglang/bench.py +627 -0
  5. sglang/bench_latency.py +22 -19
  6. sglang/bench_serving.py +758 -0
  7. sglang/check_env.py +171 -0
  8. sglang/lang/backend/__init__.py +0 -0
  9. sglang/lang/backend/anthropic.py +77 -0
  10. sglang/lang/backend/base_backend.py +80 -0
  11. sglang/lang/backend/litellm.py +90 -0
  12. sglang/lang/backend/openai.py +438 -0
  13. sglang/lang/backend/runtime_endpoint.py +283 -0
  14. sglang/lang/backend/vertexai.py +149 -0
  15. sglang/lang/tracer.py +1 -1
  16. sglang/launch_server.py +1 -1
  17. sglang/launch_server_llavavid.py +1 -4
  18. sglang/srt/conversation.py +1 -1
  19. sglang/srt/layers/context_flashattention_nopad.py +0 -29
  20. sglang/srt/layers/extend_attention.py +0 -39
  21. sglang/srt/layers/linear.py +869 -0
  22. sglang/srt/layers/quantization/__init__.py +49 -0
  23. sglang/srt/layers/quantization/fp8.py +662 -0
  24. sglang/srt/layers/radix_attention.py +31 -5
  25. sglang/srt/layers/token_attention.py +1 -51
  26. sglang/srt/managers/controller/cuda_graph_runner.py +14 -12
  27. sglang/srt/managers/controller/infer_batch.py +47 -49
  28. sglang/srt/managers/controller/manager_multi.py +107 -100
  29. sglang/srt/managers/controller/manager_single.py +76 -96
  30. sglang/srt/managers/controller/model_runner.py +35 -23
  31. sglang/srt/managers/controller/tp_worker.py +127 -138
  32. sglang/srt/managers/detokenizer_manager.py +49 -5
  33. sglang/srt/managers/io_struct.py +36 -17
  34. sglang/srt/managers/tokenizer_manager.py +228 -125
  35. sglang/srt/memory_pool.py +19 -6
  36. sglang/srt/model_loader/model_loader.py +277 -0
  37. sglang/srt/model_loader/utils.py +260 -0
  38. sglang/srt/models/chatglm.py +1 -0
  39. sglang/srt/models/dbrx.py +1 -0
  40. sglang/srt/models/grok.py +1 -0
  41. sglang/srt/models/internlm2.py +317 -0
  42. sglang/srt/models/llama2.py +65 -16
  43. sglang/srt/models/llama_classification.py +1 -0
  44. sglang/srt/models/llava.py +1 -0
  45. sglang/srt/models/llavavid.py +1 -0
  46. sglang/srt/models/minicpm.py +1 -0
  47. sglang/srt/models/mixtral.py +1 -0
  48. sglang/srt/models/mixtral_quant.py +1 -0
  49. sglang/srt/models/qwen.py +1 -0
  50. sglang/srt/models/qwen2.py +6 -0
  51. sglang/srt/models/qwen2_moe.py +7 -4
  52. sglang/srt/models/stablelm.py +1 -0
  53. sglang/srt/openai_api/adapter.py +432 -0
  54. sglang/srt/openai_api/api_adapter.py +432 -0
  55. sglang/srt/openai_api/openai_api_adapter.py +431 -0
  56. sglang/srt/openai_api/openai_protocol.py +207 -0
  57. sglang/srt/openai_api/protocol.py +208 -0
  58. sglang/srt/openai_protocol.py +17 -0
  59. sglang/srt/sampling_params.py +2 -0
  60. sglang/srt/server.py +113 -84
  61. sglang/srt/server_args.py +23 -15
  62. sglang/srt/utils.py +16 -117
  63. sglang/test/test_conversation.py +1 -1
  64. sglang/test/test_openai_protocol.py +1 -1
  65. sglang/test/test_programs.py +1 -1
  66. sglang/test/test_utils.py +2 -2
  67. {sglang-0.1.21.dist-info → sglang-0.1.22.dist-info}/METADATA +157 -167
  68. sglang-0.1.22.dist-info/RECORD +103 -0
  69. {sglang-0.1.21.dist-info → sglang-0.1.22.dist-info}/WHEEL +1 -1
  70. sglang-0.1.21.dist-info/RECORD +0 -82
  71. {sglang-0.1.21.dist-info → sglang-0.1.22.dist-info}/LICENSE +0 -0
  72. {sglang-0.1.21.dist-info → sglang-0.1.22.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,277 @@
1
+ # temporarily adapted from https://github.com/vllm-project/vllm/blob/10383887e03412196a2689b9398290719c4797bf/vllm/model_executor/model_loader/loader.py
2
+ # FIXME: in progress of refactoring the model loader
3
+
4
+ import glob
5
+ import os
6
+ import re
7
+ from typing import Any, Dict, Generator, List, Optional, Tuple, Type
8
+
9
+ import torch
10
+ from torch import nn
11
+ from tqdm import tqdm
12
+ from vllm.config import (
13
+ CacheConfig,
14
+ DeviceConfig,
15
+ LoadConfig,
16
+ LoadFormat,
17
+ LoRAConfig,
18
+ ModelConfig,
19
+ MultiModalConfig,
20
+ ParallelConfig,
21
+ SchedulerConfig,
22
+ )
23
+ from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
24
+ from vllm.model_executor.model_loader.utils import (
25
+ get_model_architecture,
26
+ set_default_torch_dtype,
27
+ )
28
+ from vllm.platforms import current_platform
29
+
30
+ from sglang.srt.model_loader.utils import (
31
+ download_safetensors_index_file_from_hf,
32
+ download_weights_from_hf,
33
+ filter_duplicate_safetensors_files,
34
+ get_quant_config,
35
+ safetensors_weights_iterator,
36
+ )
37
+
38
+
39
+ def _get_quantization_config(
40
+ model_config: ModelConfig, load_config: LoadConfig
41
+ ) -> Optional[QuantizationConfig]:
42
+ """Get the quantization config."""
43
+ if model_config.quantization is not None:
44
+ quant_config = get_quant_config(model_config, load_config)
45
+ capability = current_platform.get_device_capability()
46
+ capability = capability[0] * 10 + capability[1]
47
+ if capability < quant_config.get_min_capability():
48
+ raise ValueError(
49
+ f"The quantization method {model_config.quantization} is not "
50
+ "supported for the current GPU. "
51
+ f"Minimum capability: {quant_config.get_min_capability()}. "
52
+ f"Current capability: {capability}."
53
+ )
54
+ supported_dtypes = quant_config.get_supported_act_dtypes()
55
+ if model_config.dtype not in supported_dtypes:
56
+ raise ValueError(
57
+ f"{model_config.dtype} is not supported for quantization "
58
+ f"method {model_config.quantization}. Supported dtypes: "
59
+ f"{supported_dtypes}"
60
+ )
61
+ return quant_config
62
+ return None
63
+
64
+
65
+ def _get_model_initialization_kwargs(
66
+ model_class: Type[nn.Module],
67
+ lora_config: Optional[LoRAConfig],
68
+ multimodal_config: Optional[MultiModalConfig],
69
+ ) -> Dict[str, Any]:
70
+ """Get extra kwargs for model initialization."""
71
+ extra_kwargs: Dict[str, Any] = {}
72
+
73
+ assert lora_config is None
74
+ assert multimodal_config is None
75
+
76
+ return extra_kwargs
77
+
78
+
79
+ def _initialize_model(
80
+ model_config: ModelConfig,
81
+ load_config: LoadConfig,
82
+ lora_config: Optional[LoRAConfig],
83
+ multimodal_config: Optional[MultiModalConfig],
84
+ cache_config: CacheConfig,
85
+ ) -> nn.Module:
86
+ """Initialize a model with the given configurations."""
87
+ model_class = get_model_architecture(model_config)[0]
88
+ quant_config = _get_quantization_config(model_config, load_config)
89
+
90
+ return model_class(
91
+ config=model_config.hf_config,
92
+ cache_config=cache_config,
93
+ quant_config=quant_config,
94
+ efficient_weight_load=True,
95
+ **_get_model_initialization_kwargs(model_class, lora_config, multimodal_config),
96
+ )
97
+
98
+
99
+ class ModelLoader:
100
+ """Model loader that can load different file types from disk."""
101
+
102
+ def __init__(self, load_config: LoadConfig):
103
+ self.load_config = load_config
104
+
105
+ def _prepare_weights(
106
+ self, model_name_or_path: str, revision: Optional[str], fall_back_to_pt: bool
107
+ ) -> Tuple[str, List[str], bool]:
108
+ """Prepare weights for the model.
109
+
110
+ If the model is not local, it will be downloaded."""
111
+
112
+ is_local = os.path.isdir(model_name_or_path)
113
+ load_format = self.load_config.load_format
114
+ use_safetensors = False
115
+ # Some quantized models use .pt files for storing the weights.
116
+ if load_format == LoadFormat.AUTO:
117
+ allow_patterns = ["*.safetensors", "*.bin"]
118
+ elif load_format == LoadFormat.SAFETENSORS:
119
+ use_safetensors = True
120
+ allow_patterns = ["*.safetensors"]
121
+ elif load_format == LoadFormat.PT:
122
+ allow_patterns = ["*.pt"]
123
+ elif load_format == LoadFormat.NPCACHE:
124
+ allow_patterns = ["*.bin"]
125
+ else:
126
+ raise ValueError(f"Unknown load_format: {load_format}")
127
+
128
+ if fall_back_to_pt:
129
+ allow_patterns += ["*.pt"]
130
+
131
+ if not is_local:
132
+ hf_folder = download_weights_from_hf(
133
+ model_name_or_path,
134
+ self.load_config.download_dir,
135
+ allow_patterns,
136
+ revision,
137
+ )
138
+ else:
139
+ hf_folder = model_name_or_path
140
+
141
+ hf_weights_files: List[str] = []
142
+ for pattern in allow_patterns:
143
+ hf_weights_files += glob.glob(os.path.join(hf_folder, pattern))
144
+ if len(hf_weights_files) > 0:
145
+ if pattern == "*.safetensors":
146
+ use_safetensors = True
147
+ break
148
+
149
+ if use_safetensors:
150
+ # For models like Mistral-7B-Instruct-v0.3
151
+ # there are both sharded safetensors files and a consolidated
152
+ # safetensors file. Using both breaks.
153
+ # Here, we download the `model.safetensors.index.json` and filter
154
+ # any files not found in the index.
155
+ if not is_local:
156
+ download_safetensors_index_file_from_hf(
157
+ model_name_or_path, self.load_config.download_dir, revision
158
+ )
159
+ hf_weights_files = filter_duplicate_safetensors_files(
160
+ hf_weights_files, hf_folder
161
+ )
162
+ else:
163
+ hf_weights_files = filter_files_not_needed_for_inference(hf_weights_files)
164
+
165
+ if len(hf_weights_files) == 0:
166
+ raise RuntimeError(
167
+ f"Cannot find any model weights with `{model_name_or_path}`"
168
+ )
169
+
170
+ return hf_folder, hf_weights_files, use_safetensors
171
+
172
+ def _get_weights_iterator(
173
+ self, model_name_or_path: str, revision: Optional[str], fall_back_to_pt: bool
174
+ ) -> Generator[Tuple[str, torch.Tensor], None, None]:
175
+ """Get an iterator for the model weights based on the load format."""
176
+ hf_folder, hf_weights_files, use_safetensors = self._prepare_weights(
177
+ model_name_or_path, revision, fall_back_to_pt
178
+ )
179
+ if self.load_config.load_format == LoadFormat.NPCACHE:
180
+ # Currently np_cache only support *.bin checkpoints
181
+ assert use_safetensors is False
182
+ weights_iterator = np_cache_weights_iterator(
183
+ model_name_or_path,
184
+ self.load_config.download_dir,
185
+ hf_folder,
186
+ hf_weights_files,
187
+ )
188
+ elif use_safetensors:
189
+ weights_iterator = safetensors_weights_iterator(hf_weights_files)
190
+ else:
191
+ weights_iterator = pt_weights_iterator(hf_weights_files)
192
+
193
+ return weights_iterator
194
+
195
+ def load_model(
196
+ self,
197
+ *,
198
+ model_config: ModelConfig,
199
+ device_config: DeviceConfig,
200
+ lora_config: Optional[LoRAConfig],
201
+ multimodal_config: Optional[MultiModalConfig],
202
+ parallel_config: ParallelConfig,
203
+ scheduler_config: SchedulerConfig,
204
+ cache_config: CacheConfig,
205
+ ) -> nn.Module:
206
+ with set_default_torch_dtype(model_config.dtype):
207
+ with torch.device(device_config.device):
208
+ model = _initialize_model(
209
+ model_config,
210
+ self.load_config,
211
+ lora_config,
212
+ multimodal_config,
213
+ cache_config,
214
+ )
215
+ weights = self._get_weights_iterator(
216
+ model_config.model,
217
+ model_config.revision,
218
+ fall_back_to_pt=getattr(model, "fall_back_to_pt_during_load", True),
219
+ )
220
+
221
+ modules = {}
222
+ for name, module in model.named_modules():
223
+ modules[name] = module
224
+
225
+ def apply_quant_method(module):
226
+ quant_method = getattr(module, "quant_method", None)
227
+ if quant_method is not None:
228
+ # print("before apply quant", module.weight, module.weight.dtype)
229
+ quant_method.process_weights_after_loading(module)
230
+ # print("after apply quant", module.weight, module.weight.dtype)
231
+ # FIXME: Remove this after Mixtral is updated
232
+ # to use quant_method.
233
+ if hasattr(module, "process_weights_after_loading"):
234
+ module.process_weights_after_loading()
235
+
236
+ if torch.cuda.current_device() == 0:
237
+ weights = tqdm(
238
+ weights, total=model.get_num_params() * 1.5, desc="load model"
239
+ )
240
+
241
+ num_shard = {}
242
+ num_loaded = {}
243
+ for name, loaded_weight in weights:
244
+ model.load_weights(None, name, loaded_weight)
245
+ module_name, shard_num = model.get_module_name(name)
246
+ num_shard[module_name] = shard_num
247
+ if module_name not in num_loaded:
248
+ num_loaded[module_name] = 1
249
+ else:
250
+ num_loaded[module_name] += 1
251
+ if num_loaded[module_name] == num_shard[module_name]:
252
+ apply_quant_method(modules[module_name])
253
+
254
+ return model.eval()
255
+
256
+
257
+ def get_model(
258
+ *,
259
+ model_config: ModelConfig,
260
+ load_config: LoadConfig,
261
+ device_config: DeviceConfig,
262
+ parallel_config: ParallelConfig,
263
+ scheduler_config: SchedulerConfig,
264
+ lora_config: Optional[LoRAConfig],
265
+ multimodal_config: Optional[MultiModalConfig],
266
+ cache_config: CacheConfig,
267
+ ) -> nn.Module:
268
+ loader = ModelLoader(load_config)
269
+ return loader.load_model(
270
+ model_config=model_config,
271
+ device_config=device_config,
272
+ lora_config=lora_config,
273
+ multimodal_config=multimodal_config,
274
+ parallel_config=parallel_config,
275
+ scheduler_config=scheduler_config,
276
+ cache_config=cache_config,
277
+ )
@@ -0,0 +1,260 @@
1
+ # temporarily adapted from vLLM
2
+ # FIXME: in progress of refactoring the model loader
3
+ """Utilities for selecting and loading models."""
4
+ import contextlib
5
+ import fnmatch
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import os
10
+ import tempfile
11
+ from typing import Any, Generator, Iterable, List, Optional, Tuple, Type
12
+
13
+ import filelock
14
+ import huggingface_hub.constants
15
+ import torch
16
+ from huggingface_hub import HfFileSystem, hf_hub_download, snapshot_download
17
+ from safetensors.torch import load_file, safe_open, save_file
18
+ from torch import nn
19
+ from tqdm.auto import tqdm
20
+ from transformers.utils import SAFE_WEIGHTS_INDEX_NAME
21
+ from vllm.config import LoadConfig, ModelConfig
22
+ from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
23
+
24
+ from sglang.srt.layers.quantization import get_quantization_config
25
+
26
+ logger = logging.getLogger("srt.model_loader")
27
+ temp_dir = tempfile.gettempdir()
28
+
29
+
30
+ @contextlib.contextmanager
31
+ def set_default_torch_dtype(dtype: torch.dtype):
32
+ """Sets the default torch dtype to the given dtype."""
33
+ old_dtype = torch.get_default_dtype()
34
+ torch.set_default_dtype(dtype)
35
+ yield
36
+ torch.set_default_dtype(old_dtype)
37
+
38
+
39
+ def get_model_architecture(model_config: ModelConfig) -> Tuple[Type[nn.Module], str]:
40
+ architectures = getattr(model_config.hf_config, "architectures", [])
41
+ # Special handling for quantized Mixtral.
42
+ # FIXME(woosuk): This is a temporary hack.
43
+ if (
44
+ model_config.quantization is not None
45
+ and model_config.quantization != "fp8"
46
+ and "MixtralForCausalLM" in architectures
47
+ ):
48
+ architectures = ["QuantMixtralForCausalLM"]
49
+
50
+ for arch in architectures:
51
+ model_cls = ModelRegistry.load_model_cls(arch)
52
+ if model_cls is not None:
53
+ return (model_cls, arch)
54
+ raise ValueError(
55
+ f"Model architectures {architectures} are not supported for now. "
56
+ f"Supported architectures: {ModelRegistry.get_supported_archs()}"
57
+ )
58
+
59
+
60
+ class DisabledTqdm(tqdm):
61
+
62
+ def __init__(self, *args, **kwargs):
63
+ super().__init__(*args, **kwargs, disable=True)
64
+
65
+
66
+ def get_lock(model_name_or_path: str, cache_dir: Optional[str] = None):
67
+ lock_dir = cache_dir or temp_dir
68
+ os.makedirs(os.path.dirname(lock_dir), exist_ok=True)
69
+ model_name = model_name_or_path.replace("/", "-")
70
+ hash_name = hashlib.sha256(model_name.encode()).hexdigest()
71
+ # add hash to avoid conflict with old users' lock files
72
+ lock_file_name = hash_name + model_name + ".lock"
73
+ # mode 0o666 is required for the filelock to be shared across users
74
+ lock = filelock.FileLock(os.path.join(lock_dir, lock_file_name), mode=0o666)
75
+ return lock
76
+
77
+
78
+ def download_weights_from_hf(
79
+ model_name_or_path: str,
80
+ cache_dir: Optional[str],
81
+ allow_patterns: List[str],
82
+ revision: Optional[str] = None,
83
+ ) -> str:
84
+ """Download model weights from Hugging Face Hub.
85
+
86
+ Args:
87
+ model_name_or_path (str): The model name or path.
88
+ cache_dir (Optional[str]): The cache directory to store the model
89
+ weights. If None, will use HF defaults.
90
+ allow_patterns (List[str]): The allowed patterns for the
91
+ weight files. Files matched by any of the patterns will be
92
+ downloaded.
93
+ revision (Optional[str]): The revision of the model.
94
+
95
+ Returns:
96
+ str: The path to the downloaded model weights.
97
+ """
98
+ if not huggingface_hub.constants.HF_HUB_OFFLINE:
99
+ # Before we download we look at that is available:
100
+ fs = HfFileSystem()
101
+ file_list = fs.ls(model_name_or_path, detail=False, revision=revision)
102
+
103
+ # depending on what is available we download different things
104
+ for pattern in allow_patterns:
105
+ matching = fnmatch.filter(file_list, pattern)
106
+ if len(matching) > 0:
107
+ allow_patterns = [pattern]
108
+ break
109
+
110
+ logger.info("Using model weights format %s", allow_patterns)
111
+ # Use file lock to prevent multiple processes from
112
+ # downloading the same model weights at the same time.
113
+ with get_lock(model_name_or_path, cache_dir):
114
+ hf_folder = snapshot_download(
115
+ model_name_or_path,
116
+ allow_patterns=allow_patterns,
117
+ cache_dir=cache_dir,
118
+ tqdm_class=DisabledTqdm,
119
+ revision=revision,
120
+ local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
121
+ )
122
+ return hf_folder
123
+
124
+
125
+ def download_safetensors_index_file_from_hf(
126
+ model_name_or_path: str,
127
+ cache_dir: Optional[str],
128
+ revision: Optional[str] = None,
129
+ ) -> None:
130
+ """Download hf safetensors index file from Hugging Face Hub.
131
+
132
+ Args:
133
+ model_name_or_path (str): The model name or path.
134
+ cache_dir (Optional[str]): The cache directory to store the model
135
+ weights. If None, will use HF defaults.
136
+ revision (Optional[str]): The revision of the model.
137
+ """
138
+ # Use file lock to prevent multiple processes from
139
+ # downloading the same model weights at the same time.
140
+ with get_lock(model_name_or_path, cache_dir):
141
+ try:
142
+ # Download the safetensors index file.
143
+ hf_hub_download(
144
+ repo_id=model_name_or_path,
145
+ filename=SAFE_WEIGHTS_INDEX_NAME,
146
+ cache_dir=cache_dir,
147
+ revision=revision,
148
+ local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
149
+ )
150
+ # If file not found on remote or locally, we should not fail since
151
+ # only some models will have SAFE_WEIGHTS_INDEX_NAME.
152
+ except huggingface_hub.utils.EntryNotFoundError:
153
+ logger.info("No %s found in remote.", SAFE_WEIGHTS_INDEX_NAME)
154
+ except huggingface_hub.utils.LocalEntryNotFoundError:
155
+ logger.info("No %s found in local cache.", SAFE_WEIGHTS_INDEX_NAME)
156
+
157
+
158
+ # For models like Mistral-7B-v0.3, there are both sharded
159
+ # safetensors files and a consolidated safetensors file.
160
+ # Passing both of these to the weight loader functionality breaks.
161
+ # So, we use the SAFE_WEIGHTS_INDEX_NAME to
162
+ # look up which safetensors files should be used.
163
+ def filter_duplicate_safetensors_files(
164
+ hf_weights_files: List[str], hf_folder: str
165
+ ) -> List[str]:
166
+ # model.safetensors.index.json is a mapping from keys in the
167
+ # torch state_dict to safetensors file holding that weight.
168
+ index_file_name = os.path.join(hf_folder, SAFE_WEIGHTS_INDEX_NAME)
169
+ if not os.path.isfile(index_file_name):
170
+ return hf_weights_files
171
+
172
+ # Iterate through the weight_map (weight_name: safetensors files)
173
+ # to identify weights that we should use.
174
+ with open(index_file_name) as index_file:
175
+ weight_map = json.load(index_file)["weight_map"]
176
+ weight_files_in_index = set()
177
+ for weight_name in weight_map:
178
+ weight_files_in_index.add(os.path.join(hf_folder, weight_map[weight_name]))
179
+ # Filter out any fields that are not found in the index file.
180
+ hf_weights_files = [f for f in hf_weights_files if f in weight_files_in_index]
181
+ return hf_weights_files
182
+
183
+
184
+ def safetensors_weights_iterator(
185
+ hf_weights_files: List[str],
186
+ ) -> Generator[Tuple[str, torch.Tensor], None, None]:
187
+ """Iterate over the weights in the model safetensor files."""
188
+ for st_file in hf_weights_files:
189
+ with safe_open(st_file, framework="pt") as f:
190
+ for name in f.keys(): # noqa: SIM118
191
+ param = f.get_tensor(name)
192
+ yield name, param
193
+
194
+
195
+ def get_quant_config(
196
+ model_config: ModelConfig, load_config: LoadConfig
197
+ ) -> QuantizationConfig:
198
+ quant_cls = get_quantization_config(model_config.quantization)
199
+ # Read the quantization config from the HF model config, if available.
200
+ hf_quant_config = getattr(model_config.hf_config, "quantization_config", None)
201
+ if hf_quant_config is None:
202
+ # compressed-tensors uses a compressions_config
203
+ hf_quant_config = getattr(model_config.hf_config, "compression_config", None)
204
+ if hf_quant_config is not None:
205
+ return quant_cls.from_config(hf_quant_config)
206
+ # In case of bitsandbytes/QLoRA, get quant config from the adapter model.
207
+ if model_config.quantization == "bitsandbytes":
208
+ if (
209
+ not load_config.model_loader_extra_config
210
+ or "qlora_adapter_name_or_path" not in load_config.model_loader_extra_config
211
+ ):
212
+ return quant_cls.from_config({"adapter_name_or_path": ""})
213
+ model_name_or_path = load_config.model_loader_extra_config[
214
+ "qlora_adapter_name_or_path"
215
+ ]
216
+
217
+ else:
218
+ model_name_or_path = model_config.model
219
+ is_local = os.path.isdir(model_name_or_path)
220
+ if not is_local:
221
+ # Download the config files.
222
+ with get_lock(model_name_or_path, load_config.download_dir):
223
+ hf_folder = snapshot_download(
224
+ model_name_or_path,
225
+ revision=model_config.revision,
226
+ allow_patterns="*.json",
227
+ cache_dir=load_config.download_dir,
228
+ local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
229
+ tqdm_class=DisabledTqdm,
230
+ )
231
+ else:
232
+ hf_folder = model_name_or_path
233
+
234
+ possible_config_filenames = quant_cls.get_config_filenames()
235
+
236
+ # If the quantization config is not found, use the default config.
237
+ if not possible_config_filenames:
238
+ return quant_cls()
239
+
240
+ config_files = glob.glob(os.path.join(hf_folder, "*.json"))
241
+
242
+ quant_config_files = [
243
+ f for f in config_files if any(f.endswith(x) for x in possible_config_filenames)
244
+ ]
245
+ if len(quant_config_files) == 0:
246
+ raise ValueError(f"Cannot find the config file for {model_config.quantization}")
247
+ if len(quant_config_files) > 1:
248
+ raise ValueError(
249
+ f"Found multiple config files for {model_config.quantization}: "
250
+ f"{quant_config_files}"
251
+ )
252
+
253
+ quant_config_file = quant_config_files[0]
254
+ with open(quant_config_file, "r") as f:
255
+ config = json.load(f)
256
+
257
+ if model_config.quantization == "bitsandbytes":
258
+ config["adapter_name_or_path"] = model_name_or_path
259
+
260
+ return quant_cls.from_config(config)
@@ -360,6 +360,7 @@ class ChatGLMForCausalLM(nn.Module):
360
360
  self.logits_processor = LogitsProcessor(config)
361
361
  self.sampler = Sampler()
362
362
 
363
+ @torch.no_grad()
363
364
  def forward(
364
365
  self,
365
366
  input_ids: torch.Tensor,
sglang/srt/models/dbrx.py CHANGED
@@ -368,6 +368,7 @@ class DbrxForCausalLM(nn.Module):
368
368
  )
369
369
  self.logits_processor = LogitsProcessor(config)
370
370
 
371
+ @torch.no_grad()
371
372
  def forward(
372
373
  self,
373
374
  input_ids: torch.Tensor,
sglang/srt/models/grok.py CHANGED
@@ -601,6 +601,7 @@ class Grok1ModelForCausalLM(nn.Module):
601
601
  # Monkey patch _prepare_weights to load pre-sharded weights
602
602
  setattr(DefaultModelLoader, "_prepare_weights", _prepare_presharded_weights)
603
603
 
604
+ @torch.no_grad()
604
605
  def forward(
605
606
  self,
606
607
  input_ids: torch.Tensor,