xinference 1.3.1.post1__py3-none-any.whl → 1.4.1__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.
Potentially problematic release.
This version of xinference might be problematic. Click here for more details.
- xinference/_compat.py +1 -0
- xinference/_version.py +3 -3
- xinference/api/restful_api.py +4 -0
- xinference/core/chat_interface.py +1 -1
- xinference/core/model.py +23 -3
- xinference/core/supervisor.py +6 -0
- xinference/core/worker.py +54 -11
- xinference/model/llm/__init__.py +7 -2
- xinference/model/llm/core.py +1 -0
- xinference/model/llm/llama_cpp/core.py +50 -15
- xinference/model/llm/llm_family.json +388 -13
- xinference/model/llm/llm_family_modelscope.json +373 -14
- xinference/model/llm/mlx/core.py +15 -11
- xinference/model/llm/reasoning_parser.py +17 -9
- xinference/model/llm/sglang/core.py +112 -12
- xinference/model/llm/transformers/core.py +4 -2
- xinference/model/llm/transformers/deepseek_vl.py +1 -1
- xinference/model/llm/transformers/deepseek_vl2.py +287 -0
- xinference/model/llm/transformers/gemma3.py +185 -0
- xinference/model/llm/transformers/intern_vl.py +0 -2
- xinference/model/llm/utils.py +62 -42
- xinference/model/llm/vllm/core.py +157 -11
- xinference/model/llm/vllm/distributed_executor.py +314 -0
- xinference/model/rerank/core.py +16 -11
- xinference/thirdparty/deepseek_vl2/__init__.py +31 -0
- xinference/thirdparty/deepseek_vl2/models/__init__.py +26 -0
- xinference/thirdparty/deepseek_vl2/models/configuration_deepseek.py +210 -0
- xinference/thirdparty/deepseek_vl2/models/conversation.py +310 -0
- xinference/thirdparty/deepseek_vl2/models/modeling_deepseek.py +1975 -0
- xinference/thirdparty/deepseek_vl2/models/modeling_deepseek_vl_v2.py +697 -0
- xinference/thirdparty/deepseek_vl2/models/processing_deepseek_vl_v2.py +675 -0
- xinference/thirdparty/deepseek_vl2/models/siglip_vit.py +661 -0
- xinference/thirdparty/deepseek_vl2/serve/__init__.py +0 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/__init__.py +0 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/gradio_utils.py +83 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/overwrites.py +81 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/presets.py +115 -0
- xinference/thirdparty/deepseek_vl2/serve/app_modules/utils.py +333 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/Kelpy-Codos.js +100 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/avatar.png +0 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/custom.css +355 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/custom.js +22 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/favicon.ico +0 -0
- xinference/thirdparty/deepseek_vl2/serve/assets/simsun.ttc +0 -0
- xinference/thirdparty/deepseek_vl2/serve/inference.py +197 -0
- xinference/thirdparty/deepseek_vl2/utils/__init__.py +18 -0
- xinference/thirdparty/deepseek_vl2/utils/io.py +80 -0
- xinference/types.py +2 -2
- xinference/web/ui/build/asset-manifest.json +6 -6
- xinference/web/ui/build/index.html +1 -1
- xinference/web/ui/build/static/css/main.b494ae7e.css +2 -0
- xinference/web/ui/build/static/css/main.b494ae7e.css.map +1 -0
- xinference/web/ui/build/static/js/main.5ca4eea1.js +3 -0
- xinference/web/ui/build/static/js/main.5ca4eea1.js.map +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/0f0967acaec5df1d45b80010949c258d64297ebbb0f44b8bb3afcbd45c6f0ec4.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/68249645124f37d01eef83b1d897e751f895bea919b6fb466f907c1f87cebc84.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/cc97b49285d7717c63374766c789141a4329a04582ab32756d7e0e614d4c5c7f.json +1 -0
- xinference/web/ui/node_modules/.cache/babel-loader/f199e8173f6409a5802ed44acb95f218388131136504b2e9132129e150c92f9a.json +1 -0
- xinference/web/ui/src/locales/en.json +2 -2
- xinference/web/ui/src/locales/zh.json +1 -1
- {xinference-1.3.1.post1.dist-info → xinference-1.4.1.dist-info}/METADATA +4 -4
- {xinference-1.3.1.post1.dist-info → xinference-1.4.1.dist-info}/RECORD +67 -41
- xinference/web/ui/build/static/css/main.f8177338.css +0 -2
- xinference/web/ui/build/static/css/main.f8177338.css.map +0 -1
- xinference/web/ui/build/static/js/main.55b70cb7.js +0 -3
- xinference/web/ui/build/static/js/main.55b70cb7.js.map +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/2deac8d5636974533e3714f34e94fc754f9153a07c6ee11e72846cb8eae47e4b.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/db16a983bc08a05f0439cc61ca0840e49e1d8400eef678909f16c032a418a3d6.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/e23d476fcbf6fd69c8986bf82133d257d28aa8fc9a5cab231d81c1c75c58cd99.json +0 -1
- xinference/web/ui/node_modules/.cache/babel-loader/e7a8c37fda8725cab69c7ef8c627060bd7fc806adc67e00fe628ba148cb86d7f.json +0 -1
- /xinference/web/ui/build/static/js/{main.55b70cb7.js.LICENSE.txt → main.5ca4eea1.js.LICENSE.txt} +0 -0
- {xinference-1.3.1.post1.dist-info → xinference-1.4.1.dist-info}/LICENSE +0 -0
- {xinference-1.3.1.post1.dist-info → xinference-1.4.1.dist-info}/WHEEL +0 -0
- {xinference-1.3.1.post1.dist-info → xinference-1.4.1.dist-info}/entry_points.txt +0 -0
- {xinference-1.3.1.post1.dist-info → xinference-1.4.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# Copyright 2022-2025 XProbe Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
from functools import partial
|
|
19
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
|
|
20
|
+
|
|
21
|
+
import xoscar as xo
|
|
22
|
+
from vllm.executor.executor_base import DistributedExecutorBase
|
|
23
|
+
from vllm.utils import _run_task_with_lock, get_distributed_init_method
|
|
24
|
+
from vllm.worker.worker_base import WorkerWrapperBase
|
|
25
|
+
from xoscar.utils import get_next_port
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from vllm.config import VllmConfig
|
|
29
|
+
from vllm.model_executor.layers.sampler import SamplerOutput
|
|
30
|
+
from vllm.sequence import ExecuteModelRequest
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class WorkerActor(xo.StatelessActor):
|
|
36
|
+
def __init__(self, vllm_config: "VllmConfig", rpc_rank: int = 0, **kwargs):
|
|
37
|
+
super().__init__(**kwargs)
|
|
38
|
+
self._worker = WorkerWrapperBase(vllm_config, rpc_rank=rpc_rank)
|
|
39
|
+
|
|
40
|
+
async def __post_create__(self):
|
|
41
|
+
try:
|
|
42
|
+
# Change process title for model
|
|
43
|
+
import setproctitle
|
|
44
|
+
|
|
45
|
+
setproctitle.setproctitle(f"Xinf vLLM worker: {self._worker.rpc_rank}")
|
|
46
|
+
except ImportError:
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
def __getattr__(self, item):
|
|
50
|
+
return getattr(self._worker, item)
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def gen_uid(cls, rank):
|
|
54
|
+
return f"VllmWorker_{rank}"
|
|
55
|
+
|
|
56
|
+
def execute_method(self, method: Union[str, Callable], *args, **kwargs):
|
|
57
|
+
logger.debug(
|
|
58
|
+
"Calling method %s in vllm worker %s, args: %s, kwargs: %s",
|
|
59
|
+
method,
|
|
60
|
+
self.uid,
|
|
61
|
+
args,
|
|
62
|
+
kwargs,
|
|
63
|
+
)
|
|
64
|
+
if isinstance(method, str):
|
|
65
|
+
return getattr(self._worker, method)(*args, **kwargs)
|
|
66
|
+
else:
|
|
67
|
+
return method(self._worker, *args, **kwargs)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class WorkerWrapper:
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
loop: asyncio.AbstractEventLoop,
|
|
74
|
+
worker_actor_ref: xo.ActorRefType[WorkerActor],
|
|
75
|
+
):
|
|
76
|
+
self._loop = loop
|
|
77
|
+
self._worker_actor_ref = worker_actor_ref
|
|
78
|
+
|
|
79
|
+
def execute_method(self, method: Union[str, Callable], *args, **kwargs):
|
|
80
|
+
coro = self._worker_actor_ref.execute_method(method, *args, **kwargs)
|
|
81
|
+
return asyncio.run_coroutine_threadsafe(coro, self._loop)
|
|
82
|
+
|
|
83
|
+
async def execute_method_async(self, method: Union[str, Callable], *args, **kwargs):
|
|
84
|
+
return await self._worker_actor_ref.execute_method(method, *args, **kwargs)
|
|
85
|
+
|
|
86
|
+
def kill(self):
|
|
87
|
+
coro = xo.kill_actor(self._worker_actor_ref)
|
|
88
|
+
return asyncio.run_coroutine_threadsafe(coro, self._loop)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class XinferenceDistributedExecutor(DistributedExecutorBase):
|
|
92
|
+
"""Xoscar based distributed executor"""
|
|
93
|
+
|
|
94
|
+
use_ray: bool = False
|
|
95
|
+
_loop: asyncio.AbstractEventLoop
|
|
96
|
+
_pool_addresses: List[str]
|
|
97
|
+
_n_worker: int
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
vllm_config: "VllmConfig",
|
|
102
|
+
pool_addresses: List[str],
|
|
103
|
+
n_worker: int,
|
|
104
|
+
loop: asyncio.AbstractEventLoop,
|
|
105
|
+
*args,
|
|
106
|
+
**kwargs,
|
|
107
|
+
):
|
|
108
|
+
self._pool_addresses = pool_addresses
|
|
109
|
+
self._loop = loop
|
|
110
|
+
self._n_worker = n_worker
|
|
111
|
+
super().__init__(vllm_config, *args, **kwargs)
|
|
112
|
+
|
|
113
|
+
def _init_executor(self) -> None:
|
|
114
|
+
# Create the parallel GPU workers.
|
|
115
|
+
world_size = self.parallel_config.world_size
|
|
116
|
+
tensor_parallel_size = self.parallel_config.tensor_parallel_size
|
|
117
|
+
|
|
118
|
+
self.driver_worker: Optional[WorkerActor] = None
|
|
119
|
+
# The remaining workers are Xoscar actors
|
|
120
|
+
self.workers: List[WorkerWrapper] = []
|
|
121
|
+
|
|
122
|
+
assert (
|
|
123
|
+
self._pool_addresses and len(self._pool_addresses) == world_size
|
|
124
|
+
), f"Pool addresses(#{len(self._pool_addresses or [])} must be equal to worldsize(#{world_size})"
|
|
125
|
+
|
|
126
|
+
futures = []
|
|
127
|
+
for rank in range(world_size):
|
|
128
|
+
coro = xo.create_actor(
|
|
129
|
+
WorkerActor,
|
|
130
|
+
self.vllm_config,
|
|
131
|
+
rpc_rank=rank,
|
|
132
|
+
address=self._pool_addresses[rank],
|
|
133
|
+
uid=WorkerActor.gen_uid(rank),
|
|
134
|
+
)
|
|
135
|
+
futures.append(asyncio.run_coroutine_threadsafe(coro, self._loop))
|
|
136
|
+
refs = [fut.result() for fut in futures]
|
|
137
|
+
self.workers = [WorkerWrapper(self._loop, ref) for ref in refs[1:]]
|
|
138
|
+
self.driver_worker = WorkerActor(self.vllm_config, rpc_rank=0)
|
|
139
|
+
|
|
140
|
+
def driver_execute_method(*args, **kwargs):
|
|
141
|
+
func = partial(self.driver_worker.execute_method, *args, **kwargs)
|
|
142
|
+
return self._loop.run_in_executor(None, func)
|
|
143
|
+
|
|
144
|
+
self.driver_exec_method = driver_execute_method
|
|
145
|
+
|
|
146
|
+
# Set environment variables for the driver and workers.
|
|
147
|
+
all_args_to_update_environment_variables: List[Dict[str, str]] = [
|
|
148
|
+
dict() for _ in range(world_size)
|
|
149
|
+
]
|
|
150
|
+
|
|
151
|
+
for args in all_args_to_update_environment_variables:
|
|
152
|
+
# some carry-over env vars from the driver
|
|
153
|
+
# TODO: refactor platform-specific env vars
|
|
154
|
+
for name in [
|
|
155
|
+
"VLLM_ATTENTION_BACKEND",
|
|
156
|
+
"TPU_CHIPS_PER_HOST_BOUNDS",
|
|
157
|
+
"TPU_HOST_BOUNDS",
|
|
158
|
+
"VLLM_USE_V1",
|
|
159
|
+
"VLLM_TRACE_FUNCTION",
|
|
160
|
+
]:
|
|
161
|
+
if name in os.environ:
|
|
162
|
+
args[name] = os.environ[name]
|
|
163
|
+
|
|
164
|
+
self._env_vars_for_all_workers = all_args_to_update_environment_variables
|
|
165
|
+
|
|
166
|
+
self._run_workers(
|
|
167
|
+
"update_environment_variables", self._env_vars_for_all_workers
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
all_kwargs = []
|
|
171
|
+
distributed_init_method = get_distributed_init_method(
|
|
172
|
+
self._pool_addresses[0].split(":", 1)[0], get_next_port()
|
|
173
|
+
)
|
|
174
|
+
for rank in range(world_size):
|
|
175
|
+
local_rank = rank % (world_size // self._n_worker)
|
|
176
|
+
kwargs = dict(
|
|
177
|
+
vllm_config=self.vllm_config,
|
|
178
|
+
local_rank=local_rank,
|
|
179
|
+
rank=rank,
|
|
180
|
+
distributed_init_method=distributed_init_method,
|
|
181
|
+
is_driver_worker=not self.parallel_config
|
|
182
|
+
or (rank % tensor_parallel_size == 0),
|
|
183
|
+
)
|
|
184
|
+
all_kwargs.append(kwargs)
|
|
185
|
+
self._run_workers("init_worker", all_kwargs)
|
|
186
|
+
self._run_workers("init_device")
|
|
187
|
+
self._run_workers(
|
|
188
|
+
"load_model",
|
|
189
|
+
max_concurrent_workers=self.parallel_config.max_parallel_loading_workers,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
# This is the list of workers that are rank 0 of each TP group EXCEPT
|
|
193
|
+
# global rank 0. These are the workers that will broadcast to the
|
|
194
|
+
# rest of the workers.
|
|
195
|
+
self.tp_driver_workers: List[WorkerWrapper] = []
|
|
196
|
+
# This is the list of workers that are not drivers and not the first
|
|
197
|
+
# worker in a TP group. These are the workers that will be
|
|
198
|
+
# broadcasted to.
|
|
199
|
+
self.non_driver_workers: List[WorkerWrapper] = []
|
|
200
|
+
|
|
201
|
+
# Enforce rank order for correct rank to return final output.
|
|
202
|
+
for index, worker in enumerate(self.workers):
|
|
203
|
+
# The driver worker is rank 0 and not in self.workers.
|
|
204
|
+
rank = index + 1
|
|
205
|
+
if rank % self.parallel_config.tensor_parallel_size == 0:
|
|
206
|
+
self.tp_driver_workers.append(worker)
|
|
207
|
+
else:
|
|
208
|
+
self.non_driver_workers.append(worker)
|
|
209
|
+
|
|
210
|
+
self.pp_locks: Optional[List[asyncio.Lock]] = None
|
|
211
|
+
|
|
212
|
+
def _run_workers(
|
|
213
|
+
self,
|
|
214
|
+
method: Union[str, Callable],
|
|
215
|
+
*args,
|
|
216
|
+
async_run_tensor_parallel_workers_only: bool = False,
|
|
217
|
+
max_concurrent_workers: Optional[int] = None,
|
|
218
|
+
**kwargs,
|
|
219
|
+
) -> Any:
|
|
220
|
+
if max_concurrent_workers:
|
|
221
|
+
raise NotImplementedError("max_concurrent_workers is not supported yet.")
|
|
222
|
+
|
|
223
|
+
workers = self.workers
|
|
224
|
+
if async_run_tensor_parallel_workers_only:
|
|
225
|
+
workers = self.non_driver_workers
|
|
226
|
+
worker_outputs = [
|
|
227
|
+
worker.execute_method(method, *args, **kwargs) for worker in workers
|
|
228
|
+
]
|
|
229
|
+
|
|
230
|
+
if async_run_tensor_parallel_workers_only:
|
|
231
|
+
return worker_outputs
|
|
232
|
+
|
|
233
|
+
driver_worker_outputs = [
|
|
234
|
+
self.driver_worker.execute_method(method, *args, **kwargs) # type: ignore
|
|
235
|
+
]
|
|
236
|
+
return driver_worker_outputs + [output.result() for output in worker_outputs]
|
|
237
|
+
|
|
238
|
+
def _wait_for_tasks_completion(self, parallel_worker_tasks: Any) -> None:
|
|
239
|
+
"""Wait for futures returned from _run_workers() with
|
|
240
|
+
async_run_remote_workers_only to complete."""
|
|
241
|
+
for result in parallel_worker_tasks:
|
|
242
|
+
result.get()
|
|
243
|
+
|
|
244
|
+
def check_health(self) -> None:
|
|
245
|
+
# Assume that the workers are healthy.
|
|
246
|
+
# TODO: check the health by checking if the workers all alive
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
def shutdown(self) -> None:
|
|
250
|
+
try:
|
|
251
|
+
futs = [worker.kill() for worker in self.workers]
|
|
252
|
+
_ = [fut.result() for fut in futs]
|
|
253
|
+
except (RuntimeError, ConnectionError):
|
|
254
|
+
# event loop closed already, ignore
|
|
255
|
+
pass
|
|
256
|
+
|
|
257
|
+
def __del__(self):
|
|
258
|
+
return self.shutdown()
|
|
259
|
+
|
|
260
|
+
def _driver_execute_model(
|
|
261
|
+
self, execute_model_req: Optional["ExecuteModelRequest"]
|
|
262
|
+
) -> Optional[List["SamplerOutput"]]:
|
|
263
|
+
return self.driver_worker.execute_method("execute_model", execute_model_req) # type: ignore
|
|
264
|
+
|
|
265
|
+
async def _driver_execute_model_async(
|
|
266
|
+
self,
|
|
267
|
+
execute_model_req: Optional["ExecuteModelRequest"] = None,
|
|
268
|
+
) -> List["SamplerOutput"]:
|
|
269
|
+
if not self.tp_driver_workers:
|
|
270
|
+
return await self.driver_exec_method("execute_model", execute_model_req)
|
|
271
|
+
|
|
272
|
+
if self.pp_locks is None:
|
|
273
|
+
# This locks each pipeline parallel stage so multiple virtual
|
|
274
|
+
# engines can't execute on the same stage at the same time
|
|
275
|
+
# We create the locks here to avoid creating them in the constructor
|
|
276
|
+
# which uses a different asyncio loop.
|
|
277
|
+
self.pp_locks = [
|
|
278
|
+
asyncio.Lock()
|
|
279
|
+
for _ in range(self.parallel_config.pipeline_parallel_size)
|
|
280
|
+
]
|
|
281
|
+
|
|
282
|
+
tasks = [
|
|
283
|
+
asyncio.create_task(
|
|
284
|
+
_run_task_with_lock(
|
|
285
|
+
self.driver_exec_method,
|
|
286
|
+
self.pp_locks[0],
|
|
287
|
+
"execute_model",
|
|
288
|
+
execute_model_req,
|
|
289
|
+
)
|
|
290
|
+
)
|
|
291
|
+
]
|
|
292
|
+
for pp_rank, driver_worker in enumerate(self.tp_driver_workers, start=1):
|
|
293
|
+
tasks.append(
|
|
294
|
+
asyncio.create_task(
|
|
295
|
+
_run_task_with_lock(
|
|
296
|
+
driver_worker.execute_method_async,
|
|
297
|
+
self.pp_locks[pp_rank],
|
|
298
|
+
"execute_model",
|
|
299
|
+
execute_model_req,
|
|
300
|
+
)
|
|
301
|
+
)
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
results = await asyncio.gather(*tasks)
|
|
305
|
+
|
|
306
|
+
# Only the last PP stage has the final results.
|
|
307
|
+
return results[-1]
|
|
308
|
+
|
|
309
|
+
async def _start_worker_execution_loop(self):
|
|
310
|
+
coros = [
|
|
311
|
+
worker.execute_method_async("start_worker_execution_loop")
|
|
312
|
+
for worker in self.non_driver_workers
|
|
313
|
+
]
|
|
314
|
+
return await asyncio.gather(*coros)
|
xinference/model/rerank/core.py
CHANGED
|
@@ -106,9 +106,10 @@ def generate_rerank_description(model_spec: RerankModelSpec) -> Dict[str, List[D
|
|
|
106
106
|
return res
|
|
107
107
|
|
|
108
108
|
|
|
109
|
-
class _ModelWrapper:
|
|
109
|
+
class _ModelWrapper(nn.Module):
|
|
110
110
|
def __init__(self, module: nn.Module):
|
|
111
|
-
|
|
111
|
+
super().__init__()
|
|
112
|
+
self.model = module
|
|
112
113
|
self._local_data = threading.local()
|
|
113
114
|
|
|
114
115
|
@property
|
|
@@ -116,18 +117,22 @@ class _ModelWrapper:
|
|
|
116
117
|
return getattr(self._local_data, "n_tokens", 0)
|
|
117
118
|
|
|
118
119
|
@n_tokens.setter
|
|
119
|
-
def n_tokens(self,
|
|
120
|
-
self._local_data.n_tokens =
|
|
120
|
+
def n_tokens(self, value):
|
|
121
|
+
self._local_data.n_tokens = value
|
|
121
122
|
|
|
122
|
-
def
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def __call__(self, **kwargs):
|
|
126
|
-
attention_mask = kwargs["attention_mask"]
|
|
123
|
+
def forward(self, **kwargs):
|
|
124
|
+
attention_mask = kwargs.get("attention_mask")
|
|
127
125
|
# when batching, the attention mask 1 means there is a token
|
|
128
126
|
# thus we just sum up it to get the total number of tokens
|
|
129
|
-
|
|
130
|
-
|
|
127
|
+
if attention_mask is not None:
|
|
128
|
+
self.n_tokens += attention_mask.sum().item()
|
|
129
|
+
return self.model(**kwargs)
|
|
130
|
+
|
|
131
|
+
def __getattr__(self, attr):
|
|
132
|
+
try:
|
|
133
|
+
return super().__getattr__(attr)
|
|
134
|
+
except AttributeError:
|
|
135
|
+
return getattr(self.model, attr)
|
|
131
136
|
|
|
132
137
|
|
|
133
138
|
class RerankModel:
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Copyright (c) 2023-2024 DeepSeek.
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
4
|
+
# this software and associated documentation files (the "Software"), to deal in
|
|
5
|
+
# the Software without restriction, including without limitation the rights to
|
|
6
|
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
7
|
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
|
8
|
+
# subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
# copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
15
|
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
16
|
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
18
|
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# check if python version is above 3.10
|
|
22
|
+
import sys
|
|
23
|
+
|
|
24
|
+
if sys.version_info >= (3, 10):
|
|
25
|
+
print("Python version is above 3.10, patching the collections module.")
|
|
26
|
+
# Monkey patch collections
|
|
27
|
+
import collections
|
|
28
|
+
import collections.abc
|
|
29
|
+
|
|
30
|
+
for type_name in collections.abc.__all__:
|
|
31
|
+
setattr(collections, type_name, getattr(collections.abc, type_name))
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Copyright (c) 2023-2024 DeepSeek.
|
|
2
|
+
#
|
|
3
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
4
|
+
# this software and associated documentation files (the "Software"), to deal in
|
|
5
|
+
# the Software without restriction, including without limitation the rights to
|
|
6
|
+
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
7
|
+
# the Software, and to permit persons to whom the Software is furnished to do so,
|
|
8
|
+
# subject to the following conditions:
|
|
9
|
+
#
|
|
10
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
# copies or substantial portions of the Software.
|
|
12
|
+
#
|
|
13
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
15
|
+
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
16
|
+
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
18
|
+
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
20
|
+
from .processing_deepseek_vl_v2 import DeepseekVLV2Processor
|
|
21
|
+
from .modeling_deepseek_vl_v2 import DeepseekVLV2ForCausalLM
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"DeepseekVLV2Processor",
|
|
25
|
+
"DeepseekVLV2ForCausalLM",
|
|
26
|
+
]
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
from transformers.configuration_utils import PretrainedConfig
|
|
2
|
+
from transformers.utils import logging
|
|
3
|
+
|
|
4
|
+
logger = logging.get_logger(__name__)
|
|
5
|
+
|
|
6
|
+
DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
|
7
|
+
class DeepseekV2Config(PretrainedConfig):
|
|
8
|
+
r"""
|
|
9
|
+
This is the configuration class to store the configuration of a [`DeepseekV2Model`]. It is used to instantiate an DeepSeek
|
|
10
|
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
|
11
|
+
defaults will yield a similar configuration to that of the DeepSeek-V2 with multi-latent attention.
|
|
12
|
+
|
|
13
|
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
|
14
|
+
documentation from [`PretrainedConfig`] for more information.
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
vocab_size (`int`, *optional*, defaults to 102400):
|
|
19
|
+
Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
|
|
20
|
+
`inputs_ids` passed when calling [`DeepseekV2Model`]
|
|
21
|
+
hidden_size (`int`, *optional*, defaults to 4096):
|
|
22
|
+
Dimension of the hidden representations.
|
|
23
|
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
|
24
|
+
Dimension of the MLP representations.
|
|
25
|
+
moe_intermediate_size (`int`, *optional*, defaults to 1407):
|
|
26
|
+
Dimension of the MoE representations.
|
|
27
|
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
|
28
|
+
Number of hidden layers in the Transformer decoder.
|
|
29
|
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
|
30
|
+
Number of attention heads for each attention layer in the Transformer decoder.
|
|
31
|
+
n_shared_experts (`int`, *optional*, defaults to None):
|
|
32
|
+
Number of shared experts, None means dense model.
|
|
33
|
+
n_routed_experts (`int`, *optional*, defaults to None):
|
|
34
|
+
Number of routed experts, None means dense model.
|
|
35
|
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
|
36
|
+
Scaling factor or routed experts.
|
|
37
|
+
topk_method (`str`, *optional*, defaults to `gready`):
|
|
38
|
+
Topk method used in routed gate.
|
|
39
|
+
n_group (`int`, *optional*, defaults to None):
|
|
40
|
+
Number of groups for routed experts.
|
|
41
|
+
topk_group (`int`, *optional*, defaults to None):
|
|
42
|
+
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
|
43
|
+
num_experts_per_tok (`int`, *optional*, defaults to None):
|
|
44
|
+
Number of selected experts, None means dense model.
|
|
45
|
+
moe_layer_freq (`int`, *optional*, defaults to 1):
|
|
46
|
+
The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
|
|
47
|
+
first_k_dense_replace (`int`, *optional*, defaults to 0):
|
|
48
|
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
|
49
|
+
\--k dense layers--/
|
|
50
|
+
norm_topk_prob (`bool`, *optional*, defaults to False):
|
|
51
|
+
Whether to normalize the weights of the routed experts.
|
|
52
|
+
scoring_func (`str`, *optional*, defaults to 'softmax'):
|
|
53
|
+
Method of computing expert weights.
|
|
54
|
+
aux_loss_alpha (`float`, *optional*, defaults to 0.001):
|
|
55
|
+
Auxiliary loss weight coefficient.
|
|
56
|
+
seq_aux = (`bool`, *optional*, defaults to True):
|
|
57
|
+
Whether to compute the auxiliary loss for each individual sample.
|
|
58
|
+
num_key_value_heads (`int`, *optional*):
|
|
59
|
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
|
60
|
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
|
61
|
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
|
62
|
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
|
63
|
+
by meanpooling all the original heads within that group. For more details checkout [this
|
|
64
|
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
|
65
|
+
`num_attention_heads`.
|
|
66
|
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
|
67
|
+
The non-linear activation function (function or string) in the decoder.
|
|
68
|
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
|
69
|
+
The maximum sequence length that this model might ever be used with.
|
|
70
|
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
|
71
|
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
|
72
|
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
|
73
|
+
The epsilon used by the rms normalization layers.
|
|
74
|
+
use_cache (`bool`, *optional*, defaults to `True`):
|
|
75
|
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
|
76
|
+
relevant if `config.is_decoder=True`.
|
|
77
|
+
pad_token_id (`int`, *optional*):
|
|
78
|
+
Padding token id.
|
|
79
|
+
bos_token_id (`int`, *optional*, defaults to 1):
|
|
80
|
+
Beginning of stream token id.
|
|
81
|
+
eos_token_id (`int`, *optional*, defaults to 2):
|
|
82
|
+
End of stream token id.
|
|
83
|
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
|
84
|
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
|
85
|
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
|
86
|
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
|
87
|
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
|
88
|
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
|
89
|
+
Whether to tie weight embeddings
|
|
90
|
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
|
91
|
+
The base period of the RoPE embeddings.
|
|
92
|
+
rope_scaling (`Dict`, *optional*):
|
|
93
|
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
|
94
|
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
|
95
|
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
|
96
|
+
`max_position_embeddings` to the expected new maximum.
|
|
97
|
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
|
98
|
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
|
99
|
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
|
100
|
+
The dropout ratio for the attention probabilities.
|
|
101
|
+
use_mla (`bool`, *optional*, defaults to `True`): Use multi-latent attention or multi-head attention. If True,
|
|
102
|
+
the model will use multi-latent attention, otherwise, it will use multi-head attention.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
>>> from transformers import DeepseekV2Model, DeepseekV2Config
|
|
106
|
+
|
|
107
|
+
>>> # Initializing a Deepseek-V2 style configuration
|
|
108
|
+
>>> configuration = DeepseekV2Config()
|
|
109
|
+
|
|
110
|
+
>>> # Accessing the model configuration
|
|
111
|
+
>>> configuration = model.config
|
|
112
|
+
```"""
|
|
113
|
+
|
|
114
|
+
model_type = "deepseek_v2"
|
|
115
|
+
keys_to_ignore_at_inference = ["past_key_values"]
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
vocab_size=102400,
|
|
120
|
+
hidden_size=4096,
|
|
121
|
+
intermediate_size=11008,
|
|
122
|
+
moe_intermediate_size = 1407,
|
|
123
|
+
num_hidden_layers=30,
|
|
124
|
+
num_attention_heads=32,
|
|
125
|
+
num_key_value_heads=32,
|
|
126
|
+
n_shared_experts = None,
|
|
127
|
+
n_routed_experts = None,
|
|
128
|
+
ep_size = 1,
|
|
129
|
+
routed_scaling_factor = 1.0,
|
|
130
|
+
kv_lora_rank = 512,
|
|
131
|
+
q_lora_rank = 1536,
|
|
132
|
+
qk_rope_head_dim = 64,
|
|
133
|
+
v_head_dim = 128,
|
|
134
|
+
qk_nope_head_dim = 128,
|
|
135
|
+
topk_method = 'gready',
|
|
136
|
+
n_group = None,
|
|
137
|
+
topk_group = None,
|
|
138
|
+
num_experts_per_tok = None,
|
|
139
|
+
moe_layer_freq = 1,
|
|
140
|
+
first_k_dense_replace = 0,
|
|
141
|
+
norm_topk_prob = False,
|
|
142
|
+
scoring_func = 'softmax',
|
|
143
|
+
aux_loss_alpha = 0.001,
|
|
144
|
+
seq_aux = True,
|
|
145
|
+
hidden_act="silu",
|
|
146
|
+
max_position_embeddings=2048,
|
|
147
|
+
initializer_range=0.02,
|
|
148
|
+
rms_norm_eps=1e-6,
|
|
149
|
+
use_cache=True,
|
|
150
|
+
pad_token_id=None,
|
|
151
|
+
bos_token_id=100000,
|
|
152
|
+
eos_token_id=100001,
|
|
153
|
+
pretraining_tp=1,
|
|
154
|
+
tie_word_embeddings=False,
|
|
155
|
+
rope_theta=10000.0,
|
|
156
|
+
rope_scaling=None,
|
|
157
|
+
attention_bias=False,
|
|
158
|
+
attention_dropout=0.0,
|
|
159
|
+
use_mla=True,
|
|
160
|
+
**kwargs,
|
|
161
|
+
):
|
|
162
|
+
self.vocab_size = vocab_size
|
|
163
|
+
self.max_position_embeddings = max_position_embeddings
|
|
164
|
+
self.hidden_size = hidden_size
|
|
165
|
+
self.intermediate_size = intermediate_size
|
|
166
|
+
self.moe_intermediate_size = moe_intermediate_size
|
|
167
|
+
self.num_hidden_layers = num_hidden_layers
|
|
168
|
+
self.num_attention_heads = num_attention_heads
|
|
169
|
+
self.n_shared_experts = n_shared_experts
|
|
170
|
+
self.n_routed_experts = n_routed_experts
|
|
171
|
+
self.ep_size = ep_size
|
|
172
|
+
self.routed_scaling_factor = routed_scaling_factor
|
|
173
|
+
self.kv_lora_rank = kv_lora_rank
|
|
174
|
+
self.q_lora_rank = q_lora_rank
|
|
175
|
+
self.qk_rope_head_dim = qk_rope_head_dim
|
|
176
|
+
self.v_head_dim = v_head_dim
|
|
177
|
+
self.qk_nope_head_dim = qk_nope_head_dim
|
|
178
|
+
self.topk_method = topk_method
|
|
179
|
+
self.n_group = n_group
|
|
180
|
+
self.topk_group = topk_group
|
|
181
|
+
self.num_experts_per_tok = num_experts_per_tok
|
|
182
|
+
self.moe_layer_freq = moe_layer_freq
|
|
183
|
+
self.first_k_dense_replace = first_k_dense_replace
|
|
184
|
+
self.norm_topk_prob = norm_topk_prob
|
|
185
|
+
self.scoring_func = scoring_func
|
|
186
|
+
self.aux_loss_alpha = aux_loss_alpha
|
|
187
|
+
self.seq_aux = seq_aux
|
|
188
|
+
# for backward compatibility
|
|
189
|
+
if num_key_value_heads is None:
|
|
190
|
+
num_key_value_heads = num_attention_heads
|
|
191
|
+
|
|
192
|
+
self.num_key_value_heads = num_key_value_heads
|
|
193
|
+
self.hidden_act = hidden_act
|
|
194
|
+
self.initializer_range = initializer_range
|
|
195
|
+
self.rms_norm_eps = float(rms_norm_eps)
|
|
196
|
+
self.pretraining_tp = pretraining_tp
|
|
197
|
+
self.use_cache = use_cache
|
|
198
|
+
self.rope_theta = rope_theta
|
|
199
|
+
self.rope_scaling = rope_scaling
|
|
200
|
+
self.attention_bias = attention_bias
|
|
201
|
+
self.attention_dropout = attention_dropout
|
|
202
|
+
self.use_mla = use_mla
|
|
203
|
+
|
|
204
|
+
super().__init__(
|
|
205
|
+
pad_token_id=pad_token_id,
|
|
206
|
+
bos_token_id=bos_token_id,
|
|
207
|
+
eos_token_id=eos_token_id,
|
|
208
|
+
tie_word_embeddings=tie_word_embeddings,
|
|
209
|
+
**kwargs,
|
|
210
|
+
)
|