id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
8,084
import os.path as osp import sys import torch import lmdeploy from ..source_model.base import BaseInputModel, BaseReader from .base import (OUTPUT_MODELS, BaseOutputModel, TurbomindModelConfig, merge_qkv, permute) import _turbomind as _tm def permute(x: torch.Tensor, size_per_head: int = 128): def tp_m_s4(x: torch.Tensor, tp: int): return x.view(x.size(0) // 32, tp, -1, 128).permute(0, 2, 3, 1).contiguous()
null
8,085
import os.path as osp import sys import torch import lmdeploy from ..source_model.base import BaseInputModel, BaseReader from .base import (OUTPUT_MODELS, BaseOutputModel, TurbomindModelConfig, merge_qkv, permute) import _turbomind as _tm The provided code snippet includes necessary dependencies for implementing the `get_cuda_tensor` function. Write a Python function `def get_cuda_tensor(tensors)` to solve the following problem: Get cuda tensor. Here is the function: def get_cuda_tensor(tensors): """Get cuda tensor.""" result = map(lambda x: x.cuda() if x is not None else x, tensors) return (*result, )
Get cuda tensor.
8,086
import json import os.path as osp from pathlib import Path import torch from sentencepiece import SentencePieceProcessor from .base import INPUT_MODELS, BaseInputModel, BaseReader The provided code snippet includes necessary dependencies for implementing the `reverse_permute` function. Write a Python function `def reverse_permute(x: torch.Tensor, size_per_head: int = 128)` to solve the following problem: reverse permute to hf format. Here is the function: def reverse_permute(x: torch.Tensor, size_per_head: int = 128): """reverse permute to hf format.""" if x.shape[-1] > 1: dim = x.shape[-1] n_heads = dim // size_per_head return x.view(-1, n_heads, dim // n_heads // 2, 2).transpose(2, 3).reshape(-1, dim) else: # scales, zeros dim = x.shape[0] n_heads = dim // size_per_head return x.view(n_heads, dim // n_heads // 2, 2, 1).transpose(1, 2).reshape(dim, 1)
reverse permute to hf format.
8,087
import torch from .base import INPUT_MODELS from .llama import LlamaModel, LlamaReader The provided code snippet includes necessary dependencies for implementing the `ensure_fp16orint32` function. Write a Python function `def ensure_fp16orint32(tensors: torch.Tensor)` to solve the following problem: Ensure tensors in fp16/int32 format. Here is the function: def ensure_fp16orint32(tensors: torch.Tensor): """Ensure tensors in fp16/int32 format.""" result = [] for tensor in tensors: if tensor is not None: if tensor.dtype in [torch.float16, torch.float32, torch.bfloat16]: result.append(tensor.half()) else: assert tensor.dtype == torch.int32 result.append(tensor) else: result.append(None) return (*result, )
Ensure tensors in fp16/int32 format.
8,088
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig The provided code snippet includes necessary dependencies for implementing the `get_tokenizer_path` function. Write a Python function `def get_tokenizer_path(model_path: str, tokenizer_path: str)` to solve the following problem: Get tokenizer path if not given. Here is the function: def get_tokenizer_path(model_path: str, tokenizer_path: str): """Get tokenizer path if not given.""" if tokenizer_path is not None: assert osp.exists(tokenizer_path), f'{tokenizer_path} does not exists.' return tokenizer_path candidate = ['tokenizer.model', 'qwen.tiktoken'] for name in candidate: tmp_path = osp.join(model_path, name) if osp.exists(tmp_path): tokenizer_path = tmp_path break assert tokenizer_path, 'please supply tokenizer path by --tokenizer-path' return tokenizer_path
Get tokenizer path if not given.
8,089
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig The provided code snippet includes necessary dependencies for implementing the `create_workspace` function. Write a Python function `def create_workspace(_path: str)` to solve the following problem: Create a workspace. Args: _path (str): the path of the workspace Here is the function: def create_workspace(_path: str): """Create a workspace. Args: _path (str): the path of the workspace """ if osp.exists(_path): print(f'remove workspace in directory {_path}') shutil.rmtree(_path) print(f'create workspace in directory {_path}') os.makedirs(_path)
Create a workspace. Args: _path (str): the path of the workspace
8,090
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig def get_package_root_path(): """Get lmdeploy root path.""" import lmdeploy return Path(lmdeploy.__file__).parent The provided code snippet includes necessary dependencies for implementing the `copy_triton_model_templates` function. Write a Python function `def copy_triton_model_templates(_path: str)` to solve the following problem: copy triton model templates to the specified path. Args: _path (str): the target path Returns: str: the path of the triton models Here is the function: def copy_triton_model_templates(_path: str): """copy triton model templates to the specified path. Args: _path (str): the target path Returns: str: the path of the triton models """ root = get_package_root_path() dir_path = osp.join(root, 'serve', 'turbomind') triton_models_path = osp.join(dir_path, 'triton_models') dst_path = osp.join(_path, 'triton_models') print(f'copy triton model templates from "{triton_models_path}" to ' f'"{dst_path}"') shutil.copytree(triton_models_path, dst_path, symlinks=True) service_docker_up_file = osp.join(dir_path, 'service_docker_up.sh') print(f'copy service_docker_up.sh from "{service_docker_up_file}" to ' f'"{_path}"') shutil.copy(osp.join(dir_path, 'service_docker_up.sh'), _path) return dst_path
copy triton model templates to the specified path. Args: _path (str): the target path Returns: str: the path of the triton models
8,091
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig def get_package_root_path(): """Get lmdeploy root path.""" import lmdeploy return Path(lmdeploy.__file__).parent The provided code snippet includes necessary dependencies for implementing the `copy_tokenizer` function. Write a Python function `def copy_tokenizer(model_path: str, tokenizer_path: str, triton_models_path: str)` to solve the following problem: Copy tokenizer. Here is the function: def copy_tokenizer(model_path: str, tokenizer_path: str, triton_models_path: str): """Copy tokenizer.""" shutil.copy( tokenizer_path, osp.join(triton_models_path, osp.join('tokenizer', osp.basename(tokenizer_path)))) for _file in os.listdir(model_path): if _file.endswith('.json') or _file.endswith('.py'): json_path = osp.join(model_path, _file) shutil.copy(json_path, osp.join(triton_models_path, 'tokenizer', _file)) with get_package_root_path() as root_path: shutil.copy(osp.join(root_path, 'tokenizer.py'), osp.join(triton_models_path, 'tokenizer'))
Copy tokenizer.
8,092
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig The provided code snippet includes necessary dependencies for implementing the `update_output_format` function. Write a Python function `def update_output_format(model_name: str, model_format: str, model_path: str, output_format: str)` to solve the following problem: Update output format according to model info. Here is the function: def update_output_format(model_name: str, model_format: str, model_path: str, output_format: str): """Update output format according to model info.""" TORCH_DTYPE_MAP = {torch.bfloat16: 'bf16'} MODEL_NAME_MAP = {'qwen': 'bf16', 'llama': 'half'} model_name = model_name.split('-')[0] def _fix_device_support(output_format): """fix device support.""" if output_format == 'bf16': if not torch.cuda.is_bf16_supported(): # device does not support bf16 print('Device does not support bf16.') output_format = 'fp16' return output_format def _infer_output_format(config): """_infer_output_format.""" torch_dtype = getattr(config, 'torch_dtype', None) if torch_dtype: updated_output_format = TORCH_DTYPE_MAP.get( torch_dtype, output_format) else: # get model name prefix updated_output_format = MODEL_NAME_MAP.get(model_name, output_format) return _fix_device_support(updated_output_format) if model_format in MODEL_NAME_MAP: updated_output_format = MODEL_NAME_MAP.get(model_name, output_format) return _fix_device_support(updated_output_format) else: from transformers import AutoConfig config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) return _infer_output_format(config)
Update output format according to model info.
8,093
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig class TurbomindModelConfig: """Config for turbomind model.""" model_name: str = None tensor_para_size: int = None head_num: int = None kv_head_num: int = None vocab_size: int = None num_layer: int = None inter_size: int = None norm_eps: float = None attn_bias: int = None start_id: int = None end_id: int = None session_len: int = None weight_type: str = 'fp16' rotary_embedding: int = 128 rope_theta: float = 10000.0 size_per_head: int = 128 group_size: int = 0 max_batch_size: int = 64 max_context_token_num: int = 1 step_length: int = 1 cache_max_entry_count: float = 0.8 cache_block_seq_len: int = 128 cache_chunk_size: int = -1 num_tokens_per_iter: int = 0 max_prefill_iters: int = 1 extra_tokens_per_iter: int = 0 use_context_fmha: int = 1 quant_policy: int = 0 max_position_embeddings: int = 0 rope_scaling_factor: float = 0.0 use_logn_attn: int = 0 def from_dict(cls, env, allow_none=False): """Construct from dict.""" params = inspect.signature(cls).parameters used = {k: v for k, v in env.items() if k in params and v is not None} if not allow_none: return cls(**used) else: default = { k: None for k in params.keys() if params[k].default is inspect._empty } default.update(used) return cls(**default) def from_engine_config(cls, config: TurbomindEngineConfig): env = copy.deepcopy(config.__dict__) env['tensor_para_size'] = env['tp'] ret = TurbomindModelConfig.from_dict(env, allow_none=True) ret.rotary_embedding = ret.size_per_head # workround to support `max_prefill_token_num` in turbomind engine if config.max_prefill_token_num is not None and \ config.session_len is not None: ret.num_tokens_per_iter = config.max_prefill_token_num ret.max_prefill_iters = (config.session_len + config.max_prefill_token_num - 1) // config.max_prefill_token_num return ret def toini(self): config = copy.deepcopy(self.__dict__) parser = ConfigParser() parser['llama'] = config with io.StringIO() as ss: parser.write(ss) ss.seek(0) ini = ss.read() return ini def __str__(self): return json.dumps(self.__dict__, indent=2) def valid(self): """Check if cfg is valid.""" for _, v in self.__dict__.items(): if v is None: return False return True def update_config_weight_type(output_format: str, config: TurbomindModelConfig): WEIGHT_TYPE_MAP = { 'fp32': 'fp32', 'fp16': 'fp16', 'bf16': 'bf16', 'w4': 'int4', 'w8': 'int8' } config.weight_type = WEIGHT_TYPE_MAP[output_format]
null
8,094
import os import os.path as osp import re import shutil from pathlib import Path import fire import torch from lmdeploy.model import MODELS from lmdeploy.utils import get_model from .source_model.base import INPUT_MODELS from .target_model.base import OUTPUT_MODELS, TurbomindModelConfig The provided code snippet includes necessary dependencies for implementing the `pack_model_repository` function. Write a Python function `def pack_model_repository(workspace_path: str)` to solve the following problem: package the model repository. Args: workspace_path: the path of workspace Here is the function: def pack_model_repository(workspace_path: str): """package the model repository. Args: workspace_path: the path of workspace """ os.symlink(src=osp.join('..', '..', 'tokenizer'), dst=osp.join(workspace_path, 'triton_models', 'preprocessing', '1', 'tokenizer')) os.symlink(src=osp.join('..', '..', 'tokenizer'), dst=osp.join(workspace_path, 'triton_models', 'postprocessing', '1', 'tokenizer')) os.symlink(src=osp.join('..', '..', 'weights'), dst=osp.join(workspace_path, 'triton_models', 'interactive', '1', 'weights')) model_repo_dir = osp.join(workspace_path, 'model_repository') os.makedirs(model_repo_dir, exist_ok=True) os.symlink(src=osp.join('..', 'triton_models', 'interactive'), dst=osp.join(model_repo_dir, 'turbomind')) os.symlink(src=osp.join('..', 'triton_models', 'preprocessing'), dst=osp.join(model_repo_dir, 'preprocessing')) os.symlink(src=osp.join('..', 'triton_models', 'postprocessing'), dst=osp.join(model_repo_dir, 'postprocessing'))
package the model repository. Args: workspace_path: the path of workspace
8,095
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm def _construct_stop_or_bad_words(words: List[int] = None): if words is None or len(words) == 0: return None offsets = range(1, len(words) + 1) combined = np.array([[words, offsets]]).astype(np.int32) return combined
null
8,096
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm The provided code snippet includes necessary dependencies for implementing the `_np_dict_to_tm_dict` function. Write a Python function `def _np_dict_to_tm_dict(np_dict: dict)` to solve the following problem: map numpy.ndarray to turbomind's tensor. Here is the function: def _np_dict_to_tm_dict(np_dict: dict): """map numpy.ndarray to turbomind's tensor.""" ret = _tm.TensorMap() for k, v in np_dict.items(): ret[k] = _tm.from_dlpack(v) return ret
map numpy.ndarray to turbomind's tensor.
8,097
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm The provided code snippet includes necessary dependencies for implementing the `_tm_dict_to_torch_dict` function. Write a Python function `def _tm_dict_to_torch_dict(tm_dict: _tm.TensorMap)` to solve the following problem: map turbomind's tensor to torch's tensor. Here is the function: def _tm_dict_to_torch_dict(tm_dict: _tm.TensorMap): """map turbomind's tensor to torch's tensor.""" ret = dict() for k, v in tm_dict.items(): if v.type == _tm.DataType.TYPE_UINT32: v = v.view(_tm.DataType.TYPE_INT32) ret[k] = torch.from_dlpack(v) return ret
map turbomind's tensor to torch's tensor.
8,098
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm logger = get_logger('lmdeploy') class TurbomindEngineConfig: def _update_engine_config(config: TurbomindEngineConfig, **kwargs): if config is None: config = TurbomindEngineConfig() for k, v in kwargs.items(): if v and hasattr(config, k): setattr(config, k, v) logger.warning(f'kwargs {k} is deprecated to initialize model, ' 'use TurbomindEngineConfig instead.') if config.model_name is not None: logger.warning('model_name is deprecated in TurbomindEngineConfig ' 'and has no effect') return config
null
8,099
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm class TurbomindEngineConfig: """TurboMind Engine config. Args: model_name (str): the name of the deployed model, deprecated and has no effect when version > 0.2.1 model_format (str): the layout of the deployed model. It can be one of the following values [hf, llama, awq], `hf` meaning `hf_llama`, `llama` meaning `meta_llama`, `awq` meaning the quantized model by AWQ. tp (int): the number of GPU cards used in tensor parallelism, default to 1 session_len (int): the max session length of a sequence, default to None max_batch_size (int): the max batch size during inference, default to 128 cache_max_entry_count (float): the percentage of gpu memory occupied by the k/v cache. For versions of lmdeploy between `v0.2.0` and `v0.2.1`, it defaults to 0.5, depicting the percentage of TOTAL GPU memory to be allocated to the k/v cache. For lmdeploy versions greater than `v0.2.1`, it defaults to 0.8, signifying the percentage of FREE GPU memory to be reserved for the k/v cache quant_policy (int): , default to 0. When k/v is quantized into 8 bit, set it to 4 rope_scaling_factor (int): scaling factor used for dynamic ntk, default to 0. TurboMind follows the implementation of transformer LlamaAttention use_logn_attn (bool): whether or not to use log attn: default to False download_dir (str): Directory to download and load the weights, default to the default cache directory of huggingface. revision (str): The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. max_prefill_token_num(int): the number of tokens each iteration during prefill, default to 8192 """ # noqa: E501 model_name: Optional[str] = None model_format: Optional[str] = None tp: int = 1 session_len: Optional[int] = None max_batch_size: int = 128 cache_max_entry_count: float = 0.8 quant_policy: int = 0 rope_scaling_factor: float = 0.0 use_logn_attn: bool = False download_dir: Optional[str] = None revision: Optional[str] = None max_prefill_token_num: int = 8192 class TurbomindModelConfig: """Config for turbomind model.""" model_name: str = None tensor_para_size: int = None head_num: int = None kv_head_num: int = None vocab_size: int = None num_layer: int = None inter_size: int = None norm_eps: float = None attn_bias: int = None start_id: int = None end_id: int = None session_len: int = None weight_type: str = 'fp16' rotary_embedding: int = 128 rope_theta: float = 10000.0 size_per_head: int = 128 group_size: int = 0 max_batch_size: int = 64 max_context_token_num: int = 1 step_length: int = 1 cache_max_entry_count: float = 0.8 cache_block_seq_len: int = 128 cache_chunk_size: int = -1 num_tokens_per_iter: int = 0 max_prefill_iters: int = 1 extra_tokens_per_iter: int = 0 use_context_fmha: int = 1 quant_policy: int = 0 max_position_embeddings: int = 0 rope_scaling_factor: float = 0.0 use_logn_attn: int = 0 def from_dict(cls, env, allow_none=False): """Construct from dict.""" params = inspect.signature(cls).parameters used = {k: v for k, v in env.items() if k in params and v is not None} if not allow_none: return cls(**used) else: default = { k: None for k in params.keys() if params[k].default is inspect._empty } default.update(used) return cls(**default) def from_engine_config(cls, config: TurbomindEngineConfig): env = copy.deepcopy(config.__dict__) env['tensor_para_size'] = env['tp'] ret = TurbomindModelConfig.from_dict(env, allow_none=True) ret.rotary_embedding = ret.size_per_head # workround to support `max_prefill_token_num` in turbomind engine if config.max_prefill_token_num is not None and \ config.session_len is not None: ret.num_tokens_per_iter = config.max_prefill_token_num ret.max_prefill_iters = (config.session_len + config.max_prefill_token_num - 1) // config.max_prefill_token_num return ret def toini(self): config = copy.deepcopy(self.__dict__) parser = ConfigParser() parser['llama'] = config with io.StringIO() as ss: parser.write(ss) ss.seek(0) ini = ss.read() return ini def __str__(self): return json.dumps(self.__dict__, indent=2) def valid(self): """Check if cfg is valid.""" for _, v in self.__dict__.items(): if v is None: return False return True def _update_tm_config(dst: TurbomindModelConfig, src: TurbomindEngineConfig): # A workaround to support max token number of each iteration in prefill if src.max_prefill_token_num is not None and src.session_len is not None: dst.num_tokens_per_iter = src.max_prefill_token_num dst.max_prefill_iters = (src.session_len + src.max_prefill_token_num - 1) // src.max_prefill_token_num dst_dict = copy.deepcopy(dst.__dict__) src_dict = copy.deepcopy(src.__dict__) src_dict['tensor_para_size'] = src_dict['tp'] for k, v in src_dict.items(): if v is not None and k in dst_dict: dst_dict[k] = v return TurbomindModelConfig.from_dict(dst_dict)
null
8,100
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm logger = get_logger('lmdeploy') def _compare_individual_gpu_memory(tp: int): logger.setLevel(level=logging.INFO) try: total_mem = [] free_mem = [] for i in range(tp): torch.cuda.set_device(i) free, total = torch.cuda.mem_get_info() total_mem.append(total / (1024**2)) free_mem.append(free / (1024**2)) all_total_equal = all(total == total_mem[0] for total in total_mem) all_free_equal = all(free == free_mem[0] for free in free_mem) if not all_total_equal or not all_free_equal: logger.warning( f'Memory discrepancy detected: Total Memory={total_mem} MB, \ Free Memory={free_mem} MB') except Exception as e: logger.error(f'An exception occurred: {e}')
null
8,101
import asyncio import copy import logging import os.path as osp import sys from configparser import ConfigParser from contextlib import contextmanager from queue import LifoQueue, Queue from threading import Thread from typing import Iterable, List, Optional, Union import numpy as np import torch from torch.nn.utils.rnn import pad_sequence import lmdeploy from lmdeploy.messages import (EngineGenerationConfig, ResponseType, TurbomindEngineConfig) from lmdeploy.model import (MODELS, BaseModel, ChatTemplateConfig, best_match_model) from lmdeploy.tokenizer import Tokenizer from lmdeploy.utils import _stop_words, get_logger, get_model from .deploy.converter import (get_model_format, supported_formats, update_config_weight_type, update_output_format) from .deploy.source_model.base import INPUT_MODELS from .deploy.target_model.base import OUTPUT_MODELS, TurbomindModelConfig from .utils import ModelSource, get_model_from_config, get_model_source import _turbomind as _tm def cuda_ctx(device_id): old_device = torch.cuda.current_device() torch.cuda.set_device(device_id) yield torch.cuda.set_device(old_device)
null
8,102
import os.path as osp import subprocess The provided code snippet includes necessary dependencies for implementing the `get_llama_gemm` function. Write a Python function `def get_llama_gemm()` to solve the following problem: get the executable binary llama_gemm. Here is the function: def get_llama_gemm(): """get the executable binary llama_gemm.""" import os.path as osp import lmdeploy lmdeploy_dir = osp.split(lmdeploy.__file__)[0] bin_path = osp.join(lmdeploy_dir, 'bin', 'llama_gemm') assert osp.exists(bin_path), f'{bin_path} not exists' return bin_path
get the executable binary llama_gemm.
8,103
import os.path as osp import subprocess class TurbomindModelConfig: """Config for turbomind model.""" model_name: str = None tensor_para_size: int = None head_num: int = None kv_head_num: int = None vocab_size: int = None num_layer: int = None inter_size: int = None norm_eps: float = None attn_bias: int = None start_id: int = None end_id: int = None session_len: int = None weight_type: str = 'fp16' rotary_embedding: int = 128 rope_theta: float = 10000.0 size_per_head: int = 128 group_size: int = 0 max_batch_size: int = 64 max_context_token_num: int = 1 step_length: int = 1 cache_max_entry_count: float = 0.8 cache_block_seq_len: int = 128 cache_chunk_size: int = -1 num_tokens_per_iter: int = 0 max_prefill_iters: int = 1 extra_tokens_per_iter: int = 0 use_context_fmha: int = 1 quant_policy: int = 0 max_position_embeddings: int = 0 rope_scaling_factor: float = 0.0 use_logn_attn: int = 0 def from_dict(cls, env, allow_none=False): """Construct from dict.""" params = inspect.signature(cls).parameters used = {k: v for k, v in env.items() if k in params and v is not None} if not allow_none: return cls(**used) else: default = { k: None for k in params.keys() if params[k].default is inspect._empty } default.update(used) return cls(**default) def from_engine_config(cls, config: TurbomindEngineConfig): env = copy.deepcopy(config.__dict__) env['tensor_para_size'] = env['tp'] ret = TurbomindModelConfig.from_dict(env, allow_none=True) ret.rotary_embedding = ret.size_per_head # workround to support `max_prefill_token_num` in turbomind engine if config.max_prefill_token_num is not None and \ config.session_len is not None: ret.num_tokens_per_iter = config.max_prefill_token_num ret.max_prefill_iters = (config.session_len + config.max_prefill_token_num - 1) // config.max_prefill_token_num return ret def toini(self): config = copy.deepcopy(self.__dict__) parser = ConfigParser() parser['llama'] = config with io.StringIO() as ss: parser.write(ss) ss.seek(0) ini = ss.read() return ini def __str__(self): return json.dumps(self.__dict__, indent=2) def valid(self): """Check if cfg is valid.""" for _, v in self.__dict__.items(): if v is None: return False return True The provided code snippet includes necessary dependencies for implementing the `read_config` function. Write a Python function `def read_config(ini_path: str)` to solve the following problem: read turbomind config from turbomind. Args: ini_path (str): the path of `config.ini` file in turbomind model Here is the function: def read_config(ini_path: str): """read turbomind config from turbomind. Args: ini_path (str): the path of `config.ini` file in turbomind model """ from configparser import ConfigParser from lmdeploy.turbomind.deploy.target_model.base import \ TurbomindModelConfig with open(ini_path, 'r') as f: parser = ConfigParser() parser.read_file(f) section_name = 'llama' _cfg = parser._sections[section_name] cfg = TurbomindModelConfig.from_dict(_cfg) return cfg.head_num, cfg.size_per_head, cfg.inter_size, \ cfg.vocab_size, cfg.tensor_para_size
read turbomind config from turbomind. Args: ini_path (str): the path of `config.ini` file in turbomind model
8,104
import asyncio import functools import logging import sys import time from contextlib import contextmanager from logging import Logger, LogRecord from typing import List, Optional The provided code snippet includes necessary dependencies for implementing the `filter_suffix` function. Write a Python function `def filter_suffix(response: str, suffixes: Optional[List[str]] = None) -> str` to solve the following problem: Filter response with suffixes. Args: response (str): generated response by LLMs. suffixes (str): a list of suffixes to be deleted. Return: str: a clean response. Here is the function: def filter_suffix(response: str, suffixes: Optional[List[str]] = None) -> str: """Filter response with suffixes. Args: response (str): generated response by LLMs. suffixes (str): a list of suffixes to be deleted. Return: str: a clean response. """ if suffixes is None: return response for item in suffixes: if response.endswith(item): response = response[:len(response) - len(item)] return response
Filter response with suffixes. Args: response (str): generated response by LLMs. suffixes (str): a list of suffixes to be deleted. Return: str: a clean response.
8,105
import asyncio import functools import logging import sys import time from contextlib import contextmanager from logging import Logger, LogRecord from typing import List, Optional The provided code snippet includes necessary dependencies for implementing the `_stop_words` function. Write a Python function `def _stop_words(stop_words: List[str], tokenizer: object)` to solve the following problem: return list of stop-words to numpy.ndarray. Here is the function: def _stop_words(stop_words: List[str], tokenizer: object): """return list of stop-words to numpy.ndarray.""" import numpy as np if stop_words is None: return None assert isinstance(stop_words, List) and \ all(isinstance(elem, str) for elem in stop_words), \ f'stop_words must be a list but got {type(stop_words)}' stop_indexes = [] for stop_word in stop_words: stop_indexes += tokenizer.indexes_containing_token(stop_word) assert isinstance(stop_indexes, List) and all( isinstance(elem, int) for elem in stop_indexes), 'invalid stop_words' # each id in stop_indexes represents a stop word # refer to https://github.com/fauxpilot/fauxpilot/discussions/165 for # detailed explanation about fastertransformer's stop_indexes stop_word_offsets = range(1, len(stop_indexes) + 1) stop_words = np.array([[stop_indexes, stop_word_offsets]]).astype(np.int32) return stop_words
return list of stop-words to numpy.ndarray.
8,106
import asyncio import functools import logging import sys import time from contextlib import contextmanager from logging import Logger, LogRecord from typing import List, Optional The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(pretrained_model_name_or_path: str, download_dir: str = None, revision: str = None)` to solve the following problem: Get model from huggingface or modelscope. Here is the function: def get_model(pretrained_model_name_or_path: str, download_dir: str = None, revision: str = None): """Get model from huggingface or modelscope.""" import os if os.getenv('LMDEPLOY_USE_MODELSCOPE', 'False').lower() == 'true': from modelscope import snapshot_download else: from huggingface_hub import snapshot_download download_kwargs = {} if download_dir is not None: download_kwargs['cache_dir'] = download_dir if revision is not None: download_kwargs['revision'] = revision model_path = snapshot_download(pretrained_model_name_or_path, **download_kwargs) return model_path
Get model from huggingface or modelscope.
8,107
import asyncio import functools import logging import sys import time from contextlib import contextmanager from logging import Logger, LogRecord from typing import List, Optional The provided code snippet includes necessary dependencies for implementing the `logging_timer` function. Write a Python function `def logging_timer(op_name: str, logger: Logger, level: int = logging.DEBUG)` to solve the following problem: logging timer. Here is the function: def logging_timer(op_name: str, logger: Logger, level: int = logging.DEBUG): """logging timer.""" @contextmanager def __timer(): """timer.""" start = time.perf_counter() yield end = time.perf_counter() duration = (end - start) * 1000 logger.log(level, f'<{op_name}> take time: {duration:.2f} ms') def __inner(func): """inner.""" @functools.wraps(func) def __func_warpper(*args, **kwargs): """func warpper.""" if not logger.isEnabledFor(level): return func(*args, **kwargs) with __timer(): return func(*args, **kwargs) @functools.wraps(func) def __async_warpper(*args, **kwargs): """async warpper.""" async def __tmp(): if not logger.isEnabledFor(level): return (await func(*args, **kwargs)) with __timer(): return (await func(*args, **kwargs)) return __tmp() if asyncio.iscoroutinefunction(func): return __async_warpper else: return __func_warpper return __inner
logging timer.
8,108
import json from typing import Any, Dict, Iterable, List, Optional, Union import requests from lmdeploy.utils import get_logger The provided code snippet includes necessary dependencies for implementing the `input_prompt` function. Write a Python function `def input_prompt()` to solve the following problem: Input a prompt in the consolo interface. Here is the function: def input_prompt(): """Input a prompt in the consolo interface.""" print('\ndouble enter to end input >>> ', end='') sentinel = '' # ends when this string is seen return '\n'.join(iter(input, sentinel))
Input a prompt in the consolo interface.
8,109
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] get_bearer_token = HTTPBearer(auto_error=False) The provided code snippet includes necessary dependencies for implementing the `check_api_key` function. Write a Python function `async def check_api_key( auth: Optional[HTTPAuthorizationCredentials] = Depends(get_bearer_token), ) -> str` to solve the following problem: Check if client provide valid api key. Adopted from https://github.com/lm-sys/FastChat/blob/v0.2.35/fastchat/serve/openai_api_server.py#L108-L127 Here is the function: async def check_api_key( auth: Optional[HTTPAuthorizationCredentials] = Depends(get_bearer_token), ) -> str: """Check if client provide valid api key. Adopted from https://github.com/lm-sys/FastChat/blob/v0.2.35/fastchat/serve/openai_api_server.py#L108-L127 """ # noqa if VariableInterface.api_keys: if auth is None or ( token := auth.credentials) not in VariableInterface.api_keys: raise HTTPException( status_code=401, detail={ 'error': { 'message': 'Please request with valid api key!', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key', } }, ) return token else: # api_keys not set; allow all return None
Check if client provide valid api key. Adopted from https://github.com/lm-sys/FastChat/blob/v0.2.35/fastchat/serve/openai_api_server.py#L108-L127
8,110
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) async def check_request(request) -> Optional[JSONResponse]: """Check if a request is valid.""" if request.model in get_model_list(): return ret = create_error_response( HTTPStatus.NOT_FOUND, f'The model `{request.model}` does not exist.') return ret class UsageInfo(BaseModel): """Usage information.""" prompt_tokens: int = 0 total_tokens: int = 0 completion_tokens: Optional[int] = 0 class ChatCompletionRequestQos(BaseModel): """Chat completion request.""" model: str messages: Union[str, List[Dict[str, str]]] temperature: Optional[float] = 0.7 top_p: Optional[float] = 1.0 n: Optional[int] = 1 max_tokens: Optional[int] = Field(default=None, examples=[None]) stop: Optional[bool] = False stream: Optional[bool] = False presence_penalty: Optional[float] = 0.0 frequency_penalty: Optional[float] = 0.0 user: Optional[str] = None user_id: Optional[str] = None # additional argument of lmdeploy repetition_penalty: Optional[float] = 1.0 session_id: Optional[int] = -1 ignore_eos: Optional[bool] = False top_k: Optional[int] = 40 class ChatMessage(BaseModel): """Chat messages.""" role: str content: str class ChatCompletionResponseChoice(BaseModel): """Chat completion response choices.""" index: int message: ChatMessage finish_reason: Optional[Literal['stop', 'length']] = None class ChatCompletionResponse(BaseModel): """Chat completion response.""" id: str = Field(default_factory=lambda: f'chatcmpl-{shortuuid.random()}') object: str = 'chat.completion' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[ChatCompletionResponseChoice] usage: UsageInfo class DeltaMessage(BaseModel): """Delta messages.""" role: Optional[str] = None content: Optional[str] = None class ChatCompletionResponseStreamChoice(BaseModel): """Chat completion response stream choice.""" index: int delta: DeltaMessage finish_reason: Optional[Literal['stop', 'length']] = None class ChatCompletionStreamResponse(BaseModel): """Chat completion stream response.""" id: str = Field(default_factory=lambda: f'chatcmpl-{shortuuid.random()}') object: str = 'chat.completion.chunk' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[ChatCompletionResponseStreamChoice] The provided code snippet includes necessary dependencies for implementing the `chat_completions_v1_qos` function. Write a Python function `async def chat_completions_v1_qos(request: ChatCompletionRequestQos, raw_request: Request = None)` to solve the following problem: Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int): output token nums - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) Here is the function: async def chat_completions_v1_qos(request: ChatCompletionRequestQos, raw_request: Request = None): """Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int): output token nums - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) """ VariableInterface.session_id += 1 request.session_id = VariableInterface.session_id error_check_ret = await check_request(request) if error_check_ret is not None: return error_check_ret model_name = request.model request_id = str(request.session_id) created_time = int(time.time()) if VariableInterface.qos_engine is None: return create_error_response( HTTPStatus.NOT_FOUND, 'cannot parse qos engine config, this api is not work') result_generator = await VariableInterface.qos_engine.generate_with_qos( request) if result_generator is None: return create_error_response(HTTPStatus.INTERNAL_SERVER_ERROR, 'Failed to generate completions') def create_stream_response_json( index: int, text: str, finish_reason: Optional[str] = None, ) -> str: choice_data = ChatCompletionResponseStreamChoice( index=index, delta=DeltaMessage(role='assistant', content=text), finish_reason=finish_reason, ) response = ChatCompletionStreamResponse( id=request_id, created=created_time, model=model_name, choices=[choice_data], ) response_json = response.model_dump_json() return response_json async def completion_stream_generator() -> AsyncGenerator[str, None]: # First chunk with role for i in range(request.n): choice_data = ChatCompletionResponseStreamChoice( index=i, delta=DeltaMessage(role='assistant'), finish_reason=None, ) chunk = ChatCompletionStreamResponse(id=request_id, choices=[choice_data], model=model_name) data = chunk.model_dump_json(exclude_unset=True) yield f'data: {data}\n\n' async for res in result_generator: response_json = create_stream_response_json( index=0, text=res.response, ) yield f'data: {response_json}\n\n' yield 'data: [DONE]\n\n' # Streaming response if request.stream: return StreamingResponse(completion_stream_generator(), media_type='text/event-stream') # Non-streaming response final_res = None text = '' async for res in result_generator: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await VariableInterface.async_engine.stop_session( request.session_id) return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected') final_res = res text += res.response assert final_res is not None choices = [] choice_data = ChatCompletionResponseChoice( index=0, message=ChatMessage(role='assistant', content=text), finish_reason=final_res.finish_reason, ) choices.append(choice_data) total_tokens = sum([ final_res.history_token_len, final_res.input_token_len, final_res.generate_token_len ]) usage = UsageInfo( prompt_tokens=final_res.input_token_len, completion_tokens=final_res.generate_token_len, total_tokens=total_tokens, ) response = ChatCompletionResponse( id=request_id, created=created_time, model=model_name, choices=choices, usage=usage, ) return response
Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int): output token nums - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty)
8,111
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) async def check_request(request) -> Optional[JSONResponse]: """Check if a request is valid.""" if request.model in get_model_list(): return ret = create_error_response( HTTPStatus.NOT_FOUND, f'The model `{request.model}` does not exist.') return ret class GenerationConfig: """generation parameters used by inference engines. Args: n (int): Define how many chat completion choices to generate for each input message max_new_tokens (int): The maximum number of tokens that can be generated in the chat completion top_p (float): An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass top_k (int): An alternative to sampling with temperature, where the model considers the top_k tokens with the highest probability temperature (float): Sampling temperature repetition_penalty (float): Penalty to prevent the model from generating repeated words or phrases. A value larger than 1 discourages repetition ignore_eos (bool): Indicator to ignore the eos_token_id or not random_seed (int): Seed used when sampling a token stop_words (List[str]): Words that stop generating further tokens bad_words (List[str]): Words that the engine will never generate min_new_tokens (int): The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. """ n: int = 1 max_new_tokens: int = 512 top_p: float = 1.0 top_k: int = 1 temperature: float = 0.8 repetition_penalty: float = 1.0 ignore_eos: bool = False random_seed: int = None stop_words: List[str] = None bad_words: List[str] = None min_new_tokens: int = None skip_special_tokens: bool = True class UsageInfo(BaseModel): """Usage information.""" prompt_tokens: int = 0 total_tokens: int = 0 completion_tokens: Optional[int] = 0 class ChatMessage(BaseModel): """Chat messages.""" role: str content: str class ChatCompletionResponseChoice(BaseModel): """Chat completion response choices.""" index: int message: ChatMessage finish_reason: Optional[Literal['stop', 'length']] = None class ChatCompletionResponse(BaseModel): """Chat completion response.""" id: str = Field(default_factory=lambda: f'chatcmpl-{shortuuid.random()}') object: str = 'chat.completion' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[ChatCompletionResponseChoice] usage: UsageInfo class DeltaMessage(BaseModel): """Delta messages.""" role: Optional[str] = None content: Optional[str] = None class ChatCompletionResponseStreamChoice(BaseModel): """Chat completion response stream choice.""" index: int delta: DeltaMessage finish_reason: Optional[Literal['stop', 'length']] = None class ChatCompletionStreamResponse(BaseModel): """Chat completion stream response.""" id: str = Field(default_factory=lambda: f'chatcmpl-{shortuuid.random()}') object: str = 'chat.completion.chunk' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[ChatCompletionResponseStreamChoice] The provided code snippet includes necessary dependencies for implementing the `chat_completions_v1` function. Write a Python function `async def chat_completions_v1(request: ChatCompletionRequest, raw_request: Request = None)` to solve the following problem: Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. Chat history example: `[{"role": "user", "content": "hi"}]`. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int | None): output token nums. Default to None. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) Here is the function: async def chat_completions_v1(request: ChatCompletionRequest, raw_request: Request = None): """Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. Chat history example: `[{"role": "user", "content": "hi"}]`. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int | None): output token nums. Default to None. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) """ VariableInterface.session_id += 1 request.session_id = VariableInterface.session_id error_check_ret = await check_request(request) if error_check_ret is not None: return error_check_ret model_name = request.model request_id = str(request.session_id) created_time = int(time.time()) if isinstance(request.stop, str): request.stop = [request.stop] gen_config = GenerationConfig( max_new_tokens=request.max_tokens, top_k=request.top_k, top_p=request.top_p, temperature=request.temperature, repetition_penalty=request.repetition_penalty, ignore_eos=request.ignore_eos, stop_words=request.stop, skip_special_tokens=request.skip_special_tokens) result_generator = VariableInterface.async_engine.generate( request.messages, request.session_id, gen_config=gen_config, stream_response=True, # always use stream to enable batching sequence_start=True, sequence_end=True, do_preprocess=not isinstance(request.messages, str), # text completion for string input ) def create_stream_response_json( index: int, text: str, finish_reason: Optional[str] = None, ) -> str: choice_data = ChatCompletionResponseStreamChoice( index=index, delta=DeltaMessage(role='assistant', content=text), finish_reason=finish_reason, ) response = ChatCompletionStreamResponse( id=request_id, created=created_time, model=model_name, choices=[choice_data], ) response_json = response.model_dump_json() return response_json async def completion_stream_generator() -> AsyncGenerator[str, None]: # First chunk with role for i in range(request.n): choice_data = ChatCompletionResponseStreamChoice( index=i, delta=DeltaMessage(role='assistant'), finish_reason=None, ) chunk = ChatCompletionStreamResponse(id=request_id, choices=[choice_data], model=model_name) data = chunk.model_dump_json(exclude_unset=True) yield f'data: {data}\n\n' async for res in result_generator: response_json = create_stream_response_json( index=0, text=res.response, finish_reason=res.finish_reason, ) yield f'data: {response_json}\n\n' yield 'data: [DONE]\n\n' # Streaming response if request.stream: return StreamingResponse(completion_stream_generator(), media_type='text/event-stream') # Non-streaming response final_res = None text = '' async for res in result_generator: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await VariableInterface.async_engine.stop_session( request.session_id) return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected') final_res = res text += res.response assert final_res is not None choices = [] choice_data = ChatCompletionResponseChoice( index=0, message=ChatMessage(role='assistant', content=text), finish_reason=final_res.finish_reason, ) choices.append(choice_data) total_tokens = sum([ final_res.history_token_len, final_res.input_token_len, final_res.generate_token_len ]) usage = UsageInfo( prompt_tokens=final_res.input_token_len, completion_tokens=final_res.generate_token_len, total_tokens=total_tokens, ) response = ChatCompletionResponse( id=request_id, created=created_time, model=model_name, choices=choices, usage=usage, ) return response
Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. Chat history example: `[{"role": "user", "content": "hi"}]`. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int | None): output token nums. Default to None. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty)
8,112
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) async def check_request(request) -> Optional[JSONResponse]: """Check if a request is valid.""" if request.model in get_model_list(): return ret = create_error_response( HTTPStatus.NOT_FOUND, f'The model `{request.model}` does not exist.') return ret class UsageInfo(BaseModel): """Usage information.""" prompt_tokens: int = 0 total_tokens: int = 0 completion_tokens: Optional[int] = 0 class CompletionRequestQos(BaseModel): """Completion request.""" model: str prompt: Union[str, List[Any]] suffix: Optional[str] = None temperature: Optional[float] = 0.7 n: Optional[int] = 1 max_tokens: Optional[int] = 16 stop: Optional[Union[str, List[str]]] = None stream: Optional[bool] = False top_p: Optional[float] = 1.0 logprobs: Optional[int] = None echo: Optional[bool] = False presence_penalty: Optional[float] = 0.0 frequency_penalty: Optional[float] = 0.0 user: Optional[str] = None # additional argument of lmdeploy top_k: Optional[int] = 40 repetition_penalty: Optional[float] = 1.0 session_id: Optional[int] = -1 ignore_eos: Optional[bool] = False user_id: Optional[str] = None class CompletionResponseChoice(BaseModel): """Completion response choices.""" index: int text: str logprobs: Optional[int] = None finish_reason: Optional[Literal['stop', 'length']] = None class CompletionResponse(BaseModel): """Completion response.""" id: str = Field(default_factory=lambda: f'cmpl-{shortuuid.random()}') object: str = 'text_completion' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[CompletionResponseChoice] usage: UsageInfo class CompletionResponseStreamChoice(BaseModel): """Completion response stream choice.""" index: int text: str logprobs: Optional[float] = None finish_reason: Optional[Literal['stop', 'length']] = None class CompletionStreamResponse(BaseModel): """Completion stream response.""" id: str = Field(default_factory=lambda: f'cmpl-{shortuuid.random()}') object: str = 'text_completion' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[CompletionResponseStreamChoice] The provided code snippet includes necessary dependencies for implementing the `completions_v1_qos` function. Write a Python function `async def completions_v1_qos(request: CompletionRequestQos, raw_request: Request = None)` to solve the following problem: Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. Additional arguments supported by LMDeploy: - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) Here is the function: async def completions_v1_qos(request: CompletionRequestQos, raw_request: Request = None): """Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. Additional arguments supported by LMDeploy: - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) """ VariableInterface.session_id += 1 request.session_id = VariableInterface.session_id error_check_ret = await check_request(request) if error_check_ret is not None: return error_check_ret model_name = request.model request_id = str(request.session_id) created_time = int(time.time()) if isinstance(request.prompt, str): request.prompt = [request.prompt] if VariableInterface.qos_engine is None: return create_error_response( HTTPStatus.NOT_FOUND, 'cannot parse qos engine config, this api is not work') generators = await VariableInterface.qos_engine.generate_with_qos(request) def create_stream_response_json( index: int, text: str, finish_reason: Optional[str] = None, ) -> str: choice_data = CompletionResponseStreamChoice( index=index, text=text, finish_reason=finish_reason, ) response = CompletionStreamResponse( id=request_id, created=created_time, model=model_name, choices=[choice_data], ) response_json = response.model_dump_json() return response_json async def completion_stream_generator() -> AsyncGenerator[str, None]: # First chunk with role for generator in generators: for i in range(request.n): choice_data = CompletionResponseStreamChoice( index=i, text='', finish_reason=None, ) chunk = CompletionStreamResponse(id=request_id, choices=[choice_data], model=model_name) data = chunk.model_dump_json(exclude_unset=True) yield f'data: {data}\n\n' async for res in generator: response_json = create_stream_response_json( index=0, text=res.response, ) yield f'data: {response_json}\n\n' yield 'data: [DONE]\n\n' # Streaming response if request.stream: return StreamingResponse(completion_stream_generator(), media_type='text/event-stream') # Non-streaming response usage = UsageInfo() choices = [] async def _inner_call(i, generator): final_res = None text = '' async for res in generator: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await VariableInterface.async_engine.stop_session( request.session_id) return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected') final_res = res text += res.response assert final_res is not None choice_data = CompletionResponseChoice( index=0, text=text, finish_reason=final_res.finish_reason, ) choices.append(choice_data) total_tokens = sum([ final_res.history_token_len, final_res.input_token_len, final_res.generate_token_len ]) usage.prompt_tokens += final_res.input_token_len usage.completion_tokens += final_res.generate_token_len usage.total_tokens += total_tokens await asyncio.gather( *[_inner_call(i, generators[i]) for i in range(len(generators))]) response = CompletionResponse( id=request_id, created=created_time, model=model_name, choices=choices, usage=usage, ) return response
Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. Additional arguments supported by LMDeploy: - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty)
8,113
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) async def check_request(request) -> Optional[JSONResponse]: """Check if a request is valid.""" if request.model in get_model_list(): return ret = create_error_response( HTTPStatus.NOT_FOUND, f'The model `{request.model}` does not exist.') return ret class GenerationConfig: """generation parameters used by inference engines. Args: n (int): Define how many chat completion choices to generate for each input message max_new_tokens (int): The maximum number of tokens that can be generated in the chat completion top_p (float): An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass top_k (int): An alternative to sampling with temperature, where the model considers the top_k tokens with the highest probability temperature (float): Sampling temperature repetition_penalty (float): Penalty to prevent the model from generating repeated words or phrases. A value larger than 1 discourages repetition ignore_eos (bool): Indicator to ignore the eos_token_id or not random_seed (int): Seed used when sampling a token stop_words (List[str]): Words that stop generating further tokens bad_words (List[str]): Words that the engine will never generate min_new_tokens (int): The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. """ n: int = 1 max_new_tokens: int = 512 top_p: float = 1.0 top_k: int = 1 temperature: float = 0.8 repetition_penalty: float = 1.0 ignore_eos: bool = False random_seed: int = None stop_words: List[str] = None bad_words: List[str] = None min_new_tokens: int = None skip_special_tokens: bool = True class UsageInfo(BaseModel): """Usage information.""" prompt_tokens: int = 0 total_tokens: int = 0 completion_tokens: Optional[int] = 0 class CompletionRequest(BaseModel): """Completion request.""" model: str prompt: Union[str, List[Any]] suffix: Optional[str] = None temperature: Optional[float] = 0.7 n: Optional[int] = 1 max_tokens: Optional[int] = 16 stop: Optional[Union[str, List[str]]] = Field(default=None, examples=[None]) stream: Optional[bool] = False top_p: Optional[float] = 1.0 logprobs: Optional[int] = None echo: Optional[bool] = False presence_penalty: Optional[float] = 0.0 frequency_penalty: Optional[float] = 0.0 user: Optional[str] = None # additional argument of lmdeploy repetition_penalty: Optional[float] = 1.0 session_id: Optional[int] = -1 ignore_eos: Optional[bool] = False skip_special_tokens: Optional[bool] = True top_k: Optional[int] = 40 # for opencompass class CompletionResponseChoice(BaseModel): """Completion response choices.""" index: int text: str logprobs: Optional[int] = None finish_reason: Optional[Literal['stop', 'length']] = None class CompletionResponse(BaseModel): """Completion response.""" id: str = Field(default_factory=lambda: f'cmpl-{shortuuid.random()}') object: str = 'text_completion' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[CompletionResponseChoice] usage: UsageInfo class CompletionResponseStreamChoice(BaseModel): """Completion response stream choice.""" index: int text: str logprobs: Optional[float] = None finish_reason: Optional[Literal['stop', 'length']] = None class CompletionStreamResponse(BaseModel): """Completion stream response.""" id: str = Field(default_factory=lambda: f'cmpl-{shortuuid.random()}') object: str = 'text_completion' created: int = Field(default_factory=lambda: int(time.time())) model: str choices: List[CompletionResponseStreamChoice] The provided code snippet includes necessary dependencies for implementing the `completions_v1` function. Write a Python function `async def completions_v1(request: CompletionRequest, raw_request: Request = None)` to solve the following problem: Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums. Default to 16. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) Here is the function: async def completions_v1(request: CompletionRequest, raw_request: Request = None): """Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums. Default to 16. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) """ VariableInterface.session_id += 1 request.session_id = VariableInterface.session_id error_check_ret = await check_request(request) if error_check_ret is not None: return error_check_ret model_name = request.model request_id = str(request.session_id) created_time = int(time.time()) if isinstance(request.prompt, str): request.prompt = [request.prompt] if isinstance(request.stop, str): request.stop = [request.stop] gen_config = GenerationConfig( max_new_tokens=request.max_tokens if request.max_tokens else 512, top_k=request.top_k, top_p=request.top_p, temperature=request.temperature, repetition_penalty=request.repetition_penalty, ignore_eos=request.ignore_eos, stop_words=request.stop, skip_special_tokens=request.skip_special_tokens) generators = [] for i in range(len(request.prompt)): result_generator = VariableInterface.async_engine.generate( request.prompt[i], request.session_id + i, gen_config=gen_config, stream_response=True, # always use stream to enable batching sequence_start=True, sequence_end=True, do_preprocess=False) generators.append(result_generator) def create_stream_response_json( index: int, text: str, finish_reason: Optional[str] = None, ) -> str: choice_data = CompletionResponseStreamChoice( index=index, text=text, finish_reason=finish_reason, ) response = CompletionStreamResponse( id=request_id, created=created_time, model=model_name, choices=[choice_data], ) response_json = response.model_dump_json() return response_json async def completion_stream_generator() -> AsyncGenerator[str, None]: # First chunk with role for generator in generators: for i in range(request.n): choice_data = CompletionResponseStreamChoice( index=i, text='', finish_reason=None, ) chunk = CompletionStreamResponse(id=request_id, choices=[choice_data], model=model_name) data = chunk.model_dump_json(exclude_unset=True) yield f'data: {data}\n\n' async for res in generator: response_json = create_stream_response_json( index=0, text=res.response, finish_reason=res.finish_reason, ) yield f'data: {response_json}\n\n' yield 'data: [DONE]\n\n' # Streaming response if request.stream: return StreamingResponse(completion_stream_generator(), media_type='text/event-stream') # Non-streaming response usage = UsageInfo() choices = [] async def _inner_call(i, generator): final_res = None text = '' async for res in generator: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await VariableInterface.async_engine.stop_session( request.session_id) return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected') final_res = res text += res.response assert final_res is not None choice_data = CompletionResponseChoice( index=0, text=text, finish_reason=final_res.finish_reason, ) choices.append(choice_data) total_tokens = sum([ final_res.history_token_len, final_res.input_token_len, final_res.generate_token_len ]) usage.prompt_tokens += final_res.input_token_len usage.completion_tokens += final_res.generate_token_len usage.total_tokens += total_tokens await asyncio.gather( *[_inner_call(i, generators[i]) for i in range(len(generators))]) response = CompletionResponse( id=request_id, created=created_time, model=model_name, choices=choices, usage=usage, ) return response
Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums. Default to 16. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty)
8,114
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) class EmbeddingsRequest(BaseModel): """Embedding request.""" model: str = None input: Union[str, List[str]] user: Optional[str] = None The provided code snippet includes necessary dependencies for implementing the `create_embeddings` function. Write a Python function `async def create_embeddings(request: EmbeddingsRequest, raw_request: Request = None)` to solve the following problem: Creates embeddings for the text. Here is the function: async def create_embeddings(request: EmbeddingsRequest, raw_request: Request = None): """Creates embeddings for the text.""" return create_error_response(HTTPStatus.BAD_REQUEST, 'Unsupported by turbomind.')
Creates embeddings for the text.
8,115
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] class EncodeRequest(BaseModel): """Encode request.""" input: Union[str, List[str]] do_preprocess: Optional[bool] = False add_bos: Optional[bool] = True class EncodeResponse(BaseModel): """Encode response.""" input_ids: Union[List[int], List[List[int]]] length: Union[int, List[int]] The provided code snippet includes necessary dependencies for implementing the `encode` function. Write a Python function `async def encode(request: EncodeRequest, raw_request: Request = None)` to solve the following problem: Encode prompts. The request should be a JSON object with the following fields: - input: the prompt to be encoded. In str or List[str] format. - do_preprocess: whether do preprocess or not. Default to False. - add_bos: True when it is the beginning of a conversation. False when it is not. Default to True. Here is the function: async def encode(request: EncodeRequest, raw_request: Request = None): """Encode prompts. The request should be a JSON object with the following fields: - input: the prompt to be encoded. In str or List[str] format. - do_preprocess: whether do preprocess or not. Default to False. - add_bos: True when it is the beginning of a conversation. False when it is not. Default to True. """ def encode(prompt: str, do_preprocess: bool, add_bos: bool): if do_preprocess: prompt = VariableInterface.async_engine.chat_template.get_prompt( prompt, sequence_start=add_bos) input_ids = VariableInterface.async_engine.tokenizer.encode( prompt, add_bos=add_bos) return input_ids if isinstance(request.input, str): encoded = encode(request.input, request.do_preprocess, request.add_bos) return EncodeResponse(input_ids=encoded, length=len(encoded)) else: encoded, length = [], [] for prompt in request.input: ids = encode(prompt, request.do_preprocess, request.add_bos) encoded.append(ids) length.append(len(ids)) return EncodeResponse(input_ids=encoded, length=length)
Encode prompts. The request should be a JSON object with the following fields: - input: the prompt to be encoded. In str or List[str] format. - do_preprocess: whether do preprocess or not. Default to False. - add_bos: True when it is the beginning of a conversation. False when it is not. Default to True.
8,116
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) class GenerateRequestQos(BaseModel): """Generate request.""" prompt: Union[str, List[Dict[str, str]]] session_id: int = -1 interactive_mode: bool = False stream: bool = False stop: bool = False request_output_len: int = 512 top_p: float = 0.8 top_k: int = 40 temperature: float = 0.8 repetition_penalty: float = 1.0 ignore_eos: bool = False user_id: Optional[str] = None class GenerateResponse(BaseModel): """Generate response.""" text: str tokens: int input_tokens: int history_tokens: int finish_reason: Optional[Literal['stop', 'length']] = None The provided code snippet includes necessary dependencies for implementing the `chat_interactive_v1_qos` function. Write a Python function `async def chat_interactive_v1_qos(request: GenerateRequestQos, raw_request: Request = None)` to solve the following problem: Generate completion for the request. - On interactive mode, the chat history is kept on the server. Please set `interactive_mode = True`. - On normal mode, no chat history is kept on the server. Set `interactive_mode = False`. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - session_id: determine which instance will be called. If not specified with a value other than -1, using random value directly. - interactive_mode (bool): turn on interactive mode or not. On interactive mode, session history is kept on the server (and vice versa). - stream: whether to stream the results or not. - stop: whether to stop the session response or not. - request_output_len (int): output token nums - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - temperature (float): to modulate the next token probability - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" Here is the function: async def chat_interactive_v1_qos(request: GenerateRequestQos, raw_request: Request = None): """Generate completion for the request. - On interactive mode, the chat history is kept on the server. Please set `interactive_mode = True`. - On normal mode, no chat history is kept on the server. Set `interactive_mode = False`. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - session_id: determine which instance will be called. If not specified with a value other than -1, using random value directly. - interactive_mode (bool): turn on interactive mode or not. On interactive mode, session history is kept on the server (and vice versa). - stream: whether to stream the results or not. - stop: whether to stop the session response or not. - request_output_len (int): output token nums - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - temperature (float): to modulate the next token probability - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default" """ if request.session_id == -1: VariableInterface.session_id += 1 request.session_id = VariableInterface.session_id if VariableInterface.qos_engine is None: return create_error_response( HTTPStatus.NOT_FOUND, 'cannot parse qos engine config, this api is not work') generation = await VariableInterface.qos_engine.generate_with_qos(request) # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for out in generation: chunk = GenerateResponse(text=out.response, tokens=out.generate_token_len, input_tokens=out.input_token_len, history_tokens=out.history_token_len, finish_reason=out.finish_reason) data = chunk.model_dump_json() yield f'{data}\n' if request.stream: return StreamingResponse(stream_results(), media_type='text/event-stream') else: ret = {} text = '' tokens = 0 finish_reason = None async for out in generation: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await VariableInterface.qos_engine.stop_session( request.session_id) return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected') text += out.response tokens = out.generate_token_len finish_reason = out.finish_reason ret = {'text': text, 'tokens': tokens, 'finish_reason': finish_reason} return JSONResponse(ret)
Generate completion for the request. - On interactive mode, the chat history is kept on the server. Please set `interactive_mode = True`. - On normal mode, no chat history is kept on the server. Set `interactive_mode = False`. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - session_id: determine which instance will be called. If not specified with a value other than -1, using random value directly. - interactive_mode (bool): turn on interactive mode or not. On interactive mode, session history is kept on the server (and vice versa). - stream: whether to stream the results or not. - stop: whether to stop the session response or not. - request_output_len (int): output token nums - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - temperature (float): to modulate the next token probability - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - ignore_eos (bool): indicator for ignoring eos - user_id (str): for qos; if not specified, will set to "default"
8,117
import asyncio import os import time from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Union import uvicorn from fastapi import Depends, FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from fastapi.security.http import HTTPAuthorizationCredentials, HTTPBearer from lmdeploy.messages import (GenerationConfig, PytorchEngineConfig, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig from lmdeploy.serve.async_engine import AsyncEngine from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, ChatCompletionRequestQos, ChatCompletionResponse, ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice, ChatCompletionStreamResponse, ChatMessage, CompletionRequest, CompletionRequestQos, CompletionResponse, CompletionResponseChoice, CompletionResponseStreamChoice, CompletionStreamResponse, DeltaMessage, EmbeddingsRequest, EncodeRequest, EncodeResponse, ErrorResponse, GenerateRequest, GenerateRequestQos, GenerateResponse, ModelCard, ModelList, ModelPermission, UsageInfo) from lmdeploy.serve.qos_engine.qos_engine import QosEngine class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] def create_error_response(status: HTTPStatus, message: str): """Create error response according to http status and message. Args: status (HTTPStatus): HTTP status codes and reason phrases message (str): error message """ return JSONResponse( ErrorResponse(message=message, type='invalid_request_error', code=status.value).model_dump()) class GenerationConfig: """generation parameters used by inference engines. Args: n (int): Define how many chat completion choices to generate for each input message max_new_tokens (int): The maximum number of tokens that can be generated in the chat completion top_p (float): An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass top_k (int): An alternative to sampling with temperature, where the model considers the top_k tokens with the highest probability temperature (float): Sampling temperature repetition_penalty (float): Penalty to prevent the model from generating repeated words or phrases. A value larger than 1 discourages repetition ignore_eos (bool): Indicator to ignore the eos_token_id or not random_seed (int): Seed used when sampling a token stop_words (List[str]): Words that stop generating further tokens bad_words (List[str]): Words that the engine will never generate min_new_tokens (int): The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. """ n: int = 1 max_new_tokens: int = 512 top_p: float = 1.0 top_k: int = 1 temperature: float = 0.8 repetition_penalty: float = 1.0 ignore_eos: bool = False random_seed: int = None stop_words: List[str] = None bad_words: List[str] = None min_new_tokens: int = None skip_special_tokens: bool = True class GenerateRequest(BaseModel): """Generate request.""" prompt: Union[str, List[Dict[str, str]]] session_id: int = -1 interactive_mode: bool = False stream: bool = False stop: Optional[Union[str, List[str]]] = Field(default=None, examples=[None]) request_output_len: Optional[int] = Field(default=None, examples=[None]) # noqa top_p: float = 0.8 top_k: int = 40 temperature: float = 0.8 repetition_penalty: float = 1.0 ignore_eos: bool = False skip_special_tokens: Optional[bool] = True cancel: Optional[bool] = False # cancel a responding request class GenerateResponse(BaseModel): """Generate response.""" text: str tokens: int input_tokens: int history_tokens: int finish_reason: Optional[Literal['stop', 'length']] = None The provided code snippet includes necessary dependencies for implementing the `chat_interactive_v1` function. Write a Python function `async def chat_interactive_v1(request: GenerateRequest, raw_request: Request = None)` to solve the following problem: Generate completion for the request. - On interactive mode, the chat history is kept on the server. Please set `interactive_mode = True`. - On normal mode, no chat history is kept on the server. Set `interactive_mode = False`. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - session_id: determine which instance will be called. If not specified with a value other than -1, using random value directly. - interactive_mode (bool): turn on interactive mode or not. On interactive mode, session history is kept on the server (and vice versa). - stream: whether to stream the results or not. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. - request_output_len (int): output token nums. If not specified, will use maximum possible number for a session. - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - temperature (float): to modulate the next token probability - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. Here is the function: async def chat_interactive_v1(request: GenerateRequest, raw_request: Request = None): """Generate completion for the request. - On interactive mode, the chat history is kept on the server. Please set `interactive_mode = True`. - On normal mode, no chat history is kept on the server. Set `interactive_mode = False`. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - session_id: determine which instance will be called. If not specified with a value other than -1, using random value directly. - interactive_mode (bool): turn on interactive mode or not. On interactive mode, session history is kept on the server (and vice versa). - stream: whether to stream the results or not. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. - request_output_len (int): output token nums. If not specified, will use maximum possible number for a session. - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - temperature (float): to modulate the next token probability - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True. """ if request.cancel: if request.session_id != -1: await VariableInterface.async_engine.stop_session( request.session_id) return { 'text': '', 'tokens': 0, 'input_tokens': 0, 'history_tokens': 0, 'finish_reason': 'stop' } else: return create_error_response( HTTPStatus.BAD_REQUEST, 'please set a session_id to cancel a request') if request.session_id == -1: VariableInterface.session_id += 1 request.session_id = VariableInterface.session_id async_engine = VariableInterface.async_engine sequence_start = async_engine.id2step.get(str(request.session_id), 0) == 0 sequence_end = not request.interactive_mode if isinstance(request.stop, str): request.stop = [request.stop] gen_config = GenerationConfig( max_new_tokens=request.request_output_len, top_p=request.top_p, top_k=request.top_k, temperature=request.temperature, repetition_penalty=request.repetition_penalty, ignore_eos=request.ignore_eos, stop_words=request.stop, skip_special_tokens=request.skip_special_tokens) generation = async_engine.generate( request.prompt, request.session_id, gen_config=gen_config, stream_response=True, # always use stream to enable batching sequence_start=sequence_start, sequence_end=sequence_end) # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for out in generation: chunk = GenerateResponse(text=out.response, tokens=out.generate_token_len, input_tokens=out.input_token_len, history_tokens=out.history_token_len, finish_reason=out.finish_reason) data = chunk.model_dump_json() yield f'{data}\n' if request.stream: return StreamingResponse(stream_results(), media_type='text/event-stream') else: ret = {} text = '' tokens, input_tokens, history_tokens = 0, 0, 0 finish_reason = None async for out in generation: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await async_engine.stop_session(request.session_id) return create_error_response(HTTPStatus.BAD_REQUEST, 'Client disconnected') text += out.response tokens = out.generate_token_len input_tokens = out.input_token_len history_tokens = out.history_token_len finish_reason = out.finish_reason ret = { 'text': text, 'tokens': tokens, 'input_tokens': input_tokens, 'history_tokens': history_tokens, 'finish_reason': finish_reason } return JSONResponse(ret)
Generate completion for the request. - On interactive mode, the chat history is kept on the server. Please set `interactive_mode = True`. - On normal mode, no chat history is kept on the server. Set `interactive_mode = False`. The request should be a JSON object with the following fields: - prompt: the prompt to use for the generation. - session_id: determine which instance will be called. If not specified with a value other than -1, using random value directly. - interactive_mode (bool): turn on interactive mode or not. On interactive mode, session history is kept on the server (and vice versa). - stream: whether to stream the results or not. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. - request_output_len (int): output token nums. If not specified, will use maximum possible number for a session. - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering - temperature (float): to modulate the next token probability - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - ignore_eos (bool): indicator for ignoring eos - skip_special_tokens (bool): Whether or not to remove special tokens in the decoding. Default to be True.
8,118
import asyncio import dataclasses import os import random from argparse import ArgumentError from contextlib import asynccontextmanager from queue import Empty, Queue from threading import Thread from typing import Dict, List, Literal, Optional, Union from lmdeploy.messages import (EngineGenerationConfig, GenerationConfig, PytorchEngineConfig, Response, TurbomindEngineConfig) from lmdeploy.model import ChatTemplateConfig, best_match_model from lmdeploy.tokenizer import DetokenizeState from lmdeploy.utils import _stop_words, get_logger logger = get_logger('lmdeploy') def get_model_name_from_workspace_model(model_dir: str): """Get model name from workspace model.""" from configparser import ConfigParser triton_model_path = os.path.join(model_dir, 'triton_models', 'weights') if not os.path.exists(triton_model_path): return None ini_path = os.path.join(triton_model_path, 'config.ini') # load cfg with open(ini_path, 'r') as f: parser = ConfigParser() parser.read_file(f) return parser['llama']['model_name'] class TurbomindEngineConfig: """TurboMind Engine config. Args: model_name (str): the name of the deployed model, deprecated and has no effect when version > 0.2.1 model_format (str): the layout of the deployed model. It can be one of the following values [hf, llama, awq], `hf` meaning `hf_llama`, `llama` meaning `meta_llama`, `awq` meaning the quantized model by AWQ. tp (int): the number of GPU cards used in tensor parallelism, default to 1 session_len (int): the max session length of a sequence, default to None max_batch_size (int): the max batch size during inference, default to 128 cache_max_entry_count (float): the percentage of gpu memory occupied by the k/v cache. For versions of lmdeploy between `v0.2.0` and `v0.2.1`, it defaults to 0.5, depicting the percentage of TOTAL GPU memory to be allocated to the k/v cache. For lmdeploy versions greater than `v0.2.1`, it defaults to 0.8, signifying the percentage of FREE GPU memory to be reserved for the k/v cache quant_policy (int): , default to 0. When k/v is quantized into 8 bit, set it to 4 rope_scaling_factor (int): scaling factor used for dynamic ntk, default to 0. TurboMind follows the implementation of transformer LlamaAttention use_logn_attn (bool): whether or not to use log attn: default to False download_dir (str): Directory to download and load the weights, default to the default cache directory of huggingface. revision (str): The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. max_prefill_token_num(int): the number of tokens each iteration during prefill, default to 8192 """ # noqa: E501 model_name: Optional[str] = None model_format: Optional[str] = None tp: int = 1 session_len: Optional[int] = None max_batch_size: int = 128 cache_max_entry_count: float = 0.8 quant_policy: int = 0 rope_scaling_factor: float = 0.0 use_logn_attn: bool = False download_dir: Optional[str] = None revision: Optional[str] = None max_prefill_token_num: int = 8192 class PytorchEngineConfig: """PyTorch Engine Config. Args: model_name (str): name of the given model. tp (int): Tensor Parallelism. default 1. session_len (int): Max session length. Default None. max_batch_size (int): Max batch size. Default 128. cache_max_entry_count (float): the percentage of gpu memory occupied by the k/v cache. For lmdeploy versions greater than `v0.2.1`, it defaults to 0.8, signifying the percentage of FREE GPU memory to be reserved for the k/v cache eviction_type (str): What action to perform when kv cache is full, ['recompute', 'copy'], Default 'recompute'. prefill_interval (int): Interval to perform prefill, Default 16. block_size (int): paging cache block size, default 64. num_cpu_blocks (int): Num cpu blocks. If num is 0, cache would be allocate according to current environment. num_gpu_blocks (int): Num gpu blocks. If num is 0, cache would be allocate according to current environment. adapters (dict): The path configs to lora adapters. max_prefill_token_num (int): tokens per iteration. thread_safe (bool): thread safe engine instance. download_dir (str): Directory to download and load the weights, default to the default cache directory of huggingface. revision (str): The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. """ model_name: str = '' tp: int = 1 session_len: int = None max_batch_size: int = 128 cache_max_entry_count: float = 0.8 eviction_type: str = 'recompute' prefill_interval: int = 16 block_size: int = 64 num_cpu_blocks: int = 0 num_gpu_blocks: int = 0 adapters: Dict[str, str] = None max_prefill_token_num: int = 8192 thread_safe: bool = False download_dir: str = None revision: str = None class ChatTemplateConfig: """Parameters for chat template. Args: model_name (str): the name of the deployed model. Determine which chat template will be applied. All the chat template names: `lmdeploy list` system (str | None): begin of the system prompt meta_instruction (str | None): system prompt eosys (str | None): end of the system prompt user (str | None): begin of the user prompt eoh (str | None): end of the user prompt assistant (str | None): begin of the assistant prompt eoa (str | None): end of the assistant prompt capability: ('completion' | 'infilling' | 'chat' | 'python') = None """ # noqa: E501 model_name: str system: Optional[str] = None meta_instruction: Optional[str] = None eosys: Optional[str] = None user: Optional[str] = None eoh: Optional[str] = None assistant: Optional[str] = None eoa: Optional[str] = None separator: Optional[str] = None capability: Optional[Literal['completion', 'infilling', 'chat', 'python']] = None def chat_template(self): attrs = { key: value for key, value in dataclasses.asdict(self).items() if value is not None } if self.model_name in MODELS.module_dict.keys(): model: BaseModel = MODELS.get(self.model_name)(**attrs) else: logger.warning( f'Could not find {self.model_name} in registered models. ' f'Register {self.model_name} using the BaseChatTemplate.') model = BaseChatTemplate(**attrs) return model ]) def best_match_model(query: str) -> Optional[str]: """Get the model that matches the query. Args: query (str): the input query. Could be a model path. Return: str | None: the possible model name or none. """ for name, model in MODELS.module_dict.items(): if model.match(query): return model.match(query) The provided code snippet includes necessary dependencies for implementing the `deduce_a_name` function. Write a Python function `def deduce_a_name( model_path: str, model_name: Optional[str] = None, backend_config: Optional[Union[TurbomindEngineConfig, PytorchEngineConfig]] = None, chat_template_config: Optional[ChatTemplateConfig] = None) -> str` to solve the following problem: Deduce a model name from all the possible arguments. Here is the function: def deduce_a_name( model_path: str, model_name: Optional[str] = None, backend_config: Optional[Union[TurbomindEngineConfig, PytorchEngineConfig]] = None, chat_template_config: Optional[ChatTemplateConfig] = None) -> str: """Deduce a model name from all the possible arguments.""" def _config_model_name(config): if config and config.model_name: return config.model_name return None backend_config_model_name = _config_model_name(backend_config) chat_template_config_model_name = _config_model_name(chat_template_config) model_name = model_name or chat_template_config_model_name or backend_config_model_name # noqa if model_name is None: # model maybe from workspace for turbomind model_name = get_model_name_from_workspace_model(model_path) # may get a model name from model_path if model_name is None: model_name = best_match_model(model_path) if model_name is None: raise ArgumentError(None, f'Please set model_name for {model_path}') else: logger.info(f'matched chat template name: {model_name}') return model_name
Deduce a model name from all the possible arguments.
8,119
from typing import List, Union import numpy as np import tritonclient.grpc as grpcclient from tritonclient.utils import np_to_triton_dtype The provided code snippet includes necessary dependencies for implementing the `prepare_tensor` function. Write a Python function `def prepare_tensor(name, input_tensor)` to solve the following problem: Create grpcclient's InferInput instance according to a given tensor. Here is the function: def prepare_tensor(name, input_tensor): """Create grpcclient's InferInput instance according to a given tensor.""" t = grpcclient.InferInput(name, list(input_tensor.shape), np_to_triton_dtype(input_tensor.dtype)) t.set_data_from_numpy(input_tensor) return t
Create grpcclient's InferInput instance according to a given tensor.
8,120
import json import logging import queue import random import threading from dataclasses import dataclass from enum import Enum from functools import partial from typing import List, Union import google.protobuf.json_format import mmengine import numpy as np import tritonclient.grpc as grpcclient from tritonclient.grpc.service_pb2 import ModelInferResponse from lmdeploy.model import MODELS from lmdeploy.serve.turbomind.utils import (Postprocessor, Preprocessor, prepare_tensor) from lmdeploy.utils import filter_suffix, get_logger class StatusCode(Enum): TRITON_STREAM_END = 0 # end of streaming TRITON_STREAM_ING = 1 # response is in streaming TRITON_SESSION_READY = 2 # session is ready for inference TRITON_SERVER_ERR = -1 # triton server's error TRITON_SESSION_CLOSED = -2 # session has been closed TRITON_SESSION_OUT_OF_LIMIT = -3 # request length out of limit TRITON_SESSION_INVALID_ARG = -4 # invalid argument The provided code snippet includes necessary dependencies for implementing the `stream_callback` function. Write a Python function `def stream_callback(que, result, error)` to solve the following problem: callback function invoked by triton client. Here is the function: def stream_callback(que, result, error): """callback function invoked by triton client.""" if error: print(error) que.put(dict(errcode=StatusCode.TRITON_SERVER_ERR, errmsg=f'{error}')) else: que.put(result.get_response(as_json=True))
callback function invoked by triton client.
8,121
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger node_manager = NodeManager() class ModelPermission(BaseModel): """Model permissions.""" id: str = Field(default_factory=lambda: f'modelperm-{shortuuid.random()}') object: str = 'model_permission' created: int = Field(default_factory=lambda: int(time.time())) allow_create_engine: bool = False allow_sampling: bool = True allow_logprobs: bool = True allow_search_indices: bool = True allow_view: bool = True allow_fine_tuning: bool = False organization: str = '*' group: Optional[str] = None is_blocking: bool = False class ModelCard(BaseModel): """Model cards.""" id: str object: str = 'model' created: int = Field(default_factory=lambda: int(time.time())) owned_by: str = 'lmdeploy' root: Optional[str] = None parent: Optional[str] = None permission: List[ModelPermission] = [] class ModelList(BaseModel): """Model list consists of model cards.""" object: str = 'list' data: List[ModelCard] = [] The provided code snippet includes necessary dependencies for implementing the `available_models` function. Write a Python function `def available_models()` to solve the following problem: Show available models. Here is the function: def available_models(): """Show available models.""" model_cards = [] for model_name in node_manager.model_list: model_cards.append( ModelCard(id=model_name, root=model_name, permission=[ModelPermission()])) return ModelList(data=model_cards)
Show available models.
8,122
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger node_manager = NodeManager() The provided code snippet includes necessary dependencies for implementing the `node_status` function. Write a Python function `def node_status()` to solve the following problem: Show nodes status. Here is the function: def node_status(): """Show nodes status.""" try: return node_manager.status except: # noqa return False
Show nodes status.
8,123
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger class Node(BaseModel): """Node protocol consists of url and status.""" url: str status: Optional[Status] = None node_manager = NodeManager() The provided code snippet includes necessary dependencies for implementing the `add_node` function. Write a Python function `def add_node(node: Node, raw_request: Request = None)` to solve the following problem: Add a node to the manager. - url (str): A http url. Can be the url generated by `lmdeploy serve api_server`. - status (Dict): The description of the node. An example: {models: ['internlm-chat-7b], speed: 1}. The speed here can be RPM or other metric. All the values of nodes should be the same metric. Here is the function: def add_node(node: Node, raw_request: Request = None): """Add a node to the manager. - url (str): A http url. Can be the url generated by `lmdeploy serve api_server`. - status (Dict): The description of the node. An example: {models: ['internlm-chat-7b], speed: 1}. The speed here can be RPM or other metric. All the values of nodes should be the same metric. """ try: node_manager.add(node.url, node.status) return 'Added successfully' except: # noqa return 'Failed to add, please check the input url.'
Add a node to the manager. - url (str): A http url. Can be the url generated by `lmdeploy serve api_server`. - status (Dict): The description of the node. An example: {models: ['internlm-chat-7b], speed: 1}. The speed here can be RPM or other metric. All the values of nodes should be the same metric.
8,124
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger node_manager = NodeManager() The provided code snippet includes necessary dependencies for implementing the `remove_node` function. Write a Python function `def remove_node(node_url: str)` to solve the following problem: Show available models. Here is the function: def remove_node(node_url: str): """Show available models.""" try: node_manager.remove(node_url) return 'Deleted successfully' except: # noqa return 'Failed to delete, please check the input url.'
Show available models.
8,125
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger node_manager = NodeManager() The provided code snippet includes necessary dependencies for implementing the `chat_completions_v1` function. Write a Python function `async def chat_completions_v1(request: ChatCompletionRequest, raw_request: Request = None)` to solve the following problem: Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. A example for chat history is `[{"role": "user", "content":"knock knock"}]`. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int): output token nums - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - session_id (int): if not specified, will set random value Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) Here is the function: async def chat_completions_v1(request: ChatCompletionRequest, raw_request: Request = None): """Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. A example for chat history is `[{"role": "user", "content":"knock knock"}]`. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int): output token nums - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - session_id (int): if not specified, will set random value Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) """ check_response = await node_manager.check_request_model(request.model) if check_response is not None: return check_response node_url = node_manager.get_node_url(request.model) if not node_url: return node_manager.handle_unavailable_model(request.model) request_dict = request.model_dump() start = node_manager.pre_call(node_url) if request.stream is True: response = node_manager.stream_generate(request_dict, node_url, '/v1/chat/completions') background_task = node_manager.create_background_tasks(node_url, start) return StreamingResponse(response, background=background_task) else: response = await node_manager.generate(request_dict, node_url, '/v1/chat/completions') node_manager.post_call(node_url, start) return JSONResponse(json.loads(response))
Completion API similar to OpenAI's API. Refer to `https://platform.openai.com/docs/api-reference/chat/create` for the API specification. The request should be a JSON object with the following fields: - model: model name. Available from /v1/models. - messages: string prompt or chat history in OpenAI format. A example for chat history is `[{"role": "user", "content":"knock knock"}]`. - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - max_tokens (int): output token nums - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - session_id (int): if not specified, will set random value Currently we do not support the following features: - function_call (Users should implement this by themselves) - logit_bias (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty)
8,126
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger node_manager = NodeManager() class CompletionRequest(BaseModel): """Completion request.""" model: str prompt: Union[str, List[Any]] suffix: Optional[str] = None temperature: Optional[float] = 0.7 n: Optional[int] = 1 max_tokens: Optional[int] = 16 stop: Optional[Union[str, List[str]]] = Field(default=None, examples=[None]) stream: Optional[bool] = False top_p: Optional[float] = 1.0 logprobs: Optional[int] = None echo: Optional[bool] = False presence_penalty: Optional[float] = 0.0 frequency_penalty: Optional[float] = 0.0 user: Optional[str] = None # additional argument of lmdeploy repetition_penalty: Optional[float] = 1.0 session_id: Optional[int] = -1 ignore_eos: Optional[bool] = False skip_special_tokens: Optional[bool] = True top_k: Optional[int] = 40 # for opencompass The provided code snippet includes necessary dependencies for implementing the `completions_v1` function. Write a Python function `async def completions_v1(request: CompletionRequest, raw_request: Request = None)` to solve the following problem: Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - session_id (int): if not specified, will set random value - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) Here is the function: async def completions_v1(request: CompletionRequest, raw_request: Request = None): """Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - session_id (int): if not specified, will set random value - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty) """ check_response = await node_manager.check_request_model(request.model) if check_response is not None: return check_response node_url = node_manager.get_node_url(request.model) if not node_url: return node_manager.handle_unavailable_model(request.model) request_dict = request.model_dump() start = node_manager.pre_call(node_url) if request.stream is True: response = node_manager.stream_generate(request_dict, node_url, '/v1/completions') background_task = node_manager.create_background_tasks(node_url, start) return StreamingResponse(response, background=background_task) else: response = await node_manager.generate(request_dict, node_url, '/v1/completions') node_manager.post_call(node_url, start) return JSONResponse(json.loads(response))
Completion API similar to OpenAI's API. Go to `https://platform.openai.com/docs/api-reference/completions/create` for the API specification. The request should be a JSON object with the following fields: - model (str): model name. Available from /v1/models. - prompt (str): the input prompt. - suffix (str): The suffix that comes after a completion of inserted text. - max_tokens (int): output token nums - temperature (float): to modulate the next token probability - top_p (float): If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation. - n (int): How many chat completion choices to generate for each input message. Only support one here. - stream: whether to stream the results or not. Default to false. - repetition_penalty (float): The parameter for repetition penalty. 1.0 means no penalty - user (str): A unique identifier representing your end-user. - stop (str | List[str] | None): To stop generating further tokens. Only accept stop words that's encoded to one token idex. Additional arguments supported by LMDeploy: - ignore_eos (bool): indicator for ignoring eos - session_id (int): if not specified, will set random value - top_k (int): The number of the highest probability vocabulary tokens to keep for top-k-filtering Currently we do not support the following features: - logprobs (not supported yet) - presence_penalty (replaced with repetition_penalty) - frequency_penalty (replaced with repetition_penalty)
8,127
import copy import json import os import os.path as osp import random import time from collections import deque from http import HTTPStatus from typing import Deque, Dict, List, Literal, Optional, Union import numpy as np import requests import uvicorn import yaml from fastapi import BackgroundTasks, Depends, FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from lmdeploy.serve.openai.api_server import (check_api_key, create_error_response) from lmdeploy.serve.openai.protocol import ( # noqa: E501 ChatCompletionRequest, CompletionRequest, ModelCard, ModelList, ModelPermission) from lmdeploy.serve.proxy.constants import (API_TIMEOUT_LEN, LATENCY_DEEQUE_LEN, ErrorCodes, Strategy, err_msg) from lmdeploy.utils import get_logger app = FastAPI(docs_url='/') app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) node_manager = NodeManager() class Strategy(enum.Enum): """Strategy to dispatch requests to nodes.""" RANDOM = enum.auto() MIN_EXPECTED_LATENCY = enum.auto() MIN_OBSERVED_LATENCY = enum.auto() def from_str(cls, name): """get strategy from string.""" if name == 'random': return cls.RANDOM elif name == 'min_expected_latency': return cls.MIN_EXPECTED_LATENCY elif name == 'min_observed_latency': return cls.MIN_OBSERVED_LATENCY else: raise ValueError(f'Invalid strategy: {name}. Supported: random, ' f'min_expected_latency, min_observed_latency.') class VariableInterface: """A IO interface maintaining variables.""" async_engine: AsyncEngine = None session_id: int = 0 api_keys: Optional[List[str]] = None qos_engine: QosEngine = None request_hosts = [] The provided code snippet includes necessary dependencies for implementing the `proxy` function. Write a Python function `def proxy(server_name: str = '0.0.0.0', server_port: int = 10086, strategy: Literal['random', 'min_expected_latency', 'min_observed_latency'] = 'min_expected_latency', api_keys: Optional[Union[List[str], str]] = None, ssl: bool = False, **kwargs)` to solve the following problem: To launch the proxy server. Args: server_name (str): the server name of the proxy. Default to '0.0.0.0'. server_port (str): the server port. Default to 10086. strategy ('random' | 'min_expected_latency' | 'min_observed_latency'): the strategy to dispatch requests to nodes. Default to 'min_expected_latency' api_keys (List[str] | str | None): Optional list of API keys. Accepts string type as a single api_key. Default to None, which means no api key applied. ssl (bool): Enable SSL. Requires OS Environment variables 'SSL_KEYFILE' and 'SSL_CERTFILE'. Here is the function: def proxy(server_name: str = '0.0.0.0', server_port: int = 10086, strategy: Literal['random', 'min_expected_latency', 'min_observed_latency'] = 'min_expected_latency', api_keys: Optional[Union[List[str], str]] = None, ssl: bool = False, **kwargs): """To launch the proxy server. Args: server_name (str): the server name of the proxy. Default to '0.0.0.0'. server_port (str): the server port. Default to 10086. strategy ('random' | 'min_expected_latency' | 'min_observed_latency'): the strategy to dispatch requests to nodes. Default to 'min_expected_latency' api_keys (List[str] | str | None): Optional list of API keys. Accepts string type as a single api_key. Default to None, which means no api key applied. ssl (bool): Enable SSL. Requires OS Environment variables 'SSL_KEYFILE' and 'SSL_CERTFILE'. """ # noqa node_manager.strategy = Strategy.from_str(strategy) if api_keys is not None: if isinstance(api_keys, str): api_keys = api_keys.split(',') from lmdeploy.serve.openai.api_server import VariableInterface VariableInterface.api_keys = api_keys ssl_keyfile, ssl_certfile = None, None if ssl: ssl_keyfile = os.environ['SSL_KEYFILE'] ssl_certfile = os.environ['SSL_CERTFILE'] uvicorn.run(app=app, host=server_name, port=server_port, log_level='info', ssl_keyfile=ssl_keyfile, ssl_certfile=ssl_certfile)
To launch the proxy server. Args: server_name (str): the server name of the proxy. Default to '0.0.0.0'. server_port (str): the server port. Default to 10086. strategy ('random' | 'min_expected_latency' | 'min_observed_latency'): the strategy to dispatch requests to nodes. Default to 'min_expected_latency' api_keys (List[str] | str | None): Optional list of API keys. Accepts string type as a single api_key. Default to None, which means no api key applied. ssl (bool): Enable SSL. Requires OS Environment variables 'SSL_KEYFILE' and 'SSL_CERTFILE'.
8,128
import os from lmdeploy.serve.turbomind.chatbot import Chatbot The provided code snippet includes necessary dependencies for implementing the `input_prompt` function. Write a Python function `def input_prompt(model_name)` to solve the following problem: Input a prompt in the consolo interface. Here is the function: def input_prompt(model_name): """Input a prompt in the consolo interface.""" if model_name == 'codellama': print('\nenter !! to end the input >>>\n', end='') sentinel = '!!' else: print('\ndouble enter to end input >>> ', end='') sentinel = '' # ends when this string is seen return '\n'.join(iter(input, sentinel))
Input a prompt in the consolo interface.
8,129
from typing import Literal, Optional, Union from lmdeploy.messages import PytorchEngineConfig, TurbomindEngineConfig from lmdeploy.model import ChatTemplateConfig class TurbomindEngineConfig: """TurboMind Engine config. Args: model_name (str): the name of the deployed model, deprecated and has no effect when version > 0.2.1 model_format (str): the layout of the deployed model. It can be one of the following values [hf, llama, awq], `hf` meaning `hf_llama`, `llama` meaning `meta_llama`, `awq` meaning the quantized model by AWQ. tp (int): the number of GPU cards used in tensor parallelism, default to 1 session_len (int): the max session length of a sequence, default to None max_batch_size (int): the max batch size during inference, default to 128 cache_max_entry_count (float): the percentage of gpu memory occupied by the k/v cache. For versions of lmdeploy between `v0.2.0` and `v0.2.1`, it defaults to 0.5, depicting the percentage of TOTAL GPU memory to be allocated to the k/v cache. For lmdeploy versions greater than `v0.2.1`, it defaults to 0.8, signifying the percentage of FREE GPU memory to be reserved for the k/v cache quant_policy (int): , default to 0. When k/v is quantized into 8 bit, set it to 4 rope_scaling_factor (int): scaling factor used for dynamic ntk, default to 0. TurboMind follows the implementation of transformer LlamaAttention use_logn_attn (bool): whether or not to use log attn: default to False download_dir (str): Directory to download and load the weights, default to the default cache directory of huggingface. revision (str): The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. max_prefill_token_num(int): the number of tokens each iteration during prefill, default to 8192 """ # noqa: E501 model_name: Optional[str] = None model_format: Optional[str] = None tp: int = 1 session_len: Optional[int] = None max_batch_size: int = 128 cache_max_entry_count: float = 0.8 quant_policy: int = 0 rope_scaling_factor: float = 0.0 use_logn_attn: bool = False download_dir: Optional[str] = None revision: Optional[str] = None max_prefill_token_num: int = 8192 class PytorchEngineConfig: """PyTorch Engine Config. Args: model_name (str): name of the given model. tp (int): Tensor Parallelism. default 1. session_len (int): Max session length. Default None. max_batch_size (int): Max batch size. Default 128. cache_max_entry_count (float): the percentage of gpu memory occupied by the k/v cache. For lmdeploy versions greater than `v0.2.1`, it defaults to 0.8, signifying the percentage of FREE GPU memory to be reserved for the k/v cache eviction_type (str): What action to perform when kv cache is full, ['recompute', 'copy'], Default 'recompute'. prefill_interval (int): Interval to perform prefill, Default 16. block_size (int): paging cache block size, default 64. num_cpu_blocks (int): Num cpu blocks. If num is 0, cache would be allocate according to current environment. num_gpu_blocks (int): Num gpu blocks. If num is 0, cache would be allocate according to current environment. adapters (dict): The path configs to lora adapters. max_prefill_token_num (int): tokens per iteration. thread_safe (bool): thread safe engine instance. download_dir (str): Directory to download and load the weights, default to the default cache directory of huggingface. revision (str): The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. """ model_name: str = '' tp: int = 1 session_len: int = None max_batch_size: int = 128 cache_max_entry_count: float = 0.8 eviction_type: str = 'recompute' prefill_interval: int = 16 block_size: int = 64 num_cpu_blocks: int = 0 num_gpu_blocks: int = 0 adapters: Dict[str, str] = None max_prefill_token_num: int = 8192 thread_safe: bool = False download_dir: str = None revision: str = None class ChatTemplateConfig: """Parameters for chat template. Args: model_name (str): the name of the deployed model. Determine which chat template will be applied. All the chat template names: `lmdeploy list` system (str | None): begin of the system prompt meta_instruction (str | None): system prompt eosys (str | None): end of the system prompt user (str | None): begin of the user prompt eoh (str | None): end of the user prompt assistant (str | None): begin of the assistant prompt eoa (str | None): end of the assistant prompt capability: ('completion' | 'infilling' | 'chat' | 'python') = None """ # noqa: E501 model_name: str system: Optional[str] = None meta_instruction: Optional[str] = None eosys: Optional[str] = None user: Optional[str] = None eoh: Optional[str] = None assistant: Optional[str] = None eoa: Optional[str] = None separator: Optional[str] = None capability: Optional[Literal['completion', 'infilling', 'chat', 'python']] = None def chat_template(self): attrs = { key: value for key, value in dataclasses.asdict(self).items() if value is not None } if self.model_name in MODELS.module_dict.keys(): model: BaseModel = MODELS.get(self.model_name)(**attrs) else: logger.warning( f'Could not find {self.model_name} in registered models. ' f'Register {self.model_name} using the BaseChatTemplate.') model = BaseChatTemplate(**attrs) return model ]) def run_api_server(api_server_url: str, server_name: str = 'localhost', server_port: int = 6006, batch_size: int = 32): """chat with AI assistant through web ui. Args: api_server_url (str): restufl api url server_name (str): the ip address of gradio server server_port (int): the port of gradio server batch_size (int): batch size for running Turbomind directly """ InterFace.api_server_url = api_server_url model_names = get_model_list(f'{api_server_url}/v1/models') model_name = '' if isinstance(model_names, list) and len(model_names) > 0: model_name = model_names[0] else: raise ValueError('gradio can find a suitable model from restful-api') with gr.Blocks(css=CSS, theme=THEME) as demo: state_chatbot = gr.State([]) state_session_id = gr.State(0) with gr.Column(elem_id='container'): gr.Markdown('## LMDeploy Playground') chatbot = gr.Chatbot(elem_id='chatbot', label=model_name) instruction_txtbox = gr.Textbox( placeholder='Please input the instruction', label='Instruction') with gr.Row(): cancel_btn = gr.Button(value='Cancel', interactive=False) reset_btn = gr.Button(value='Reset') with gr.Row(): request_output_len = gr.Slider(1, 2048, value=512, step=1, label='Maximum new tokens') top_p = gr.Slider(0.01, 1, value=0.8, step=0.01, label='Top_p') temperature = gr.Slider(0.01, 1.5, value=0.7, step=0.01, label='Temperature') send_event = instruction_txtbox.submit(chat_stream_restful, [ instruction_txtbox, state_chatbot, cancel_btn, reset_btn, state_session_id, top_p, temperature, request_output_len ], [state_chatbot, chatbot, cancel_btn, reset_btn]) instruction_txtbox.submit( lambda: gr.Textbox.update(value=''), [], [instruction_txtbox], ) cancel_btn.click( cancel_restful_func, [state_chatbot, cancel_btn, reset_btn, state_session_id], [state_chatbot, cancel_btn, reset_btn], cancels=[send_event]) reset_btn.click(reset_restful_func, [instruction_txtbox, state_chatbot, state_session_id], [state_chatbot, chatbot, instruction_txtbox], cancels=[send_event]) def init(): with InterFace.lock: InterFace.global_session_id += 1 new_session_id = InterFace.global_session_id return new_session_id demo.load(init, inputs=None, outputs=[state_session_id]) print(f'server is gonna mount on: http://{server_name}:{server_port}') demo.queue(concurrency_count=batch_size, max_size=100, api_open=True).launch( max_threads=10, share=True, server_port=server_port, server_name=server_name, ) def run_triton_server(triton_server_addr: str, server_name: str = 'localhost', server_port: int = 6006): """chat with AI assistant through web ui. Args: triton_server_addr (str): the communication address of inference server server_name (str): the ip address of gradio server server_port (int): the port of gradio server """ with gr.Blocks(css=CSS, theme=THEME) as demo: log_level = os.environ.get('SERVICE_LOG_LEVEL', 'INFO') llama_chatbot = gr.State( Chatbot(triton_server_addr, log_level=log_level, display=True)) state_chatbot = gr.State([]) state_session_id = gr.State(0) model_name = llama_chatbot.value.model_name reset_all = partial(reset_all_func, model_name=model_name, triton_server_addr=triton_server_addr) with gr.Column(elem_id='container'): gr.Markdown('## LMDeploy Playground') chatbot = gr.Chatbot(elem_id='chatbot', label=model_name) instruction_txtbox = gr.Textbox( placeholder='Please input the instruction', label='Instruction') with gr.Row(): cancel_btn = gr.Button(value='Cancel', interactive=False) reset_btn = gr.Button(value='Reset') with gr.Row(): request_output_len = gr.Slider(1, 2048, value=512, step=1, label='Maximum new tokens') top_p = gr.Slider(0.01, 1, value=0.8, step=0.01, label='Top_p') temperature = gr.Slider(0.01, 1.5, value=0.7, step=0.01, label='Temperature') send_event = instruction_txtbox.submit( add_instruction, [instruction_txtbox, state_chatbot], [instruction_txtbox, state_chatbot]).then(chat_stream, [ state_chatbot, llama_chatbot, cancel_btn, reset_btn, state_session_id, top_p, temperature, request_output_len ], [state_chatbot, chatbot, cancel_btn, reset_btn]) cancel_btn.click(cancel_func, [state_chatbot, llama_chatbot, cancel_btn, reset_btn], [llama_chatbot, chatbot, cancel_btn, reset_btn], cancels=[send_event]) reset_btn.click( reset_all, [instruction_txtbox, state_chatbot, llama_chatbot], [llama_chatbot, state_chatbot, chatbot, instruction_txtbox], cancels=[send_event]) def init(): with InterFace.lock: InterFace.global_session_id += 1 new_session_id = InterFace.global_session_id return new_session_id demo.load(init, inputs=None, outputs=[state_session_id]) print(f'server is gonna mount on: http://{server_name}:{server_port}') demo.queue(concurrency_count=4, max_size=100, api_open=True).launch( max_threads=10, share=True, server_port=server_port, server_name=server_name, ) def run_local(model_path: str, model_name: Optional[str] = None, backend: Literal['turbomind', 'pytorch'] = 'turbomind', backend_config: Optional[Union[PytorchEngineConfig, TurbomindEngineConfig]] = None, chat_template_config: Optional[ChatTemplateConfig] = None, server_name: str = '0.0.0.0', server_port: int = 6006, tp: int = 1, **kwargs): """chat with AI assistant through web ui. Args: model_path (str): the path of a model. It could be one of the following options: - i) A local directory path of a turbomind model which is converted by `lmdeploy convert` command or download from ii) and iii). - ii) The model_id of a lmdeploy-quantized model hosted inside a model repo on huggingface.co, such as "InternLM/internlm-chat-20b-4bit", "lmdeploy/llama2-chat-70b-4bit", etc. - iii) The model_id of a model hosted inside a model repo on huggingface.co, such as "internlm/internlm-chat-7b", "Qwen/Qwen-7B-Chat ", "baichuan-inc/Baichuan2-7B-Chat" and so on. model_name (str): needed when model_path is a pytorch model on huggingface.co, such as "internlm/internlm-chat-7b", "Qwen/Qwen-7B-Chat ", "baichuan-inc/Baichuan2-7B-Chat" and so on. backend (str): either `turbomind` or `pytorch` backend. Default to `turbomind` backend. backend_config (TurbomindEngineConfig | PytorchEngineConfig): beckend config instance. Default to none. chat_template_config (ChatTemplateConfig): chat template configuration. Default to None. server_name (str): the ip address of gradio server. Default to "0.0.0.0". For huggingface space demo, it should be "huggingface-space". server_port (int): the port of gradio server tp (int): tensor parallel for Turbomind """ InterFace.async_engine = AsyncEngine( model_path=model_path, backend=backend, backend_config=backend_config, chat_template_config=chat_template_config, model_name=model_name, tp=tp, **kwargs) with gr.Blocks(css=CSS, theme=THEME) as demo: state_chatbot = gr.State([]) state_session_id = gr.State(0) with gr.Column(elem_id='container'): gr.Markdown('## LMDeploy Playground') chatbot = gr.Chatbot( elem_id='chatbot', label=InterFace.async_engine.engine.model_name) instruction_txtbox = gr.Textbox( placeholder='Please input the instruction', label='Instruction') with gr.Row(): cancel_btn = gr.Button(value='Cancel', interactive=False) reset_btn = gr.Button(value='Reset') with gr.Row(): request_output_len = gr.Slider(1, 2048, value=512, step=1, label='Maximum new tokens') top_p = gr.Slider(0.01, 1, value=0.8, step=0.01, label='Top_p') temperature = gr.Slider(0.01, 1.5, value=0.7, step=0.01, label='Temperature') send_event = instruction_txtbox.submit(chat_stream_local, [ instruction_txtbox, state_chatbot, cancel_btn, reset_btn, state_session_id, top_p, temperature, request_output_len ], [state_chatbot, chatbot, cancel_btn, reset_btn]) instruction_txtbox.submit( lambda: gr.Textbox.update(value=''), [], [instruction_txtbox], ) cancel_btn.click( cancel_local_func, [state_chatbot, cancel_btn, reset_btn, state_session_id], [state_chatbot, cancel_btn, reset_btn], cancels=[send_event]) reset_btn.click(reset_local_func, [instruction_txtbox, state_chatbot, state_session_id], [state_chatbot, chatbot, instruction_txtbox], cancels=[send_event]) def init(): with InterFace.lock: InterFace.global_session_id += 1 new_session_id = InterFace.global_session_id return new_session_id demo.load(init, inputs=None, outputs=[state_session_id]) if server_name == 'huggingface-space': demo.queue(concurrency_count=InterFace.async_engine.instance_num, max_size=100).launch() else: print(f'server is gonna mount on: http://{server_name}:{server_port}') demo.queue(concurrency_count=InterFace.async_engine.instance_num, max_size=100, api_open=True).launch( max_threads=10, share=True, server_port=server_port, server_name=server_name, ) The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def run(model_path_or_server: str, server_name: str = '0.0.0.0', server_port: int = 6006, batch_size: int = 32, backend: Literal['turbomind', 'pytorch'] = 'turbomind', backend_config: Optional[Union[PytorchEngineConfig, TurbomindEngineConfig]] = None, chat_template_config: Optional[ChatTemplateConfig] = None, tp: int = 1, model_name: str = None, **kwargs)` to solve the following problem: chat with AI assistant through web ui. Args: model_path_or_server (str): the path of the deployed model or the tritonserver URL or restful api URL. For example: - ./workspace - 0.0.0.0:23333 - http://0.0.0.0:23333 server_name (str): the ip address of gradio server server_port (int): the port of gradio server batch_size (int): batch size for running Turbomind directly backend (str): either `turbomind` or `pytorch` backend. Default to `turbomind` backend. backend_config (TurbomindEngineConfig | PytorchEngineConfig): beckend config instance. Default to none. chat_template_config (ChatTemplateConfig): chat template configuration. Default to None. tp (int): tensor parallel for Turbomind Here is the function: def run(model_path_or_server: str, server_name: str = '0.0.0.0', server_port: int = 6006, batch_size: int = 32, backend: Literal['turbomind', 'pytorch'] = 'turbomind', backend_config: Optional[Union[PytorchEngineConfig, TurbomindEngineConfig]] = None, chat_template_config: Optional[ChatTemplateConfig] = None, tp: int = 1, model_name: str = None, **kwargs): """chat with AI assistant through web ui. Args: model_path_or_server (str): the path of the deployed model or the tritonserver URL or restful api URL. For example: - ./workspace - 0.0.0.0:23333 - http://0.0.0.0:23333 server_name (str): the ip address of gradio server server_port (int): the port of gradio server batch_size (int): batch size for running Turbomind directly backend (str): either `turbomind` or `pytorch` backend. Default to `turbomind` backend. backend_config (TurbomindEngineConfig | PytorchEngineConfig): beckend config instance. Default to none. chat_template_config (ChatTemplateConfig): chat template configuration. Default to None. tp (int): tensor parallel for Turbomind """ if ':' in model_path_or_server: if 'http:' in model_path_or_server: from lmdeploy.serve.gradio.api_server_backend import run_api_server run_api_server(model_path_or_server, server_name, server_port, batch_size) else: from lmdeploy.serve.gradio.triton_server_backend import \ run_triton_server run_triton_server(model_path_or_server, server_name, server_port) else: from lmdeploy.serve.gradio.turbomind_coupled import run_local run_local(model_path_or_server, server_name=server_name, server_port=server_port, backend=backend, backend_config=backend_config, chat_template_config=chat_template_config, model_name=model_name, batch_size=batch_size, tp=tp, **kwargs)
chat with AI assistant through web ui. Args: model_path_or_server (str): the path of the deployed model or the tritonserver URL or restful api URL. For example: - ./workspace - 0.0.0.0:23333 - http://0.0.0.0:23333 server_name (str): the ip address of gradio server server_port (int): the port of gradio server batch_size (int): batch size for running Turbomind directly backend (str): either `turbomind` or `pytorch` backend. Default to `turbomind` backend. backend_config (TurbomindEngineConfig | PytorchEngineConfig): beckend config instance. Default to none. chat_template_config (ChatTemplateConfig): chat template configuration. Default to None. tp (int): tensor parallel for Turbomind
8,130
import itertools import logging from typing import Optional import torch from transformers import GenerationConfig, PreTrainedModel from lmdeploy.utils import get_logger from .adapters import init_adapter from .dist import get_local_rank, get_rank, get_world_size from .model import accel_model, init_model from .session import BasicSessionManagerWithHistory from .utils import BasicStreamer, TerminalIO, control if __name__ == '__main__': cli() def get_logger( name: Optional[str] = None, log_file: Optional[str] = None, log_level: int = logging.INFO, file_mode: str = 'w', log_formatter: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) -> Logger: """Initialize and get a logger by name. If the logger has not been initialized, this method will initialize the logger by adding one or two handlers, otherwise the initialized logger will be directly returned. During initialization, a StreamHandler will always be added. If `log_file` is specified, a FileHandler will also be added. Args: name (str): Logger name. log_file (str | None): The log filename. If specified, a FileHandler will be added to the logger. log_level (int): The logger level. file_mode (str): The file mode used in opening log file. Defaults to 'w'. log_formatter (str): The logger output format. Returns: logging.Logger: The expected logger. """ logger = logging.getLogger(name) if name in logger_initialized: return logger # handle hierarchical names # e.g., logger "a" is initialized, then logger "a.b" will skip the # initialization since it is a child of "a". for logger_name in logger_initialized: if name.startswith(logger_name): return logger # handle duplicate logs to the console for handler in logger.root.handlers: if type(handler) is logging.StreamHandler: handler.setLevel(logging.ERROR) stream_handler = logging.StreamHandler(stream=sys.stdout) handlers = [stream_handler] if log_file is not None: # Here, the default behaviour of the official logger is 'a'. Thus, we # provide an interface to change the file mode to the default # behaviour. file_handler = logging.FileHandler(log_file, file_mode) handlers.append(file_handler) formatter = ColorFormatter(log_formatter) for handler in handlers: handler.setFormatter(formatter) handler.setLevel(log_level) handler.addFilter(FilterDuplicateWarning(name)) logger.addHandler(handler) logger.setLevel(log_level) logger.propagate = False logger_initialized[name] = True return logger def get_rank(): """Get rank of current process. Assume environment variable ``RANK`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('RANK', '0')) def set_logging(log_file: str, debug: bool): torch.set_printoptions(linewidth=120) level = logging.DEBUG if debug else logging.INFO log_file = log_file or 'chat.log' if r := get_rank() != 0: log_file = log_file + f'.{r}' format = '%(filename)s: \ %(levelname)s: \ %(funcName)s(): \ %(lineno)d:\t \ %(message)s' logger = get_logger(__name__, log_file=log_file, log_level=level, file_mode='w', log_formatter=format) print(f'Worker {get_rank()} logging to {log_file}') return logger
null
8,131
import itertools import logging from typing import Optional import torch from transformers import GenerationConfig, PreTrainedModel from lmdeploy.utils import get_logger from .adapters import init_adapter from .dist import get_local_rank, get_rank, get_world_size from .model import accel_model, init_model from .session import BasicSessionManagerWithHistory from .utils import BasicStreamer, TerminalIO, control def main( model_path: str, tokenizer_path: Optional[str] = None, accel: Optional[str] = None, max_new_tokens: int = 128, temperature: float = 0.8, top_p: float = 0.95, seed: int = 0, use_fast_tokenizer: bool = True, max_alloc: int = 2048, max_session_len: int = None, log_file: Optional[str] = None, debug: bool = False, adapter: Optional[str] = None, ): """Chat with model through terminal. Args: model_path (str): Path to model. tokenizer_path (str): Path to tokenizer. accel (str): Model accelerator. max_new_tokens (int): Maximum number of tokens to generate. temperature (float): Temperature for sampling. top_p (float): Top p for sampling. seed (int): Random seed. use_fast_tokenizer (bool): Whether to use fast tokenizer. This argument is directly pass to transformer's ``AutoTokenizer.from_pretrained``. Generally, user should choose to use fast tokenizers. But if using fast raise some error, try to force using a slow one. max_alloc (int): Maximum memory to allocate (for deepspeed). max_session_len (int): Maximum number of tokens allowed for all chat sessions. This include both history and current session. log_file (str): Path to log file. debug (bool): Whether to enable debug mode. adapter (str): Force to use an adapter. Generally user should not use this argument because adapter is selected based on the type of model. Only when it is impossible, e.g. distinguishing llama 1/2 based on `LlamaforCausalLM` class, this argument is required. Currently, only "llama1" is acceptable for llama1 models. """ # noqa: E501 logger = set_logging(log_file, debug) # workers should sync in sampling torch.manual_seed(seed) local_rank = get_local_rank() world_size = get_world_size() # Init model and tokenizer if not tokenizer_path: tokenizer_path = model_path model, tokenizer = init_model( model_path, tokenizer_path, use_fast_tokenizer=use_fast_tokenizer, ) # Init adapter based on model and tokenizer adapter = init_adapter(model, tokenizer, adapter) # Accelerate model model: PreTrainedModel = accel_model(model, accel, max_alloc=max_alloc, tp_size=world_size) # warmup warmup_config = GenerationConfig( max_new_tokens=1, do_sample=temperature > 0, temperature=temperature, top_p=top_p, ) model.generate(torch.tensor([[6]], device=get_local_rank()), warmup_config) gen_config = GenerationConfig( max_new_tokens=max_new_tokens, do_sample=temperature > 0, temperature=temperature, top_p=top_p, ) # Session manager handling history max_session_len = max_alloc if max_session_len is None else max_session_len sm = BasicSessionManagerWithHistory(max_session_len=max_session_len, start_ids=adapter.start_ids, sep_ids=adapter.sep_ids) io = TerminalIO() streamer = BasicStreamer(adapter.decode, io.output) for r in itertools.count(1): # User input from IO logger.info(f'Round {r}') prompt: str = io.input() logger.info(f'User input: {prompt}') # Allow user to change config during runtime or exit if control(prompt, gen_config, sm): continue # Tokenize and apply model specific templates input_ids = adapter.encode_and_decorate(prompt) logger.info(f'Input ids:\n{input_ids}') # Prepend chat history (tensor concatenation) input_ids = sm.prepend_history(input_ids) logger.info(f'Input ids with history:\n{input_ids}') # Generate input_ids = input_ids.cuda(local_rank) # returned tensor including input and generated output output = model.generate(input_ids, gen_config, streamer=streamer, stopping_criteria=adapter.stopping_criteria) logger.info(f'Output:\n{output}') # Save output into session manager and maybe trim some history sm.add_to_history(output) def cli(): import fire fire.Fire(main)
null
8,132
from transformers.generation.streamers import BaseStreamer from lmdeploy.utils import get_logger from .dist import get_rank, master_only, master_only_and_broadcast_general logger = get_logger(__name__) def get_rank(): """Get rank of current process. Assume environment variable ``RANK`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('RANK', '0')) The provided code snippet includes necessary dependencies for implementing the `control` function. Write a Python function `def control(prompt, gen_config, sm)` to solve the following problem: Allow user to control generation config and session manager. Return: True if control command applied, False otherwise. Here is the function: def control(prompt, gen_config, sm): """Allow user to control generation config and session manager. Return: True if control command applied, False otherwise. """ if prompt == 'exit': exit(0) if prompt == 'clear': sm.new_session() logger.info('Session cleared') return True # Re-config during runtime if prompt.startswith('config set'): try: keqv = prompt.split()[-1] k, v = keqv.split('=') v = eval(v) gen_config.__setattr__(k, v) logger.info(f'Worker {get_rank()} set {k} to {repr(v)}') logger.info(f'Generator config changed to: {gen_config}') return True except: # noqa logger.info( 'illegal instruction, treated as normal conversation. ') return False
Allow user to control generation config and session manager. Return: True if control command applied, False otherwise.
8,133
import functools import os import torch from torch.distributed import broadcast, broadcast_object_list, is_initialized The provided code snippet includes necessary dependencies for implementing the `get_world_size` function. Write a Python function `def get_world_size()` to solve the following problem: Get rank of current process. Assume environment variable ``WORLD_SIZE`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables Here is the function: def get_world_size(): """Get rank of current process. Assume environment variable ``WORLD_SIZE`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('WORLD_SIZE', '1'))
Get rank of current process. Assume environment variable ``WORLD_SIZE`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables
8,134
import functools import os import torch from torch.distributed import broadcast, broadcast_object_list, is_initialized def get_rank(): """Get rank of current process. Assume environment variable ``RANK`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('RANK', '0')) The provided code snippet includes necessary dependencies for implementing the `master_only` function. Write a Python function `def master_only(func)` to solve the following problem: Decorator to run a function only on the master process. Here is the function: def master_only(func): """Decorator to run a function only on the master process.""" @functools.wraps(func) def wrapper(*args, **kwargs): if is_initialized(): if get_rank() != 0: return None return func(*args, **kwargs) return wrapper
Decorator to run a function only on the master process.
8,135
import functools import os import torch from torch.distributed import broadcast, broadcast_object_list, is_initialized def get_rank(): """Get rank of current process. Assume environment variable ``RANK`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('RANK', '0')) The provided code snippet includes necessary dependencies for implementing the `master_only_and_broadcast_general` function. Write a Python function `def master_only_and_broadcast_general(func)` to solve the following problem: Decorator to run a function only on the master process and broadcast the result to all processes. Here is the function: def master_only_and_broadcast_general(func): """Decorator to run a function only on the master process and broadcast the result to all processes.""" @functools.wraps(func) def wrapper(*args, **kwargs): if is_initialized(): if get_rank() == 0: result = [func(*args, **kwargs)] else: result = [None] broadcast_object_list(result, src=0) result = result[0] else: result = func(*args, **kwargs) return result return wrapper
Decorator to run a function only on the master process and broadcast the result to all processes.
8,136
import functools import os import torch from torch.distributed import broadcast, broadcast_object_list, is_initialized def get_local_rank(): """Get local rank of current process. Assume environment variable ``LOCAL_RANK`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('LOCAL_RANK', '0')) def get_rank(): """Get rank of current process. Assume environment variable ``RANK`` is properly set by some launcher. See: https://pytorch.org/docs/stable/elastic/run.html#environment-variables """ # noqa: E501 return int(os.getenv('RANK', '0')) The provided code snippet includes necessary dependencies for implementing the `master_only_and_broadcast_tensor` function. Write a Python function `def master_only_and_broadcast_tensor(func)` to solve the following problem: Decorator to run a function only on the master process and broadcast the result to all processes. Note: Require CUDA tensor. Note: Not really work because we don't know the shape aforehand, for cpu tensors, use master_only_and_broadcast_general Here is the function: def master_only_and_broadcast_tensor(func): """Decorator to run a function only on the master process and broadcast the result to all processes. Note: Require CUDA tensor. Note: Not really work because we don't know the shape aforehand, for cpu tensors, use master_only_and_broadcast_general """ @functools.wraps(func) def wrapper(*args, size, dtype, **kwargs): if is_initialized(): if get_rank() == 0: result = func(*args, **kwargs) else: result = torch.empty(size=size, dtype=dtype, device=get_local_rank()) broadcast(result, src=0) # print(f'rank {get_rank()} received {result}') else: result = func(*args, **kwargs) return result return wrapper
Decorator to run a function only on the master process and broadcast the result to all processes. Note: Require CUDA tensor. Note: Not really work because we don't know the shape aforehand, for cpu tensors, use master_only_and_broadcast_general
8,137
import argparse import queue import warnings from typing import List, Optional import pynvml import torch import torch.multiprocessing as mp from torch.nn.utils.rnn import pad_sequence from transformers import (AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase) from lmdeploy.utils import get_logger from .model import accel_model, init_model The provided code snippet includes necessary dependencies for implementing the `safe_numel` function. Write a Python function `def safe_numel(free_mem, model_size, max_intermediate)` to solve the following problem: Number of elements without out-of-memory. Here is the function: def safe_numel(free_mem, model_size, max_intermediate): """Number of elements without out-of-memory.""" return int(free_mem - model_size) // max_intermediate
Number of elements without out-of-memory.
8,138
import argparse import queue import warnings from typing import List, Optional import pynvml import torch import torch.multiprocessing as mp from torch.nn.utils.rnn import pad_sequence from transformers import (AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase) from lmdeploy.utils import get_logger from .model import accel_model, init_model The provided code snippet includes necessary dependencies for implementing the `avail_gpus` function. Write a Python function `def avail_gpus(percentage=0.96)` to solve the following problem: Detect available gpus. Args: percentage (float): The minimum percentage of free memory to be considered as available. Return: A list of gpu ids. average free memory on single gpu. Here is the function: def avail_gpus(percentage=0.96): """Detect available gpus. Args: percentage (float): The minimum percentage of free memory to be considered as available. Return: A list of gpu ids. average free memory on single gpu. """ gpus = [] mems = [] pynvml.nvmlInit() for i in range(torch.cuda.device_count()): handle = pynvml.nvmlDeviceGetHandleByIndex(int(i)) mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle) free, total = int(mem_info.free), int(mem_info.total) if free / total > percentage: gpus.append(i) mems.append(free) pynvml.nvmlShutdown() if len(gpus) == 0: raise RuntimeError('No GPU available.') return gpus, sum(mems) / len(mems)
Detect available gpus. Args: percentage (float): The minimum percentage of free memory to be considered as available. Return: A list of gpu ids. average free memory on single gpu.
8,139
import argparse import queue import warnings from typing import List, Optional import pynvml import torch import torch.multiprocessing as mp from torch.nn.utils.rnn import pad_sequence from transformers import (AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase) from lmdeploy.utils import get_logger from .model import accel_model, init_model def decode_single(model: PreTrainedModel, input_ids: torch.Tensor, attention_mask: torch.Tensor = None, return_logits=True): """Decode a single batch. Args: model (PreTrainedModel): Pretrained model. input_ids (torch.Tensor): A batch of input ids. attention_mask (torch.Tensor): A batch of attention masks. Returns: torch.Tensor: A batch of probabilities (on CPU). Note: This function assume input_ids[i] = [bos, x1, x2, ..., xn] and return prob = [p(x1|bos), p(x2|bos,x1), ..., p(xn|bos..xn-1)] So prob is shorter than input_ids by 1. """ # Call Causal LM forward outputs = model(input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=False, output_attentions=False, use_cache=False, return_dict=True) # fp32, [bs, seq_len, vocab_size] logits = outputs.logits if not return_logits: # inplace softmax to get probs torch.softmax(logits, dim=-1, out=logits) # Shift to fetch probabilities shift_labels = input_ids[..., 1:].contiguous() shift_probs = logits[..., :-1, :].contiguous() logits = torch.gather(shift_probs, -1, shift_labels.unsqueeze(-1)) if attention_mask is not None: logits *= attention_mask[..., None] logits = logits.cpu() return logits def init_model(model_path: str, tokenizer_path: Optional[str] = None, use_fast_tokenizer=True): """Initialize model and tokenizer from given model path. Args: model_path (str): Path to model. tokenizer_path (str): Path to tokenizer. use_fast_tokenizer (bool): Whether to use fast tokenizer. Note: If the model is converted from new version of transformers, use_fast_tokenizer should be True. If using depodaca/llama-xb-hf, use_fast_tokenizer should be False. """ start = time.monotonic() if not tokenizer_path: tokenizer_path = model_path tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, use_fast=use_fast_tokenizer, trust_remote_code=True) with LoadWoInit(): model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16, trust_remote_code=True) logger.info(f'Model loaded in {time.monotonic() - start:.1f} seconds') logger.info(f'Model loaded from {model_path}') logger.debug(model) return model, tokenizer def accel_model(model, accel: Optional[str] = None, gpu_id=None, max_alloc=2048, tp_size=1): """Accelerate model with given accelerator. Note: Currently we support only deepspeed or just no acceleration. """ logger.info(f'Accelerate model with {accel}') if accel is None: # No acceleration, just to cuda # assume single gpu single process # user is responsible to assign the gpu id via CUDA_VISIBLE_DEVICES # noqa: E501 gpu_id = gpu_id if gpu_id is not None else get_local_rank() model = model.cuda(gpu_id) elif accel.lower() == 'deepspeed': # Use deepspeed inference inject fast kernel and/or tensor parallel try: import deepspeed except ImportError as e: raise ImportError('--accel=deepspeed is specified but ' 'deepspeed is not installed.\n' 'Install with `pip install deepspeed`.') from e config = dict( tensor_parallel=dict(tp_size=tp_size), # Use world size in general dtype=torch.float16, replace_with_kernel_inject=True, max_out_tokens=max_alloc, ) if 'InternLM' in model.__class__.__name__: try: # Use customized deepspeed supporting InternLM # https://github.com/wangruohui/DeepSpeed/tree/support_internlm_0.10.0 (commit cdef2ce) # noqa: E501 from deepspeed.module_inject.containers.internlm import \ InternLMLayerPolicy # noqa: E501 except ImportError: # InternLM is not officially supported by DeepSpeed # Set replace_with_kernel_inject=False to use AutoTP config.update({'replace_with_kernel_inject': False}) warnings.warn( '\033[0;93m' 'Current installation of deepspeed does not ' 'support InternLM. Disable kernel injection. ' 'To support InternLM, install customized deepspeed with ' '`pip install git+https://github.com/wangruohui/DeepSpeed@support_internlm_0.10.0`' # noqa: E501 '\033[0m') else: for module in model.modules(): # Since remote code is dynamically located, # we need to do this dynamically if module.__class__.__name__ == 'InternLMDecoderLayer': InternLMLayerPolicy._orig_layer_class = module.__class__ # noqa: E501 break logger.debug(f'Using deepspeed config\n{config}') model = deepspeed.init_inference( model=model, # Transformers models config=config, ) # for k, v in model.named_parameters(): # logger.debug(f"{k}: v.device") else: raise ValueError(f'Unsupported accelerator {accel}.') logger.debug(model) return model def worker_fn(model_path: str, inq: mp.Queue, outq: mp.Queue, accel: Optional[str] = None, gpu_id=0): # torch.set_default_device(gpu_id) model, _ = init_model(model_path) model = model.eval() model = accel_model(model, accel, gpu_id=gpu_id) while True: try: idx, args = inq.get(timeout=1) except queue.Empty: continue if idx is None: print(f'Worker {gpu_id} received exit signal.') break # print(args) input_ids, input_lens, *args = args input_ids = input_ids.cuda(gpu_id) max_len = max(input_lens) assert max_len == input_ids.size(-1), \ f'input_ids.shape = {input_ids.shape}, max_len = {max_len}' input_lens = torch.tensor(input_lens, device=gpu_id) attention_mask = \ torch.arange(max_len, device=gpu_id)[None, :] < input_lens[:, None] assert attention_mask.shape == input_ids.shape, \ f'attention_mask.shape = {attention_mask.shape}' try: probs = decode_single(model, input_ids, attention_mask, *args) except torch.cuda.OutOfMemoryError: warnings.warn( f'OOM on GPU {gpu_id}, discard prompts at indics {idx}.') probs = torch.empty((input_ids.size(0), 0), dtype=torch.float32, device='cpu') outq.put((idx, probs)) print(f'Exiting worker {gpu_id} ...') inq.close() outq.close() print(f'Worker {gpu_id} finished.')
null
8,140
import argparse import queue import warnings from typing import List, Optional import pynvml import torch import torch.multiprocessing as mp from torch.nn.utils.rnn import pad_sequence from transformers import (AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase) from lmdeploy.utils import get_logger from .model import accel_model, init_model def _format(ts, start, end): if start < 0: start += len(ts) if end <= 0: end += len(ts) return '\n'.join( (f'{i}\t{t}' for i, t in zip(range(start, end), ts[start:end])))
null
8,141
import os import random from typing import List from lmdeploy.messages import EngineGenerationConfig, PytorchEngineConfig from lmdeploy.model import MODELS, best_match_model from lmdeploy.tokenizer import DetokenizeState, Tokenizer def input_prompt(model_name): """Input a prompt in the consolo interface.""" if model_name == 'codellama': print('\nenter !! to end the input >>>\n', end='') sentinel = '!!' else: print('\ndouble enter to end input >>> ', end='') sentinel = '' # ends when this string is seen return '\n'.join(iter(input, sentinel)) def valid_str(string, coding='utf-8'): """decode text according to its encoding type.""" invalid_chars = [b'\xef\xbf\xbd'] bstr = bytes(string, coding) for invalid_char in invalid_chars: bstr = bstr.replace(invalid_char, b'') ret = bstr.decode(encoding=coding, errors='ignore') return ret def _stop_words(stop_words: List[str], tokenizer: Tokenizer): """Return a list of token ids corresponding to stop-words.""" if stop_words is None: return None assert isinstance(stop_words, List) and \ all(isinstance(elem, str) for elem in stop_words), \ f'stop_words must be a list but got {type(stop_words)}' stop_words = [ tokenizer.encode(stop_word, False)[-1] for stop_word in stop_words ] assert isinstance(stop_words, List) and all( isinstance(elem, int) for elem in stop_words), 'invalid stop_words' return stop_words class EngineGenerationConfig(GenerationConfig): """generation parameter used by the inference engines.""" stop_words: List[int] = None bad_words: List[int] = None def From(gen_config: GenerationConfig, tokenizer: Tokenizer): """convert `GenerationConfig` to `EngineGenerationConfig` Args: gen_config (GenerationConfig): an instance of class `GenerationConfig` tokenizer (Tokenizer): a tokenizer to encode the `stop_words` and `bad_words` in `gen_config` Returns: EngineGenerationConfig: the generation config used by inference engines Examples: >>> from lmdeploy import Tokenizer, GenerationConfig, EngineGenerationConfig >>> tokenizer = Tokenizer('internlm/internlm-chat-7b') >>> gen_config = GenerationConfig(stop_words=['<eoa>']) >>> gen_config = EngineGenerationConfig.From(gen_config, tokenizer) """ # noqa E501 def special_word_token_ids(words): if words is not None: assert isinstance(words, List) and \ all(isinstance(elem, str) for elem in words), \ f'stop_words must be a list of str but got {type(words)}' indexes = [] for word in words: indexes += tokenizer.indexes_containing_token(word) return indexes return None return EngineGenerationConfig( n=gen_config.n, max_new_tokens=gen_config.max_new_tokens, min_new_tokens=gen_config.min_new_tokens, top_p=gen_config.top_p, top_k=gen_config.top_k, temperature=gen_config.temperature, repetition_penalty=gen_config.repetition_penalty, ignore_eos=gen_config.ignore_eos, random_seed=gen_config.random_seed, skip_special_tokens=gen_config.skip_special_tokens, stop_words=special_word_token_ids(gen_config.stop_words), bad_words=special_word_token_ids(gen_config.bad_words)) class PytorchEngineConfig: """PyTorch Engine Config. Args: model_name (str): name of the given model. tp (int): Tensor Parallelism. default 1. session_len (int): Max session length. Default None. max_batch_size (int): Max batch size. Default 128. cache_max_entry_count (float): the percentage of gpu memory occupied by the k/v cache. For lmdeploy versions greater than `v0.2.1`, it defaults to 0.8, signifying the percentage of FREE GPU memory to be reserved for the k/v cache eviction_type (str): What action to perform when kv cache is full, ['recompute', 'copy'], Default 'recompute'. prefill_interval (int): Interval to perform prefill, Default 16. block_size (int): paging cache block size, default 64. num_cpu_blocks (int): Num cpu blocks. If num is 0, cache would be allocate according to current environment. num_gpu_blocks (int): Num gpu blocks. If num is 0, cache would be allocate according to current environment. adapters (dict): The path configs to lora adapters. max_prefill_token_num (int): tokens per iteration. thread_safe (bool): thread safe engine instance. download_dir (str): Directory to download and load the weights, default to the default cache directory of huggingface. revision (str): The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. """ model_name: str = '' tp: int = 1 session_len: int = None max_batch_size: int = 128 cache_max_entry_count: float = 0.8 eviction_type: str = 'recompute' prefill_interval: int = 16 block_size: int = 64 num_cpu_blocks: int = 0 num_gpu_blocks: int = 0 adapters: Dict[str, str] = None max_prefill_token_num: int = 8192 thread_safe: bool = False download_dir: str = None revision: str = None MODELS = Registry('model', locations=['lmdeploy.model']) ]) def best_match_model(query: str) -> Optional[str]: """Get the model that matches the query. Args: query (str): the input query. Could be a model path. Return: str | None: the possible model name or none. """ for name, model in MODELS.module_dict.items(): if model.match(query): return model.match(query) class DetokenizeState: """A state collection of incrementally detekenization. Args: ids_offset (int): offset to all input ids. In LMDeploy, the output ids length is not one by one. It could be random by random. prev_tokens (List[str] | None): for incrementally decoding. Default to None, which means the first round. prefix_offset (int): the start index of tokens to be converted to string (prev + new tokens). Default to 0 for the first round. read_offset (int): the end index of tokens to be converted to string (prev token). Default to 0 for the first round. """ ids_offset: int = 0 prev_tokens: Optional[List[str]] = None prefix_offset: int = 0 read_offset: int = 0 def as_tuple(self) -> Tuple: """Return a tuple of states.""" return (self.ids_offset, self.prev_tokens, self.prefix_offset, self.read_offset) The provided code snippet includes necessary dependencies for implementing the `run_chat` function. Write a Python function `def run_chat(model_path: str, engine_config: PytorchEngineConfig, gen_config: EngineGenerationConfig = None, session_id: int = 1, trust_remote_code: bool = True)` to solve the following problem: An example to perform model inference through the command line interface. Args: model_path (str): the huggingface model path. engine_config (PytorchEngineConfig): Config of engine. gen_config (EngineGenerationConfig): Config of generation. session_id (int): the identical id of a session. trust_remote_code (bool): trust remote code. Here is the function: def run_chat(model_path: str, engine_config: PytorchEngineConfig, gen_config: EngineGenerationConfig = None, session_id: int = 1, trust_remote_code: bool = True): """An example to perform model inference through the command line interface. Args: model_path (str): the huggingface model path. engine_config (PytorchEngineConfig): Config of engine. gen_config (EngineGenerationConfig): Config of generation. session_id (int): the identical id of a session. trust_remote_code (bool): trust remote code. """ from lmdeploy.pytorch.engine import Engine tm_model = Engine.from_pretrained(model_path, engine_config=engine_config, trust_remote_code=trust_remote_code) tokenizer = tm_model.tokenizer generator = tm_model.create_instance() adapter_name = None if engine_config.adapters is not None: adapter_name = next(iter(engine_config.adapters.keys())) if gen_config is None: gen_config = EngineGenerationConfig() nth_round = 1 step = 0 seed = random.getrandbits(64) model_name = engine_config.model_name if model_name is None: model_name = best_match_model(model_path) assert model_name is not None, 'Can not find match model template' print(f'match template: <{model_name}>') model = MODELS.get(model_name)() stop_words = _stop_words(model.stop_words, tokenizer) while True: prompt = input_prompt(model_name) if prompt == 'exit': exit(0) elif prompt == 'end': generator.end(session_id) nth_round = 1 step = 0 seed = random.getrandbits(64) else: prompt = model.get_prompt(prompt, nth_round == 1) input_ids = tokenizer.encode(prompt, nth_round == 1) session_len = model.session_len if session_len is None: session_len = tm_model.session_len if step >= session_len: print('WARNING: exceed session max length.' ' Please end the session.') continue print(f'{prompt} ', end='', flush=True) state = DetokenizeState() gen_config.random_seed = seed gen_config.stop_words = stop_words for outputs in generator.stream_infer(session_id=session_id, input_ids=input_ids, gen_config=gen_config, adapter_name=adapter_name): status, res, tokens = outputs # decode res response, state = tokenizer.detokenize_incrementally( res, state) response = valid_str(response) print(f'{response}', end='', flush=True) # update step step += len(input_ids) + tokens print() nth_round += 1
An example to perform model inference through the command line interface. Args: model_path (str): the huggingface model path. engine_config (PytorchEngineConfig): Config of engine. gen_config (EngineGenerationConfig): Config of generation. session_id (int): the identical id of a session. trust_remote_code (bool): trust remote code.
8,142
from typing import Dict, Union import numpy as np from ...adapter.adapter import ADAPTER_MANAGER, SchedulerAdapter from ...messages import SchedulerSequence from .base_block_manager import BaseBlockManager The provided code snippet includes necessary dependencies for implementing the `_div_up` function. Write a Python function `def _div_up(x, n)` to solve the following problem: perform div up. Here is the function: def _div_up(x, n): """perform div up.""" return (x + n - 1) // n
perform div up.
8,143
from typing import Union import numpy as np from ...adapter.adapter import ADAPTER_MANAGER, SchedulerAdapter from ...block import LogicalTokenBlocks from ...messages import SchedulerSequence from .default_block_manager import DefaultBlockManager The provided code snippet includes necessary dependencies for implementing the `_div_up` function. Write a Python function `def _div_up(x, n)` to solve the following problem: perform div up. Here is the function: def _div_up(x, n): """perform div up.""" return (x + n - 1) // n
perform div up.
8,144
from typing import Union import numpy as np from ...adapter.adapter import ADAPTER_MANAGER, SchedulerAdapter from ...block import LogicalTokenBlocks from ...messages import SchedulerSequence from .default_block_manager import DefaultBlockManager The provided code snippet includes necessary dependencies for implementing the `_last_block_size` function. Write a Python function `def _last_block_size(history_len: int, block_size: int)` to solve the following problem: last block size. Here is the function: def _last_block_size(history_len: int, block_size: int): """last block size.""" last = history_len % block_size last = last if last != 0 else block_size return last
last block size.
8,145
from typing import Union import numpy as np from ...adapter.adapter import ADAPTER_MANAGER, SchedulerAdapter from ...block import LogicalTokenBlocks from ...messages import SchedulerSequence from .default_block_manager import DefaultBlockManager class SchedulerSequence: """Scheduler message.""" seq_id: int token_ids: Tensor session: SchedulerSession block_size: int history_token_ids: list = field(default_factory=list) num_new_tokens: int = 0 sampling_param: SamplingParam = field(default_factory=SamplingParam) status: MessageStatus = MessageStatus.WAITING logical_blocks: LogicalTokenBlocks = field( default_factory=LogicalTokenBlocks) sender_id: int = -1 req_id: int = -1 adapter_name: str = None arrive_time: float = 0.0 meta: Any = None return_logits: bool = False random_offsets: int = 0 def history_len(self) -> int: """get history length.""" return len(self.history_token_ids) def session_id(self) -> int: """get session id.""" return self.session.session_id def num_all_tokens(self) -> int: """num all tokens.""" return len(self.token_ids) + self.history_len def update_token_ids(self, token_ids: Tensor, update_history: bool = True): """Update token ids, old token ids will be added to history.""" if update_history: self.history_token_ids += self.token_ids.tolist() if not isinstance(token_ids, Tensor): token_ids = self.token_ids.new_tensor(token_ids) if token_ids.dim() == 0: token_ids = token_ids.unsqueeze(0) self.token_ids = token_ids self.random_offsets += 1 self.arrive_time = time.time() def set_step(self, step: int): """set step.""" assert step <= self.history_len history_token_ids = torch.tensor(self.history_token_ids, dtype=torch.long) new_history_ids = self.history_token_ids[:step] new_token_ids = torch.cat([history_token_ids[step:], self.token_ids]) self.history_token_ids = new_history_ids self.token_ids = new_token_ids The provided code snippet includes necessary dependencies for implementing the `_num_blocks_to_drop` function. Write a Python function `def _num_blocks_to_drop(seq: SchedulerSequence, window_size: int)` to solve the following problem: num blocks to free. Here is the function: def _num_blocks_to_drop(seq: SchedulerSequence, window_size: int): """num blocks to free.""" if seq.history_len <= window_size: return 0 block_size = seq.block_size history_len = seq.history_len num_blocks = len(seq.logical_blocks) win_start_block_id = (history_len - window_size) // block_size win_end_block_id = (history_len - 1) // block_size num_win_blocks = win_end_block_id - win_start_block_id + 1 return max(0, num_blocks - num_win_blocks)
num blocks to free.
8,146
from collections import OrderedDict from dataclasses import dataclass from typing import Dict, List, Set, Union from lmdeploy.utils import get_logger, logging_timer from ..adapter.adapter import ADAPTER_MANAGER, SchedulerAdapter from ..config import CacheConfig, SchedulerConfig from ..messages import MessageStatus, SchedulerSequence, SchedulerSession from .block_manager import DefaultBlockManager as BlockManager from .block_manager import build_block_manager SeqList = List[SchedulerSequence] def _find_seq_with_session_id(group: SeqList, session_id: int): return [seq for seq in group if seq.session_id == session_id]
null
8,147
import torch import triton import triton.language as tl from packaging import version from torch import Tensor from triton.runtime.jit import get_cuda_stream def _fwd_split_kernel( Q, K, V, sm_scale, KV_seqlens, Block_offsets, Acc_out, stride_qbs, stride_qh, stride_qd, stride_kbs, stride_kh, stride_kd, stride_vbs, stride_vh, stride_vd, stride_ok, stride_obs, stride_oh, stride_od, stride_boffb, kv_group_num, block_per_cta, window_size: tl.constexpr, num_sub_blocks: tl.constexpr, BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, ): """first step kernel of split k attention.""" cur_batch = tl.program_id(0) cur_head = tl.program_id(1) split_k_id = tl.program_id(2) cur_kv_head = cur_head // kv_group_num q_seqlen = 1 kv_seqlen = tl.load(KV_seqlens + cur_batch) history_len = kv_seqlen - q_seqlen # initialize offsets offs_n = tl.arange(0, BLOCK_N) offs_d = tl.arange(0, BLOCK_DMODEL) off_q = (cur_batch * stride_qbs + cur_head * stride_qh + offs_d * stride_qd) off_k = (cur_kv_head * stride_kh + offs_d[None, :] * stride_kd) off_v = (cur_kv_head * stride_vh + offs_d[None, :] * stride_vd) q = tl.load(Q + off_q).to(tl.float32) k_ptrs = K + off_k v_ptrs = V + off_v block_offset_ptrs = Block_offsets + cur_batch * stride_boffb # initialize pointer to m and l m_i = -float('inf') l_i = float(0) acc = tl.zeros([BLOCK_DMODEL], dtype=tl.float32) kv_len_per_prog = block_per_cta * BLOCK_N loop_start = kv_len_per_prog * split_k_id loop_end = tl.minimum(loop_start + kv_len_per_prog, kv_seqlen) # load block offset # dirty start_block_id = loop_start // BLOCK_N if window_size > 0: start_block_id = tl.maximum(history_len - window_size, loop_start) // BLOCK_N kv_min_loc = tl.maximum(history_len - window_size, 0) b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) loop_start = start_block_id * BLOCK_N for start_n in range(loop_start, loop_end, BLOCK_N): start_n = tl.multiple_of(start_n, BLOCK_N) mask = (start_n + offs_n[:, None]) < kv_seqlen # -- compute qk ---- k = tl.load( k_ptrs + b_offset[:, None] * stride_kbs, mask=mask, other=0.0, ) v = tl.load( v_ptrs + b_offset[:, None] * stride_vbs, mask=mask, other=0.0, ) # prefetch b_offset if start_n + BLOCK_N < loop_end: start_block_id += 1 b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) qk = tl.sum(q[None, :] * k, 1) qk *= sm_scale # NOTE: inf - inf = nan, and nan will leads to error qk_mask = history_len >= (start_n + offs_n) if window_size > 0: qk_mask = qk_mask and ((start_n + offs_n) >= kv_min_loc) qk = tl.where( qk_mask, qk, -float('inf'), ) # -- compute p, m_i and l_i m_i_new = tl.maximum(m_i, tl.max(qk, 0)) p = tl.exp(qk - m_i_new) alpha = tl.exp(m_i - m_i_new) l_i_new = alpha * l_i + tl.sum(p, 0) # -- update output accumulator -- # scale acc acc = acc * alpha # update acc p_new = p.to(v.dtype) acc += tl.sum(p_new[:, None] * v, 0) # update m_i and l_i l_i = l_i_new m_i = m_i_new # initialize pointers to output off_acc = (cur_batch * stride_obs + split_k_id * stride_ok + cur_head * stride_oh + offs_d * stride_od) tl.store(Acc_out + off_acc, acc) off_meta = (cur_batch * stride_obs + split_k_id * stride_ok + cur_head * stride_oh + BLOCK_DMODEL) tl.store(Acc_out + off_meta + tl.arange(0, 1), m_i) tl.store(Acc_out + off_meta + 1 + tl.arange(0, 1), l_i) def _reduce_split_kernel( Acc, Out, stride_ak, stride_abs, stride_ah, stride_ad, stride_obs, stride_oh, stride_od, SPLIT_K: tl.constexpr, BLOCK_DMODEL: tl.constexpr, ): """second step kernel of split k attention.""" cur_batch = tl.program_id(0) cur_head = tl.program_id(1) # initialize offsets offs_d = tl.arange(0, BLOCK_DMODEL) offs_k = tl.arange(0, SPLIT_K) offs_acc = (cur_batch * stride_abs + cur_head * stride_ah + offs_k[:, None] * stride_ak + offs_d[None, :] * stride_ad) offs_mi = (cur_batch * stride_abs + cur_head * stride_ah + stride_ak * offs_k + BLOCK_DMODEL) acc_k = tl.load(Acc + offs_acc) m_k = tl.load(Acc + offs_mi) l_k = tl.load(Acc + offs_mi + 1) m_max = tl.max(m_k, 0) alpha = tl.exp(m_k - m_max) acc_k = acc_k * alpha[:, None] l_k = l_k * alpha acc = tl.sum(acc_k, 0) l_sum = tl.sum(l_k, 0) acc = acc / l_sum out_offs = (cur_batch * stride_obs + cur_head * stride_oh + offs_d * stride_od) tl.store(Out + out_offs, acc) def _get_convert_pv(nv_capability): """lazy load convert_pv.""" if nv_capability[0] >= 8: def convert_pv(p, v): """convert pv.""" p = p.to(v.dtype) return p, v else: def convert_pv(p, v): """convert pv.""" v = v.to(p.dtype) return p, v return convert_pv _convert_pv = None def _fwd_kernel( Q, K, V, sm_scale, Q_start_loc, Q_seqlens, KV_seqlens, Block_offsets, Out, stride_qbs, stride_qh, stride_qd, stride_kbs, stride_kh, stride_kd, stride_vbs, stride_vh, stride_vd, stride_obs, stride_oh, stride_od, stride_boffb, kv_group_num, window_size: tl.constexpr, num_sub_blocks: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, ): """paged attention kernel.""" cur_batch = tl.program_id(0) cur_head = tl.program_id(1) start_m = tl.program_id(2) cur_kv_head = cur_head // kv_group_num q_seqlen = tl.load(Q_seqlens + cur_batch) kv_seqlen = tl.load(KV_seqlens + cur_batch) q_start_loc = tl.load(Q_start_loc + cur_batch) history_len = kv_seqlen - q_seqlen block_start_loc = BLOCK_M * start_m # initialize offsets offs_n = tl.arange(0, BLOCK_N) offs_d = tl.arange(0, BLOCK_DMODEL) offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) off_q = ((q_start_loc + offs_m[:, None]) * stride_qbs + cur_head * stride_qh + offs_d[None, :] * stride_qd) off_k = (cur_kv_head * stride_kh + offs_d[:, None] * stride_kd) off_v = (cur_kv_head * stride_vh + offs_d[None, :] * stride_vd) q = tl.load(Q + off_q, mask=offs_m[:, None] < q_seqlen, other=0.0) k_ptrs = K + off_k v_ptrs = V + off_v block_offset_ptrs = Block_offsets + cur_batch * stride_boffb # initialize pointer to m and l m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf') l_i = tl.zeros([BLOCK_M], dtype=tl.float32) acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) block_mask = tl.where(block_start_loc < q_seqlen, 1, 0) # this is dirty start_block_id = kv_seqlen - kv_seqlen if window_size > 0: start_block_id = tl.maximum(history_len - window_size, 0) // BLOCK_N kv_min_loc = tl.maximum(history_len + offs_m - window_size, 0) b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) kv_start_loc = start_block_id * BLOCK_N for start_n in range(kv_start_loc, block_mask * kv_seqlen, BLOCK_N): start_n = tl.multiple_of(start_n, BLOCK_N) # -- compute qk ---- k = tl.load( k_ptrs + b_offset[None, :] * stride_kbs, mask=start_n + offs_n[None, :] < kv_seqlen, other=0.0, ) v = tl.load( v_ptrs + b_offset[:, None] * stride_vbs, mask=start_n + offs_n[:, None] < kv_seqlen, other=0.0, ) if start_n + BLOCK_N < kv_seqlen: start_block_id = start_n // BLOCK_N + 1 b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) qk += tl.dot(q, k) qk *= sm_scale # NOTE: inf - inf = nan, and nan will leads to error qk_mask = (history_len + offs_m[:, None]) >= (start_n + offs_n[None, :]) if window_size > 0: qk_mask = qk_mask and ( (start_n + offs_n[None, :]) >= kv_min_loc[:, None]) qk = tl.where( qk_mask, qk, float(-1e30), ) # -- compute p, m_i and l_i m_i_new = tl.maximum(m_i, tl.max(qk, 1)) p = tl.exp(qk - m_i_new[:, None]) alpha = tl.exp(m_i - m_i_new) l_i_new = alpha * l_i + tl.sum(p, 1) # -- update output accumulator -- # scale acc acc = acc * alpha[:, None] # update acc p, v = _convert_pv(p, v) acc += tl.dot(p, v) # update m_i and l_i l_i = l_i_new m_i = m_i_new acc = acc / l_i[:, None] # initialize pointers to output off_o = ((q_start_loc + offs_m[:, None]) * stride_obs + cur_head * stride_oh + offs_d[None, :] * stride_od) out_ptrs = Out + off_o tl.store(out_ptrs, acc, mask=offs_m[:, None] < q_seqlen) The provided code snippet includes necessary dependencies for implementing the `paged_attention_fwd` function. Write a Python function `def paged_attention_fwd( q: Tensor, k: Tensor, v: Tensor, o: Tensor, block_offsets: Tensor, q_start_loc: Tensor, q_seqlens: Tensor, kv_seqlens: Tensor, max_seqlen: int, window_size: int = -1, )` to solve the following problem: Paged Attention forward. Args: q (Tensor): Query state. k (Tensor): Key state caches. v (Tensor): Value state caches. o (Tensor): Output state. block_offsets (Tensor): The block offset of key and value. q_start_loc (Tensor): Start token location of each data in batch. q_seqlens (Tensor): Query length for each data in batch. kv_seqlens (Tensor): Key/Value length for each data in batch. max_seqlen (int): The max input length. BLOCK (int): The kernel block size. Here is the function: def paged_attention_fwd( q: Tensor, k: Tensor, v: Tensor, o: Tensor, block_offsets: Tensor, q_start_loc: Tensor, q_seqlens: Tensor, kv_seqlens: Tensor, max_seqlen: int, window_size: int = -1, ): """Paged Attention forward. Args: q (Tensor): Query state. k (Tensor): Key state caches. v (Tensor): Value state caches. o (Tensor): Output state. block_offsets (Tensor): The block offset of key and value. q_start_loc (Tensor): Start token location of each data in batch. q_seqlens (Tensor): Query length for each data in batch. kv_seqlens (Tensor): Key/Value length for each data in batch. max_seqlen (int): The max input length. BLOCK (int): The kernel block size. """ global _convert_pv if _convert_pv is None: nv_cap = torch.cuda.get_device_capability() _convert_pv = _get_convert_pv(nv_cap) def _kernel_meta(): """kernel meta.""" device = q.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) # shape constraints Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1] assert Lq == Lk and Lk == Lv assert Lk in {16, 32, 64, 128, 256} sm_scale = 1.0 / (Lq**0.5) # 计算scale系数 batch, head = q_seqlens.shape[0], q.shape[-2] kv_group_num = q.shape[-2] // k.shape[-2] num_warps = 4 if Lk <= 64 else 8 BLOCK = 64 if k.size(1) < 16 else k.size(1) num_sub_blocks = BLOCK // k.size(1) kernel_meta = _kernel_meta() is_decoding = q.shape[-3] == q_seqlens.size(0) if not is_decoding: grid = (batch, head, triton.cdiv(max_seqlen, BLOCK)) _fwd_kernel[grid](q, k, v, sm_scale, q_start_loc, q_seqlens, kv_seqlens, block_offsets, o, stride_qbs=q.stride(-3), stride_qh=q.stride(-2), stride_qd=q.stride(-1), stride_kbs=k.stride(-3), stride_kh=k.stride(-2), stride_kd=k.stride(-1), stride_vbs=v.stride(-3), stride_vh=v.stride(-2), stride_vd=v.stride(-1), stride_obs=o.stride(-3), stride_oh=o.stride(-2), stride_od=o.stride(-1), stride_boffb=block_offsets.stride(0), kv_group_num=kv_group_num, window_size=window_size, num_sub_blocks=num_sub_blocks, BLOCK_M=BLOCK, BLOCK_DMODEL=Lk, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1, **kernel_meta) else: SPLIT_K = 4 grid = (batch, head, SPLIT_K) block_per_cta = triton.cdiv(block_offsets.size(-1), SPLIT_K) acc = q.new_empty(batch, head, SPLIT_K, Lq + 2, dtype=torch.float32) _fwd_split_kernel[grid](q, k, v, sm_scale, kv_seqlens, block_offsets, acc, stride_qbs=q.stride(-3), stride_qh=q.stride(-2), stride_qd=q.stride(-1), stride_kbs=k.stride(-3), stride_kh=k.stride(-2), stride_kd=k.stride(-1), stride_vbs=v.stride(-3), stride_vh=v.stride(-2), stride_vd=v.stride(-1), stride_ok=acc.stride(-2), stride_obs=acc.stride(-4), stride_oh=acc.stride(-3), stride_od=acc.stride(-1), stride_boffb=block_offsets.stride(0), kv_group_num=kv_group_num, block_per_cta=block_per_cta, window_size=window_size, num_sub_blocks=num_sub_blocks, BLOCK_DMODEL=Lk, BLOCK_N=BLOCK, num_warps=4, num_stages=1, **kernel_meta) grid = (batch, head) _reduce_split_kernel[grid](acc, o, stride_ak=acc.stride(-2), stride_abs=acc.stride(-4), stride_ah=acc.stride(-3), stride_ad=acc.stride(-1), stride_obs=o.stride(-3), stride_oh=o.stride(-2), stride_od=o.stride(-1), SPLIT_K=SPLIT_K, BLOCK_DMODEL=Lk, num_warps=num_warps, num_stages=1, **kernel_meta)
Paged Attention forward. Args: q (Tensor): Query state. k (Tensor): Key state caches. v (Tensor): Value state caches. o (Tensor): Output state. block_offsets (Tensor): The block offset of key and value. q_start_loc (Tensor): Start token location of each data in batch. q_seqlens (Tensor): Query length for each data in batch. kv_seqlens (Tensor): Key/Value length for each data in batch. max_seqlen (int): The max input length. BLOCK (int): The kernel block size.
8,148
import torch import triton import triton.language as tl from triton.runtime.jit import get_cuda_stream def _rearange_all_gather_kernel(X, StartLoc, SeqLen, AdapterIds, Ranks, Out, stride_x, stride_o, world_size, BLOCK: tl.constexpr, BLOCK_P: tl.constexpr): """rearange all gather kernel.""" batch_id = tl.program_id(0) block_id = tl.program_id(1) start_loc = tl.load(StartLoc + batch_id) + block_id * BLOCK seq_len = tl.load(SeqLen + batch_id) if block_id * BLOCK >= seq_len: return block_off = start_loc + tl.arange(0, BLOCK) block_mask = block_id * BLOCK + tl.arange(0, BLOCK) < seq_len adapter_id = tl.load(AdapterIds + batch_id) rank = tl.load(Ranks + adapter_id) prank = rank // world_size p_off = tl.arange(0, BLOCK_P) for p_id in range(world_size): ip_off = p_id * BLOCK_P + p_off i_mask = block_mask[:, None] and (p_off < prank)[None, :] i_off = block_off[:, None] * stride_x + ip_off[None, :] x = tl.load(X + i_off, mask=i_mask) op_off = p_id * prank + p_off o_mask = i_mask o_off = block_off[:, None] * stride_o + op_off[None, :] tl.store(Out + o_off, x, mask=o_mask) def _rearange_all_gather_decoding_kernel(X, AdapterIds, Ranks, Out, stride_x, stride_o, world_size, seq_len, BLOCK: tl.constexpr, BLOCK_P: tl.constexpr): """rearange all gather kernel.""" block_id = tl.program_id(0) block_off = block_id * BLOCK + tl.arange(0, BLOCK) block_mask = block_off < seq_len adapter_ids = tl.load(AdapterIds + block_off, mask=block_mask) ranks = tl.load(Ranks + adapter_ids) pranks = ranks // world_size p_off = tl.arange(0, BLOCK_P) for p_id in range(world_size): ip_off = p_id * BLOCK_P + p_off i_mask = block_mask[:, None] and (p_off[None, :] < pranks[:, None]) i_off = block_off[:, None] * stride_x + ip_off[None, :] x = tl.load(X + i_off, mask=i_mask) op_off = p_id * pranks[:, None] + p_off[None, :] o_mask = i_mask o_off = block_off[:, None] * stride_o + op_off tl.store(Out + o_off, x, mask=o_mask) The provided code snippet includes necessary dependencies for implementing the `rearange_all_gather` function. Write a Python function `def rearange_all_gather(x: torch.Tensor, b_start_loc: torch.Tensor, b_seq_lens: torch.Tensor, adapter_ids: torch.LongTensor, ranks: torch.Tensor, world_size: int, max_seq_len: int, output: torch.Tensor = None)` to solve the following problem: rearange all gather. Here is the function: def rearange_all_gather(x: torch.Tensor, b_start_loc: torch.Tensor, b_seq_lens: torch.Tensor, adapter_ids: torch.LongTensor, ranks: torch.Tensor, world_size: int, max_seq_len: int, output: torch.Tensor = None): """rearange all gather.""" def _kernel_meta(): device = x.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) max_rank = x.size(1) batch_size = len(b_seq_lens) partition_size = max_rank // world_size if output is None: output = torch.empty_like(x) num_warps = 4 kernel_meta = _kernel_meta() is_decoding = batch_size == x.size(0) if not is_decoding: BLOCK = 128 BLOCK_P = partition_size grid = (batch_size, triton.cdiv(max_seq_len, BLOCK)) _rearange_all_gather_kernel[grid](x, b_start_loc, b_seq_lens, adapter_ids, ranks, output, stride_x=x.stride(0), stride_o=output.stride(0), world_size=world_size, BLOCK=BLOCK, BLOCK_P=BLOCK_P, num_warps=num_warps, num_stages=1, **kernel_meta) else: BLOCK = 64 BLOCK_P = partition_size seq_len = x.size(0) grid = (triton.cdiv(seq_len, BLOCK), ) _rearange_all_gather_decoding_kernel[grid](x, adapter_ids, ranks, output, stride_x=x.stride(0), stride_o=output.stride(0), world_size=world_size, seq_len=seq_len, BLOCK=BLOCK, BLOCK_P=BLOCK_P, num_warps=num_warps, num_stages=1, **kernel_meta) return output
rearange all gather.
8,149
import math import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream assert triton.__version__ >= '2.1.0' def _fwd_split_kernel( Q, K, V, sm_scale, alibi_scale, B_kvlen, Block_offsets, Acc_out, stride_qbs, stride_qh, stride_qd, stride_kbs, stride_kh, stride_kd, stride_vbs, stride_vh, stride_vd, stride_ok, stride_obs, stride_oh, stride_od, stride_boffb, head_offset, num_heads, kv_group_num, block_per_cta, num_sub_blocks: tl.constexpr, BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, ): """first step kernel of split k attention.""" cur_batch = tl.program_id(0) cur_head = tl.program_id(1) split_k_id = tl.program_id(2) cur_kv_head = cur_head // kv_group_num cur_batch_seq_len = 1 cur_batch_kv_len = tl.load(B_kvlen + cur_batch) history_len = cur_batch_kv_len - cur_batch_seq_len # initialize offsets offs_n = tl.arange(0, BLOCK_N) offs_d = tl.arange(0, BLOCK_DMODEL) off_q = (cur_batch * stride_qbs + cur_head * stride_qh + offs_d * stride_qd) off_k = (cur_kv_head * stride_kh + offs_d[None, :] * stride_kd) off_v = (cur_kv_head * stride_vh + offs_d[None, :] * stride_vd) q = tl.load(Q + off_q).to(tl.float32) k_ptrs = K + off_k v_ptrs = V + off_v block_offset_ptrs = Block_offsets + cur_batch * stride_boffb head_slope = get_slope( cur_head.to(tl.float32) + head_offset, num_heads.to(tl.float32)) # initialize pointer to m and l m_i = -float('inf') l_i = float(0) acc = tl.zeros([BLOCK_DMODEL], dtype=tl.float32) kv_len_per_prog = block_per_cta * BLOCK_N loop_start = kv_len_per_prog * split_k_id loop_end = tl.minimum(loop_start + kv_len_per_prog, cur_batch_kv_len) # load block offset start_block_id = loop_start // BLOCK_N b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) for start_n in range(loop_start, loop_end, BLOCK_N): start_n = tl.multiple_of(start_n, BLOCK_N) mask = (start_n + offs_n[:, None]) < cur_batch_kv_len # -- compute qk ---- k = tl.load( k_ptrs + b_offset[:, None] * stride_kbs, mask=mask, other=0.0, ) v = tl.load( v_ptrs + b_offset[:, None] * stride_vbs, mask=mask, other=0.0, ) # prefetch b_offset if start_n + BLOCK_N < loop_end: start_block_id += 1 b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) qk = tl.sum(q[None, :] * k, 1) qk *= sm_scale mask = start_n + offs_n bias = mask.to(tl.float32) * (head_slope * alibi_scale) qk += bias # NOTE: inf - inf = nan, and nan will leads to error qk = tl.where( history_len >= (start_n + offs_n), qk, -float('inf'), ) # -- compute p, m_i and l_i m_i_new = tl.maximum(m_i, tl.max(qk, 0)) p = tl.exp(qk - m_i_new) alpha = tl.exp(m_i - m_i_new) l_i_new = alpha * l_i + tl.sum(p, 0) # -- update output accumulator -- # scale acc acc = acc * alpha # update acc p_new = p.to(v.dtype) acc += tl.sum(p_new[:, None] * v, 0) # update m_i and l_i l_i = l_i_new m_i = m_i_new # initialize pointers to output off_acc = (cur_batch * stride_obs + split_k_id * stride_ok + cur_head * stride_oh + offs_d * stride_od) tl.store(Acc_out + off_acc, acc) off_meta = (cur_batch * stride_obs + split_k_id * stride_ok + cur_head * stride_oh + BLOCK_DMODEL) tl.store(Acc_out + off_meta + tl.arange(0, 1), m_i) tl.store(Acc_out + off_meta + 1 + tl.arange(0, 1), l_i) def _reduce_split_kernel( Acc, Out, stride_ak, stride_abs, stride_ah, stride_ad, stride_obs, stride_oh, stride_od, SPLIT_K: tl.constexpr, BLOCK_DMODEL: tl.constexpr, ): """second step kernel of split k attention.""" cur_batch = tl.program_id(0) cur_head = tl.program_id(1) # initialize offsets offs_d = tl.arange(0, BLOCK_DMODEL) offs_k = tl.arange(0, SPLIT_K) offs_acc = (cur_batch * stride_abs + cur_head * stride_ah + offs_k[:, None] * stride_ak + offs_d[None, :] * stride_ad) offs_mi = (cur_batch * stride_abs + cur_head * stride_ah + stride_ak * offs_k + BLOCK_DMODEL) acc_k = tl.load(Acc + offs_acc) m_k = tl.load(Acc + offs_mi) l_k = tl.load(Acc + offs_mi + 1) m_max = tl.max(m_k, 0) alpha = tl.exp(m_k - m_max) acc_k = acc_k * alpha[:, None] l_k = l_k * alpha acc = tl.sum(acc_k, 0) l_sum = tl.sum(l_k, 0) acc = acc / l_sum out_offs = (cur_batch * stride_obs + cur_head * stride_oh + offs_d * stride_od) tl.store(Out + out_offs, acc) def _fwd_kernel( Q, K, V, sm_scale, alibi_scale, B_Start_Loc, B_Seqlen, B_kvlen, Block_offsets, Out, stride_qbs, stride_qh, stride_qd, stride_kbs, stride_kh, stride_kd, stride_vbs, stride_vh, stride_vd, stride_obs, stride_oh, stride_od, stride_boffb, head_offset, num_heads, kv_group_num, num_sub_blocks: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, ): """forward kernel.""" cur_batch = tl.program_id(0) cur_head = tl.program_id(1) start_m = tl.program_id(2) cur_kv_head = cur_head // kv_group_num cur_batch_seq_len = tl.load(B_Seqlen + cur_batch) cur_batch_kv_len = tl.load(B_kvlen + cur_batch) cur_batch_in_all_start_index = tl.load(B_Start_Loc + cur_batch) history_len = cur_batch_kv_len - cur_batch_seq_len block_start_loc = BLOCK_M * start_m head_slope = get_slope( cur_head.to(tl.float32) + head_offset, num_heads.to(tl.float32)) # initialize offsets offs_n = tl.arange(0, BLOCK_N) offs_d = tl.arange(0, BLOCK_DMODEL) offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) off_q = ((cur_batch_in_all_start_index + offs_m[:, None]) * stride_qbs + cur_head * stride_qh + offs_d[None, :] * stride_qd) off_k = (cur_kv_head * stride_kh + offs_d[:, None] * stride_kd) off_v = (cur_kv_head * stride_vh + offs_d[None, :] * stride_vd) q = tl.load(Q + off_q, mask=offs_m[:, None] < cur_batch_seq_len, other=0.0) k_ptrs = K + off_k v_ptrs = V + off_v block_offset_ptrs = Block_offsets + cur_batch * stride_boffb # initialize pointer to m and l m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf') l_i = tl.zeros([BLOCK_M], dtype=tl.float32) acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) block_mask = tl.where(block_start_loc < cur_batch_seq_len, 1, 0) b_offset = _load_block_offsets(block_offset_ptrs, 0, num_sub_blocks, BLOCK_N) for start_n in range(0, block_mask * cur_batch_kv_len, BLOCK_N): start_n = tl.multiple_of(start_n, BLOCK_N) # -- compute qk ---- k = tl.load( k_ptrs + b_offset[None, :] * stride_kbs, mask=(start_n + offs_n[None, :]) < cur_batch_kv_len, other=0.0, ) v = tl.load( v_ptrs + b_offset[:, None] * stride_vbs, mask=(start_n + offs_n[:, None]) < cur_batch_kv_len, other=0.0, ) if start_n + BLOCK_N < cur_batch_kv_len: start_block_id = start_n // BLOCK_N + 1 b_offset = _load_block_offsets(block_offset_ptrs, start_block_id, num_sub_blocks, BLOCK_N) qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) qk += tl.dot(q, k) qk *= sm_scale mask = start_n + offs_n[None, :] bias = mask.to(tl.float32) * (head_slope * alibi_scale) qk += bias # NOTE: inf - inf = nan, and nan will leads to error qk = tl.where( (history_len + offs_m[:, None]) >= mask, qk, float(-1e30), ) # -- compute p, m_i and l_i m_i_new = tl.maximum(m_i, tl.max(qk, 1)) p = tl.exp(qk - m_i_new[:, None]) alpha = tl.exp(m_i - m_i_new) l_i_new = alpha * l_i + tl.sum(p, 1) # -- update output accumulator -- # scale acc acc = acc * alpha[:, None] # update acc p = p.to(v.dtype) acc += tl.dot(p, v) # update m_i and l_i l_i = l_i_new m_i = m_i_new acc = acc / l_i[:, None] # initialize pointers to output off_o = ((cur_batch_in_all_start_index + offs_m[:, None]) * stride_obs + cur_head * stride_oh + offs_d[None, :] * stride_od) out_ptrs = Out + off_o tl.store(out_ptrs, acc, mask=offs_m[:, None] < cur_batch_seq_len) The provided code snippet includes necessary dependencies for implementing the `alibi_paged_attention_fwd` function. Write a Python function `def alibi_paged_attention_fwd(q: Tensor, k: Tensor, v: Tensor, o: Tensor, block_offsets: Tensor, b_start_loc: Tensor, b_seq_len: Tensor, b_kv_seq_len: Tensor, max_input_len: int, head_offset: int = 0, num_heads: int = -1, alibi_scale: float = 1.0)` to solve the following problem: Paged attention forward with alibi bias. Args: q (Tensor): Query state. k (Tensor): Key state caches. v (Tensor): Value state caches. o (Tensor): Output state. block_offsets (Tensor): The block offset of key and value. b_start_loc (Tensor): Start token location of each data in batch. b_seq_len (Tensor): Query length for each data in batch. b_kv_seq_len (Tensor): Key/Value length for each data in batch. max_input_len (int): The max input length. head_offset (int): The offset of the start head. Head might be partitioned when tensor parallel inference. num_heads (int): The number of heads. Head might be partitioned when tensor parallel inference. BLOCK (int): The kernel block size. Here is the function: def alibi_paged_attention_fwd(q: Tensor, k: Tensor, v: Tensor, o: Tensor, block_offsets: Tensor, b_start_loc: Tensor, b_seq_len: Tensor, b_kv_seq_len: Tensor, max_input_len: int, head_offset: int = 0, num_heads: int = -1, alibi_scale: float = 1.0): """Paged attention forward with alibi bias. Args: q (Tensor): Query state. k (Tensor): Key state caches. v (Tensor): Value state caches. o (Tensor): Output state. block_offsets (Tensor): The block offset of key and value. b_start_loc (Tensor): Start token location of each data in batch. b_seq_len (Tensor): Query length for each data in batch. b_kv_seq_len (Tensor): Key/Value length for each data in batch. max_input_len (int): The max input length. head_offset (int): The offset of the start head. Head might be partitioned when tensor parallel inference. num_heads (int): The number of heads. Head might be partitioned when tensor parallel inference. BLOCK (int): The kernel block size. """ def _kernel_meta(): device = q.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) # shape constraints Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1] assert Lq == Lk and Lk == Lv assert Lk in {16, 32, 64, 128} sm_scale = 1.0 / (Lq**0.5) # 计算scale系数 batch, head = b_seq_len.shape[0], q.shape[-2] kv_group_num = q.shape[-2] // k[0].shape[-2] if num_heads <= 0: num_heads = head BLOCK = 64 if k.size(1) < 16 else k.size(1) num_sub_blocks = BLOCK // k.size(1) grid = (batch, head, triton.cdiv(max_input_len, BLOCK)) # batch, head, num_warps = 4 if Lk <= 64 else 8 kernel_meta = _kernel_meta() is_decoding = q.shape[-3] == b_seq_len.size(0) if not is_decoding: _fwd_kernel[grid](q, k, v, sm_scale, alibi_scale, b_start_loc, b_seq_len, b_kv_seq_len, block_offsets, o, q.stride(-3), q.stride(-2), q.stride(-1), k.stride(-3), k.stride(-2), k.stride(-1), v.stride(-3), v.stride(-2), v.stride(-1), o.stride(-3), o.stride(-2), o.stride(-1), block_offsets.stride(0), head_offset=head_offset, num_heads=num_heads, kv_group_num=kv_group_num, num_sub_blocks=num_sub_blocks, BLOCK_M=BLOCK, BLOCK_DMODEL=Lk, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1, **kernel_meta) else: SPLIT_K = 4 grid = (batch, head, SPLIT_K) block_per_cta = triton.cdiv(block_offsets.size(-1), SPLIT_K) acc = q.new_empty(batch, head, SPLIT_K, Lq + 2, dtype=torch.float32) _fwd_split_kernel[grid](q, k, v, sm_scale, alibi_scale, b_kv_seq_len, block_offsets, acc, stride_qbs=q.stride(-3), stride_qh=q.stride(-2), stride_qd=q.stride(-1), stride_kbs=k.stride(-3), stride_kh=k.stride(-2), stride_kd=k.stride(-1), stride_vbs=v.stride(-3), stride_vh=v.stride(-2), stride_vd=v.stride(-1), stride_ok=acc.stride(-2), stride_obs=acc.stride(-4), stride_oh=acc.stride(-3), stride_od=acc.stride(-1), stride_boffb=block_offsets.stride(0), head_offset=head_offset, num_heads=num_heads, kv_group_num=kv_group_num, block_per_cta=block_per_cta, num_sub_blocks=num_sub_blocks, BLOCK_DMODEL=Lk, BLOCK_N=BLOCK, num_warps=4, num_stages=1, **kernel_meta) grid = (batch, head) _reduce_split_kernel[grid](acc, o, stride_ak=acc.stride(-2), stride_abs=acc.stride(-4), stride_ah=acc.stride(-3), stride_ad=acc.stride(-1), stride_obs=o.stride(-3), stride_oh=o.stride(-2), stride_od=o.stride(-1), SPLIT_K=SPLIT_K, BLOCK_DMODEL=Lk, num_warps=num_warps, num_stages=1, **kernel_meta)
Paged attention forward with alibi bias. Args: q (Tensor): Query state. k (Tensor): Key state caches. v (Tensor): Value state caches. o (Tensor): Output state. block_offsets (Tensor): The block offset of key and value. b_start_loc (Tensor): Start token location of each data in batch. b_seq_len (Tensor): Query length for each data in batch. b_kv_seq_len (Tensor): Key/Value length for each data in batch. max_input_len (int): The max input length. head_offset (int): The offset of the start head. Head might be partitioned when tensor parallel inference. num_heads (int): The number of heads. Head might be partitioned when tensor parallel inference. BLOCK (int): The kernel block size.
8,150
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def _next_pow_of_2(x): """get next power of 2.""" return 1 << (x - 1).bit_length() def _x_a_mm_kernel( X, LoRA_A, XA, B_start_loc, B_seq_lens, B_adapter_id, Rank_page_table, Rank_page_start, Ranks, stride_xs, stride_xh, stride_las, stride_lah, stride_xas, stride_xar, stride_ptb, rank_step, BLOCK_M: tl.constexpr, BLOCK_R: tl.constexpr, BLOCK_H: tl.constexpr, BLOCK_DMODEL: tl.constexpr, ): """xa mm kernel.""" cur_batch = tl.program_id(0) start_m = tl.program_id(1) r_off = tl.arange(0, BLOCK_R) seq_len = tl.load(B_seq_lens + cur_batch) if start_m * BLOCK_M >= seq_len: return start_loc = tl.load(B_start_loc + cur_batch) adapter_id = tl.load(B_adapter_id + cur_batch) rank = tl.load(Ranks + adapter_id) // rank_step page_start = tl.load(Rank_page_start + adapter_id) page_table_off = adapter_id * stride_ptb + r_off + page_start rank_mask = r_off < rank page_table = tl.load(Rank_page_table + page_table_off, mask=rank_mask) m_off = start_m * BLOCK_M + tl.arange(0, BLOCK_M) dm_off = tl.arange(0, BLOCK_DMODEL) x_off = (start_loc + m_off) * stride_xs xs_mask = m_off < seq_len la_page_off = page_table * stride_las acc = tl.zeros((BLOCK_M, BLOCK_R), dtype=tl.float32) # compute acc for start_h in range(0, BLOCK_H, BLOCK_DMODEL): cur_dm_off = start_h + dm_off h_mask = cur_dm_off < BLOCK_H # load x xh_off = cur_dm_off * stride_xh x_mask = xs_mask[:, None] and h_mask[None, :] x = tl.load(X + x_off[:, None] + xh_off[None, :], mask=x_mask, other=0.0) # load lora a lah_off = cur_dm_off * stride_lah la_mask = rank_mask[None, :] and h_mask[:, None] la = tl.load(LoRA_A + la_page_off[None, :] + lah_off[:, None], mask=la_mask, other=0.0) # compute acc += tl.dot(x, la) acc = acc.to(X.dtype.element_ty) xa_off = (start_loc + m_off) * stride_xas xas_mask = xs_mask xa_mask = xas_mask[:, None] and rank_mask[None, :] tl.store(XA + xa_off[:, None] + r_off[None, :] * stride_xar, acc, mask=xa_mask) The provided code snippet includes necessary dependencies for implementing the `mbgmm_a` function. Write a Python function `def mbgmm_a(x: Tensor, lora_a: Tensor, q_start_loc: Tensor, q_seqlens: Tensor, adapter_ids: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_seq_len: int, max_rank: int, rank_step: int = 1)` to solve the following problem: mbgmm_a. Here is the function: def mbgmm_a(x: Tensor, lora_a: Tensor, q_start_loc: Tensor, q_seqlens: Tensor, adapter_ids: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_seq_len: int, max_rank: int, rank_step: int = 1): """mbgmm_a.""" def _kernel_meta(): device = x.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) assert x.dim() == 2 assert lora_a.dim() == 2 assert rank_page_table.dim() == 2 head_size = x.size(-1) batch_size = len(q_seqlens) max_rank = max_rank // rank_step BLOCK_M = 32 BLOCK_R = _next_pow_of_2(max_rank) if BLOCK_R < 16: BLOCK_R = 16 BLOCK_H = head_size BLOCK_DMODEL = 64 num_warps = 4 grid = [batch_size, triton.cdiv(max_seq_len, BLOCK_M)] xa = x.new_empty((x.size(0), max_rank)) kernel_meta = _kernel_meta() _x_a_mm_kernel[grid](x, lora_a, xa, q_start_loc, q_seqlens, adapter_ids, Rank_page_table=rank_page_table, Rank_page_start=rank_page_start, Ranks=ranks, stride_xs=x.stride(0), stride_xh=x.stride(1), stride_las=lora_a.stride(0), stride_lah=lora_a.stride(1), stride_xas=xa.stride(0), stride_xar=xa.stride(1), stride_ptb=rank_page_table.stride(0), rank_step=rank_step, BLOCK_M=BLOCK_M, BLOCK_R=BLOCK_R, BLOCK_H=BLOCK_H, BLOCK_DMODEL=BLOCK_DMODEL, num_warps=num_warps, num_stages=1, **kernel_meta) return xa
mbgmm_a.
8,151
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def _next_pow_of_2(x): """get next power of 2.""" return 1 << (x - 1).bit_length() def _acc_b_mm_kernel( XA, LoRA_B, Out, B_start_loc, B_seq_lens, B_adapter_id, B_scaling, Rank_page_table, Rank_page_start, Ranks, stride_xas, stride_xar, stride_os, stride_oh, stride_lbs, stride_lbh, stride_ptb, BLOCK_M: tl.constexpr, BLOCK_R: tl.constexpr, BLOCK_HO: tl.constexpr, BLOCK_DMODEL: tl.constexpr, ): cur_batch = tl.program_id(0) start_m = tl.program_id(1) r_off = tl.arange(0, BLOCK_R) seq_len = tl.load(B_seq_lens + cur_batch) if start_m * BLOCK_M >= seq_len: return start_loc = tl.load(B_start_loc + cur_batch) adapter_id = tl.load(B_adapter_id + cur_batch) scaling = tl.load(B_scaling + cur_batch) rank = tl.load(Ranks + adapter_id) page_start = tl.load(Rank_page_start + adapter_id) page_table_off = adapter_id * stride_ptb + r_off + page_start rank_mask = r_off < rank page_table = tl.load(Rank_page_table + page_table_off, mask=rank_mask) m_off = start_m * BLOCK_M + tl.arange(0, BLOCK_M) dm_off = tl.arange(0, BLOCK_DMODEL) lb_page_off = page_table * stride_lbs xs_mask = m_off < seq_len o_off = (start_loc + m_off) * stride_os os_mask = xs_mask xa_off = (start_loc + m_off) * stride_xas xa_mask = xs_mask[:, None] and rank_mask[None, :] acc = tl.load(XA + xa_off[:, None] + r_off[None, :] * stride_xar, mask=xa_mask, other=0.0) acc = acc.to(LoRA_B.dtype.element_ty) # compute output for start_h in range(0, BLOCK_HO, BLOCK_DMODEL): cur_dm_off = start_h + dm_off h_mask = cur_dm_off < BLOCK_HO # load lora b lbh_off = cur_dm_off * stride_lbh lb_mask = rank_mask[:, None] and h_mask[None, :] lb = tl.load(LoRA_B + lb_page_off[:, None] + lbh_off[None, :], mask=lb_mask, other=0) # compute out = tl.dot(acc, lb) out = out.to(lb.dtype) out = out * scaling # store o oh_off = cur_dm_off * stride_oh o_mask = os_mask[:, None] and h_mask[None, :] tl.store(Out + o_off[:, None] + oh_off[None, :], out, mask=o_mask) The provided code snippet includes necessary dependencies for implementing the `mbgmm_b` function. Write a Python function `def mbgmm_b(xa: Tensor, lora_b: Tensor, q_start_loc: Tensor, q_seqlens: Tensor, adapter_ids: Tensor, scaling: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_seq_len: int, max_rank: int, out_size: int = None)` to solve the following problem: mbgmm_b. Here is the function: def mbgmm_b(xa: Tensor, lora_b: Tensor, q_start_loc: Tensor, q_seqlens: Tensor, adapter_ids: Tensor, scaling: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_seq_len: int, max_rank: int, out_size: int = None): """mbgmm_b.""" def _kernel_meta(): device = xa.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) assert xa.dim() == 2 assert lora_b.dim() == 2 assert rank_page_table.dim() == 2 if out_size is None: out_size = lora_b.size(-1) batch_size = len(q_seqlens) BLOCK_M = 32 BLOCK_R = _next_pow_of_2(max_rank) if BLOCK_R < 16: BLOCK_R = 16 BLOCK_HO = out_size BLOCK_DMODEL = 64 num_warps = 4 grid = [batch_size, triton.cdiv(max_seq_len, BLOCK_M)] output = xa.new_empty((xa.size(0), BLOCK_HO)) kernel_meta = _kernel_meta() _acc_b_mm_kernel[grid](xa, lora_b, output, q_start_loc, q_seqlens, adapter_ids, scaling, Rank_page_table=rank_page_table, Rank_page_start=rank_page_start, Ranks=ranks, stride_xas=xa.stride(0), stride_xar=xa.stride(1), stride_os=output.stride(0), stride_oh=output.stride(1), stride_lbs=lora_b.stride(0), stride_lbh=lora_b.stride(1), stride_ptb=rank_page_table.stride(0), BLOCK_M=BLOCK_M, BLOCK_R=BLOCK_R, BLOCK_HO=BLOCK_HO, BLOCK_DMODEL=BLOCK_DMODEL, num_warps=num_warps, num_stages=1, **kernel_meta) return output
mbgmm_b.
8,152
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def _next_pow_of_2(x): """get next power of 2.""" return 1 << (x - 1).bit_length() def _x_a_mv_kernel( X, LoRA_A, XA, B_adapter_id, Rank_page_table, Rank_page_start, Ranks, stride_xs, stride_xh, stride_las, stride_lah, stride_xas, stride_xar, stride_ptb, rank_step, BLOCK_R: tl.constexpr, BLOCK_H: tl.constexpr, BLOCK_DMODEL: tl.constexpr, ): """xa mv kernel.""" cur_batch = tl.program_id(0) r_off = tl.arange(0, BLOCK_R) adapter_id = tl.load(B_adapter_id + cur_batch) rank = tl.load(Ranks + adapter_id) // rank_step page_start = tl.load(Rank_page_start + adapter_id) page_table_off = adapter_id * stride_ptb + r_off + page_start rank_mask = r_off < rank page_table = tl.load(Rank_page_table + page_table_off, mask=rank_mask) dm_off = tl.arange(0, BLOCK_DMODEL) x_off = cur_batch * stride_xs la_page_off = page_table * stride_las acc = tl.zeros((BLOCK_R, ), dtype=tl.float32) # compute acc for start_h in range(0, BLOCK_H, BLOCK_DMODEL): cur_dm_off = start_h + dm_off h_mask = cur_dm_off < BLOCK_H # load x xh_off = cur_dm_off * stride_xh x_mask = h_mask x = tl.load(X + x_off + xh_off, mask=x_mask, other=0.0) # load lora a lah_off = cur_dm_off * stride_lah la_mask = rank_mask[:, None] and h_mask[None, :] la = tl.load(LoRA_A + la_page_off[:, None] + lah_off[None, :], mask=la_mask, other=0.0) # compute acc += tl.sum(x[None, :] * la, 1) acc = acc.to(X.dtype.element_ty) xa_off = cur_batch * stride_xas tl.store(XA + xa_off + r_off * stride_xar, acc, mask=rank_mask) The provided code snippet includes necessary dependencies for implementing the `mbgmv_a` function. Write a Python function `def mbgmv_a(x: Tensor, lora_a: Tensor, adapter_ids: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_rank: int, rank_step: int = 1)` to solve the following problem: mbgmv_a. Here is the function: def mbgmv_a(x: Tensor, lora_a: Tensor, adapter_ids: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_rank: int, rank_step: int = 1): """mbgmv_a.""" def _kernel_meta(): device = x.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) assert x.dim() == 2 assert lora_a.dim() == 2 assert rank_page_table.dim() == 2 head_size = x.size(-1) batch_size = x.size(0) max_rank = max_rank // rank_step BLOCK_R = _next_pow_of_2(max_rank) BLOCK_H = head_size BLOCK_DMODEL = 512 num_warps = 4 grid = [batch_size] xa = x.new_empty((x.size(0), BLOCK_R)) kernel_meta = _kernel_meta() _x_a_mv_kernel[grid](x, lora_a, xa, adapter_ids, Rank_page_table=rank_page_table, Rank_page_start=rank_page_start, Ranks=ranks, stride_xs=x.stride(0), stride_xh=x.stride(1), stride_las=lora_a.stride(0), stride_lah=lora_a.stride(1), stride_xas=xa.stride(0), stride_xar=xa.stride(1), stride_ptb=rank_page_table.stride(0), rank_step=rank_step, BLOCK_R=BLOCK_R, BLOCK_H=BLOCK_H, BLOCK_DMODEL=BLOCK_DMODEL, num_warps=num_warps, num_stages=1, **kernel_meta) return xa
mbgmv_a.
8,153
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def _next_pow_of_2(x): """get next power of 2.""" return 1 << (x - 1).bit_length() def _acc_b_mv_kernel( XA, LoRA_B, Out, B_adapter_id, B_scaling, Rank_page_table, Rank_page_start, Ranks, stride_xas, stride_xar, stride_os, stride_oh, stride_lbs, stride_lbh, stride_ptb, BLOCK_R: tl.constexpr, BLOCK_HO: tl.constexpr, BLOCK_DMODEL: tl.constexpr, ): """acc b mv kernel.""" cur_batch = tl.program_id(0) r_off = tl.arange(0, BLOCK_R) adapter_id = tl.load(B_adapter_id + cur_batch) scaling = tl.load(B_scaling + cur_batch) rank = tl.load(Ranks + adapter_id) page_start = tl.load(Rank_page_start + adapter_id) page_table_off = adapter_id * stride_ptb + r_off + page_start rank_mask = r_off < rank page_table = tl.load(Rank_page_table + page_table_off, mask=rank_mask) dm_off = tl.arange(0, BLOCK_DMODEL) lb_page_off = page_table * stride_lbs o_off = cur_batch * stride_os xa_off = cur_batch * stride_xas acc = tl.load(XA + xa_off + r_off * stride_xar, mask=rank_mask, other=0.0) # compute output for start_h in range(0, BLOCK_HO, BLOCK_DMODEL): cur_dm_off = start_h + dm_off h_mask = cur_dm_off < BLOCK_HO # load lora b lbh_off = cur_dm_off * stride_lbh lb_mask = rank_mask[:, None] and h_mask[None, :] lb = tl.load(LoRA_B + lb_page_off[:, None] + lbh_off[None, :], mask=lb_mask, other=0) # compute out = tl.sum(acc[:, None] * lb, 0) out = out.to(lb.dtype) out = out * scaling # store o oh_off = cur_dm_off * stride_oh tl.store(Out + o_off + oh_off, out, mask=h_mask) The provided code snippet includes necessary dependencies for implementing the `mbgmv_b` function. Write a Python function `def mbgmv_b(xa: Tensor, lora_b: Tensor, adapter_ids: Tensor, scaling: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_rank: int, out_size: int = None)` to solve the following problem: mbgmv_b. Here is the function: def mbgmv_b(xa: Tensor, lora_b: Tensor, adapter_ids: Tensor, scaling: Tensor, rank_page_table: Tensor, ranks: Tensor, rank_page_start: Tensor, max_rank: int, out_size: int = None): """mbgmv_b.""" def _kernel_meta(): device = xa.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) assert xa.dim() == 2 assert lora_b.dim() == 2 assert rank_page_table.dim() == 2 if out_size is None: out_size = lora_b.size(-1) batch_size = xa.size(0) BLOCK_R = _next_pow_of_2(max_rank) BLOCK_HO = out_size BLOCK_DMODEL = 512 num_warps = 4 grid = [batch_size] output = xa.new_empty((xa.size(0), BLOCK_HO)) kernel_meta = _kernel_meta() _acc_b_mv_kernel[grid](xa, lora_b, output, adapter_ids, scaling, Rank_page_table=rank_page_table, Rank_page_start=rank_page_start, Ranks=ranks, stride_xas=xa.stride(0), stride_xar=xa.stride(1), stride_lbs=lora_b.stride(0), stride_lbh=lora_b.stride(1), stride_os=output.stride(0), stride_oh=output.stride(1), stride_ptb=rank_page_table.stride(0), BLOCK_R=BLOCK_R, BLOCK_HO=BLOCK_HO, BLOCK_DMODEL=BLOCK_DMODEL, num_warps=num_warps, num_stages=1, **kernel_meta) return output
mbgmv_b.
8,154
import torch import torch.nn.functional as F import triton import triton.language as tl def per_channel_quant(x, n_bits, dtype): """Quantize the input tensor 'x' channel-wise using the given number of bits. Args: x (torch.Tensor): The input tensor to be quantized. Must be a 2-dimensional tensor. n_bits (int): The number of bits to use for quantization. dtype (torch.dtype): The data type to which the quantized tensor should be converted. Returns: tuple: A tuple containing two items -- the quantized tensor and the scale used for quantization. """ assert x.ndim == 2 x = x.to(torch.float32) x_absmax = x.view(x.shape[0], -1).abs().max(dim=1, keepdim=True)[0] q_max = 2**(n_bits - 1) - 1 q_min = -2**(n_bits - 1) scale = x_absmax / (2**(n_bits - 1) - 1) x_q = torch.round(x / scale).clamp(q_min, q_max).to(dtype) return x_q, scale configs=[ triton.Config({ 'BLOCK_M': 16, 'BLOCK_N': 128, 'BLOCK_K': 256, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 32, 'BLOCK_N': 64, 'BLOCK_K': 128, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 64, 'BLOCK_N': 64, 'BLOCK_K': 128, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 128, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 128, }, num_stages=4, num_warps=4) ], key=['M', 'N', 'K'], def matmul_kernel_dynamic_quant(a, b, rms_scale, linear_scale, residual=None, bias=None, output_dtype=torch.float16): """This function performs matrix multiplication with dynamic quantization. It takes two input tensors `a` and `b`, scales them with `rms_scale` and `linear_scale`, and optionally adds a `residual` tensor and a `bias`. The output is returned in the specified `output_dtype`. """ assert a.shape[-1] == b.shape[-1] assert b.ndim == 2 and b.is_contiguous() b = b.t() # (K, N) M = a.numel() // a.shape[-1] K, N = b.shape c_shape = a.shape[:-1] + (N, ) if residual is not None: assert residual.shape == c_shape assert residual.is_contiguous() c = torch.empty(c_shape, device=a.device, dtype=output_dtype) def grid(META): return (triton.cdiv(M, META['BLOCK_M']) * triton.cdiv(N, META['BLOCK_N']), ) if residual is not None: _linear_add[grid](a, b, c, residual, M, N, K, a.stride(-2), a.stride(-1), b.stride(0), b.stride(1), c.stride(-2), c.stride(-1), GROUP_SIZE_M=8, rms_scale_ptr=rms_scale, linear_scale_ptr=linear_scale) else: _linear[grid](a, b, c, M, N, K, a.stride(-2), a.stride(-1), b.stride(0), b.stride(1), c.stride(-2), c.stride(-1), GROUP_SIZE_M=8, rms_scale_ptr=rms_scale, linear_scale_ptr=linear_scale) if bias is not None: c += bias return c def rms_norm_dynamic_quant(x, w, eps): """Performs RMS normalization with dynamic quantization. The function reshapes the input tensor `x`, creates an empty tensor `y` with the same shape as `x`, and calculates RMS normalization on the reshaped `x` using a Triton kernel `_rms_norm_fwd_fused_dynamic_symmetric`. """ x_arg = x.reshape(-1, x.shape[-1]) y = torch.empty_like(x, dtype=torch.int8) M, K = x_arg.shape MAX_FUSED_SIZE = 65536 // x.element_size() BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(K)) if K > BLOCK_SIZE: raise RuntimeError( "This rms norm doesn't support feature dim >= 64KB.") num_warps = min(max(BLOCK_SIZE // 256, 1), 8) scale = torch.empty(x.shape[:-1] + (1, ), dtype=torch.float32, device=x.device) _rms_norm_fwd_fused_dynamic_symmetric[(M, )]( x_arg, y, w, scale, x_arg.stride(0), K, eps, BLOCK_SIZE=BLOCK_SIZE, num_warps=num_warps, ) return y, scale The provided code snippet includes necessary dependencies for implementing the `test_rms_and_linear` function. Write a Python function `def test_rms_and_linear(x, rms_weight, linear_weight, dtype=torch.float16, eps=1e-5)` to solve the following problem: Test quantized rms norm and quantized linear layer. Here is the function: def test_rms_and_linear(x, rms_weight, linear_weight, dtype=torch.float16, eps=1e-5): """Test quantized rms norm and quantized linear layer.""" def rms_norm_torch(x, w, eps): variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True) x = x * torch.rsqrt(variance + eps) return w * x def linear_torch(x, b): return F.linear(x, b) linear_weight_quant, linear_scale = per_channel_quant( linear_weight, 8, torch.int8) rms_out, rms_scale = rms_norm_dynamic_quant(x, rms_weight, eps) assert rms_out.shape == x.shape and rms_scale.shape[:-1] == x.shape[:-1] linear_out = matmul_kernel_dynamic_quant(rms_out, linear_weight_quant, rms_scale, linear_scale, output_dtype=dtype) rms_out_torch = rms_norm_torch(x, rms_weight, eps).half() linear_out_torch = linear_torch(rms_out_torch, linear_weight) print(f'linear_out.abs().mean() = {linear_out.abs().mean()}') print(f'linear_out_torch.abs().mean() = {linear_out_torch.abs().mean()}') print('perchannel error: ', (linear_out - linear_out_torch).abs().mean()) cos = torch.nn.CosineSimilarity(0) print( 'Output cos', cos(linear_out.flatten().to(torch.float32), linear_out_torch.flatten().to(torch.float32)))
Test quantized rms norm and quantized linear layer.
8,155
import torch import torch.nn.functional as F import triton import triton.language as tl def per_token_quant_int8(x, eps): """Function to perform per-token quantization on an input tensor `x`. It converts the tensor values into signed 8-bit integers and returns the quantized tensor along with the scaling factor used for quantization. """ x_q = torch.empty_like(x, device=x.device, dtype=torch.int8) M = x.numel() // x.shape[-1] N = x.shape[-1] x_s = torch.empty(x.shape[:-1] + (1, ), device=x.device, dtype=torch.float32) BLOCK = triton.next_power_of_2(N) # heuristics for number of warps num_warps = min(max(BLOCK // 256, 1), 8) # enqueue kernel _per_token_quant_int8[(M, )](x, x_q, x_s, x.stride(-2), N, eps, BLOCK=BLOCK, num_warps=num_warps) return x_q, x_s The provided code snippet includes necessary dependencies for implementing the `test_per_token_quant` function. Write a Python function `def test_per_token_quant(x, eps)` to solve the following problem: Test per-token quantization. Here is the function: def test_per_token_quant(x, eps): """Test per-token quantization.""" def per_token_quant_int8_torch(x, eps): _absmax = torch.clamp(x.abs().max(dim=-1, keepdim=True)[0], min=eps) x_s = _absmax / 127 x_q = torch.clamp((x / x_s).round(), min=-128, max=127) return x_q, x_s x_q, x_s = per_token_quant_int8(x, eps) x_q_torch, x_s_torch = per_token_quant_int8_torch(x, eps) assert x_q.shape == x_q_torch.shape and x_s.shape == x_s_torch.shape cos = torch.nn.CosineSimilarity(0) print( 'x_q cos', cos(x_q.flatten().to(torch.float32), x_q_torch.flatten().to(torch.float32))) print( 'x_s cos', cos(x_s.flatten().to(torch.float32), x_s_torch.flatten().to(torch.float32)))
Test per-token quantization.
8,156
import torch import torch.nn.functional as F import triton import triton.language as tl def per_channel_quant(x, n_bits, dtype): """Quantize the input tensor 'x' channel-wise using the given number of bits. Args: x (torch.Tensor): The input tensor to be quantized. Must be a 2-dimensional tensor. n_bits (int): The number of bits to use for quantization. dtype (torch.dtype): The data type to which the quantized tensor should be converted. Returns: tuple: A tuple containing two items -- the quantized tensor and the scale used for quantization. """ assert x.ndim == 2 x = x.to(torch.float32) x_absmax = x.view(x.shape[0], -1).abs().max(dim=1, keepdim=True)[0] q_max = 2**(n_bits - 1) - 1 q_min = -2**(n_bits - 1) scale = x_absmax / (2**(n_bits - 1) - 1) x_q = torch.round(x / scale).clamp(q_min, q_max).to(dtype) return x_q, scale configs=[ triton.Config({ 'BLOCK_M': 16, 'BLOCK_N': 128, 'BLOCK_K': 256, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 32, 'BLOCK_N': 64, 'BLOCK_K': 128, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 64, 'BLOCK_N': 64, 'BLOCK_K': 128, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 64, 'BLOCK_N': 128, 'BLOCK_K': 128, }, num_stages=4, num_warps=4), triton.Config({ 'BLOCK_M': 128, 'BLOCK_N': 128, 'BLOCK_K': 128, }, num_stages=4, num_warps=4) ], key=['M', 'N', 'K'], def matmul_kernel_dynamic_quant(a, b, rms_scale, linear_scale, residual=None, bias=None, output_dtype=torch.float16): """This function performs matrix multiplication with dynamic quantization. It takes two input tensors `a` and `b`, scales them with `rms_scale` and `linear_scale`, and optionally adds a `residual` tensor and a `bias`. The output is returned in the specified `output_dtype`. """ assert a.shape[-1] == b.shape[-1] assert b.ndim == 2 and b.is_contiguous() b = b.t() # (K, N) M = a.numel() // a.shape[-1] K, N = b.shape c_shape = a.shape[:-1] + (N, ) if residual is not None: assert residual.shape == c_shape assert residual.is_contiguous() c = torch.empty(c_shape, device=a.device, dtype=output_dtype) def grid(META): return (triton.cdiv(M, META['BLOCK_M']) * triton.cdiv(N, META['BLOCK_N']), ) if residual is not None: _linear_add[grid](a, b, c, residual, M, N, K, a.stride(-2), a.stride(-1), b.stride(0), b.stride(1), c.stride(-2), c.stride(-1), GROUP_SIZE_M=8, rms_scale_ptr=rms_scale, linear_scale_ptr=linear_scale) else: _linear[grid](a, b, c, M, N, K, a.stride(-2), a.stride(-1), b.stride(0), b.stride(1), c.stride(-2), c.stride(-1), GROUP_SIZE_M=8, rms_scale_ptr=rms_scale, linear_scale_ptr=linear_scale) if bias is not None: c += bias return c def rms_norm_dynamic_quant(x, w, eps): """Performs RMS normalization with dynamic quantization. The function reshapes the input tensor `x`, creates an empty tensor `y` with the same shape as `x`, and calculates RMS normalization on the reshaped `x` using a Triton kernel `_rms_norm_fwd_fused_dynamic_symmetric`. """ x_arg = x.reshape(-1, x.shape[-1]) y = torch.empty_like(x, dtype=torch.int8) M, K = x_arg.shape MAX_FUSED_SIZE = 65536 // x.element_size() BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(K)) if K > BLOCK_SIZE: raise RuntimeError( "This rms norm doesn't support feature dim >= 64KB.") num_warps = min(max(BLOCK_SIZE // 256, 1), 8) scale = torch.empty(x.shape[:-1] + (1, ), dtype=torch.float32, device=x.device) _rms_norm_fwd_fused_dynamic_symmetric[(M, )]( x_arg, y, w, scale, x_arg.stride(0), K, eps, BLOCK_SIZE=BLOCK_SIZE, num_warps=num_warps, ) return y, scale def bench_rms_and_linear(M, dtype, provider, eps=1e-5, device='cuda'): def rms_norm_torch(x, w, eps): variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True) x = x * torch.rsqrt(variance + eps) return w * x def linear_torch(x, b): return F.linear(x, b) N = 4096 K = 4096 x_shape = (M, K) rms_w_shape = (x_shape[-1], ) rms_weight = torch.randn(rms_w_shape, dtype=dtype, device='cuda', requires_grad=True) x = torch.randn(x_shape, dtype=dtype, device='cuda') linear_weight = torch.randn((N, K), dtype=dtype, device='cuda', requires_grad=True) linear_weight_quant, linear_scale = per_channel_quant( linear_weight, 8, torch.int8) alpha = max(x.max().abs(), x.min().abs()) rms_scale = alpha / 127 if provider == 'int8_dynamic_triton_op': rms_out, rms_scale = rms_norm_dynamic_quant(x, rms_weight, eps) def y_fwd(): matmul_kernel_dynamic_quant(rms_out, linear_weight_quant, rms_scale, linear_scale, output_dtype=dtype) elif provider == 'float_torch': rms_out_torch = rms_norm_torch(x, rms_weight, eps).half() def y_fwd(): linear_torch(rms_out_torch, linear_weight) quantiles = [0.5, 0.2, 0.8] ms, min_ms, max_ms = triton.testing.do_bench(y_fwd, quantiles=quantiles, rep=500) return ms, max_ms, min_ms
null
8,157
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def rms_norm(hidden_states: Tensor, weight: Tensor, eps: float = 1e-6): """rms norm.""" def _kernel_meta(): device = hidden_states.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) feat_size = weight.shape[0] seq_len = hidden_states.numel() // hidden_states.size(-1) input_stride = hidden_states.stride(-2) BLOCK_N = triton.next_power_of_2(feat_size) out = torch.empty_like(hidden_states) kernel_meta = _kernel_meta() grid = (seq_len, ) rms_norm_kernel[grid](hidden_states, weight, out, input_stride, feat_size, eps, feat_size, BLOCK_N, num_warps=4, num_stages=2, **kernel_meta) return out if __name__ == '__main__': import time def torch_forward(hidden_states, weight, variance_epsilon=1e-6): """pytorch forward.""" input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon) return weight * hidden_states.to(input_dtype) test_rms_norm(1, 8128, 5120, torch.float16) test_rms_norm(1, 8128, 5120, torch.float32) test_rms_norm(1, 992, 128, torch.float16) test_rms_norm(1, 65537, 128, torch.float32) The provided code snippet includes necessary dependencies for implementing the `test_rms_norm` function. Write a Python function `def test_rms_norm(bsz, ctx_len, feat_len, dtype)` to solve the following problem: test rms norm. Here is the function: def test_rms_norm(bsz, ctx_len, feat_len, dtype): """test rms norm.""" input = torch.empty((bsz, ctx_len, feat_len), dtype=dtype, device='cuda').normal_(mean=0., std=0.5).contiguous() weight = torch.empty((feat_len), dtype=dtype, device='cuda').normal_(mean=0., std=0.5).contiguous() triton_output = rms_norm(hidden_states=input, weight=weight) torch_output = torch_forward(hidden_states=input, weight=weight) assert torch.allclose(torch_output, triton_output, atol=1e-2, rtol=0) N_REPEATS = 20 t0 = time.time() for _ in range(N_REPEATS): torch_forward(hidden_states=input, weight=weight) t1 = time.time() for _ in range(N_REPEATS): rms_norm(hidden_states=input, weight=weight) t2 = time.time() torch_cost = (t1 - t0) / N_REPEATS * 1000 triton_cost = (t2 - t1) / N_REPEATS * 1000 print( 'input {} weight {} dtype {}\n torch {:.3f} triton {:.3f} (ms)\n'. format(input.shape, weight.shape, dtype, torch_cost, triton_cost))
test rms norm.
8,158
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def apply_rotary_pos_emb_kernel( Q, COS, SIN, POS, Q_EMB, seq_len, stride_qh: tl.constexpr, BLOCK: tl.constexpr, BLOCK_N: tl.constexpr, ): """apply rotary on key OR query kernel.""" seq_block_id = tl.program_id(0) head_id = tl.program_id(1) pos_offset = seq_block_id * BLOCK + tl.arange(0, BLOCK) pos_ids = tl.load(POS + pos_offset, pos_offset < seq_len, other=-1) feat_size = BLOCK_N * 2 feat_offset_l = tl.arange(0, BLOCK_N) feat_offset_h = BLOCK_N + feat_offset_l cs_offset_l = pos_ids[:, None] * feat_size + feat_offset_l[None, :] cs_offset_h = pos_ids[:, None] * feat_size + feat_offset_h[None, :] pos_ids_mask = pos_ids[:, None] >= 0 cos_l = tl.load(COS + cs_offset_l, mask=pos_ids_mask) cos_h = tl.load(COS + cs_offset_h, mask=pos_ids_mask) sin_l = tl.load(SIN + cs_offset_l, mask=pos_ids_mask) sin_h = tl.load(SIN + cs_offset_h, mask=pos_ids_mask) q_offset_seq = pos_offset[:, None] * stride_qh + head_id * feat_size q_offset_l = q_offset_seq + feat_offset_l[None, :] q_offset_h = q_offset_seq + feat_offset_h[None, :] pos_mask = pos_offset[:, None] < seq_len q_l = tl.load(Q + q_offset_l, mask=pos_mask) q_h = tl.load(Q + q_offset_h, mask=pos_mask) q_emb_l = q_l * cos_l - q_h * sin_l q_emb_h = q_h * cos_h + q_l * sin_h tl.store(Q_EMB + q_offset_l, q_emb_l, mask=pos_mask) tl.store(Q_EMB + q_offset_h, q_emb_h, mask=pos_mask) def apply_rotary_pos_emb_qk_kernel( Q, K, COS, SIN, POS, Q_EMB, K_EMB, seq_len, stride_qh: tl.constexpr, stride_kh: tl.constexpr, BLOCK: tl.constexpr, BLOCK_N: tl.constexpr, ): """apply rotary on key AND query kernel.""" seq_block_id = tl.program_id(0) head_id = tl.program_id(1) pos_offset = seq_block_id * BLOCK + tl.arange(0, BLOCK) pos_ids = tl.load(POS + pos_offset, pos_offset < seq_len, other=-1) feat_size = BLOCK_N * 2 feat_offset_l = tl.arange(0, BLOCK_N) feat_offset_h = BLOCK_N + feat_offset_l cs_offset_l = pos_ids[:, None] * feat_size + feat_offset_l[None, :] cs_offset_h = pos_ids[:, None] * feat_size + feat_offset_h[None, :] pos_ids_mask = pos_ids[:, None] >= 0 cos_l = tl.load(COS + cs_offset_l, mask=pos_ids_mask) cos_h = tl.load(COS + cs_offset_h, mask=pos_ids_mask) sin_l = tl.load(SIN + cs_offset_l, mask=pos_ids_mask) sin_h = tl.load(SIN + cs_offset_h, mask=pos_ids_mask) q_offset_seq = pos_offset[:, None] * stride_qh + head_id * feat_size q_offset_l = q_offset_seq + feat_offset_l[None, :] q_offset_h = q_offset_seq + feat_offset_h[None, :] k_offset_seq = pos_offset[:, None] * stride_kh + head_id * feat_size k_offset_l = k_offset_seq + feat_offset_l[None, :] k_offset_h = k_offset_seq + feat_offset_h[None, :] pos_mask = pos_offset[:, None] < seq_len q_l = tl.load(Q + q_offset_l, mask=pos_mask) q_h = tl.load(Q + q_offset_h, mask=pos_mask) k_l = tl.load(K + k_offset_l, mask=pos_mask) k_h = tl.load(K + k_offset_h, mask=pos_mask) q_emb_l = q_l * cos_l - q_h * sin_l q_emb_h = q_h * cos_h + q_l * sin_h k_emb_l = k_l * cos_l - k_h * sin_l k_emb_h = k_h * cos_h + k_l * sin_h tl.store(Q_EMB + q_offset_l, q_emb_l, mask=pos_mask) tl.store(Q_EMB + q_offset_h, q_emb_h, mask=pos_mask) tl.store(K_EMB + k_offset_l, k_emb_l, mask=pos_mask) tl.store(K_EMB + k_offset_h, k_emb_h, mask=pos_mask) The provided code snippet includes necessary dependencies for implementing the `apply_rotary_pos_emb` function. Write a Python function `def apply_rotary_pos_emb(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor, position_ids: Tensor, position_ids_1d: Tensor = None, q_embed: Tensor = None, k_embed: Tensor = None)` to solve the following problem: Apply rotary positional embedding on query and key. Args: q (Tensor): Query state. k (Tensor): Key state. cos (Tensor): cosine matrix (seq_len, dim). sin (Tensor): sine matrix (seq_len, dim). position_ids (Tensor): Position ids of q and k. position_ids_1d (Tensor): 1d Position ids. q_embed (Tensor): output q, can be same as q k_embed (Tensor): output k, can be same as k Returns: Tuple[Tensor, Tensor]: Embedded query and key. Here is the function: def apply_rotary_pos_emb(q: Tensor, k: Tensor, cos: Tensor, sin: Tensor, position_ids: Tensor, position_ids_1d: Tensor = None, q_embed: Tensor = None, k_embed: Tensor = None): """Apply rotary positional embedding on query and key. Args: q (Tensor): Query state. k (Tensor): Key state. cos (Tensor): cosine matrix (seq_len, dim). sin (Tensor): sine matrix (seq_len, dim). position_ids (Tensor): Position ids of q and k. position_ids_1d (Tensor): 1d Position ids. q_embed (Tensor): output q, can be same as q k_embed (Tensor): output k, can be same as k Returns: Tuple[Tensor, Tensor]: Embedded query and key. """ if not q.is_contiguous(): q = q.contiguous() if not k.is_contiguous(): k = k.contiguous() if cos.device != q.device or cos.dtype != q.dtype: cos = cos.to(device=q.device, dtype=q.dtype) if sin.device != q.device or sin.dtype != q.dtype: sin = sin.to(device=q.device, dtype=q.dtype) if position_ids_1d is None: seq_length = position_ids[..., -1] + 1 position_ids_1d = [ids[:l] for ids, l in zip(position_ids, seq_length)] position_ids_1d = torch.cat(position_ids_1d) if q_embed is None: q_embed = torch.empty_like(q) if k_embed is None: k_embed = torch.empty_like(k) seq_len = position_ids_1d.size(-1) BLOCK = 32 num_heads_q = q.size(-2) num_heads_k = k.size(-2) num_warps = 4 num_stages = 2 device = q.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) if num_heads_k == num_heads_q: grid = [triton.cdiv(seq_len, BLOCK), num_heads_q] apply_rotary_pos_emb_qk_kernel[grid](q, k, cos, sin, position_ids_1d, q_embed, k_embed, seq_len=seq_len, stride_qh=q.stride(-3), stride_kh=k.stride(-3), BLOCK=BLOCK, BLOCK_N=q.size(-1) // 2, num_warps=num_warps, num_stages=num_stages, stream=stream, device=device_idx, device_type=device_type) else: grid_q = [triton.cdiv(seq_len, BLOCK), num_heads_q] grid_k = [triton.cdiv(seq_len, BLOCK), num_heads_k] apply_rotary_pos_emb_kernel[grid_q](q, cos, sin, position_ids_1d, q_embed, seq_len=seq_len, stride_qh=q.stride(-3), BLOCK=BLOCK, BLOCK_N=q.size(-1) // 2, num_warps=num_warps, num_stages=num_stages, stream=stream, device=device_idx, device_type=device_type) apply_rotary_pos_emb_kernel[grid_k](k, cos, sin, position_ids_1d, k_embed, seq_len=seq_len, stride_qh=k.stride(-3), BLOCK=BLOCK, BLOCK_N=k.size(-1) // 2, num_warps=num_warps, num_stages=num_stages, stream=stream, device=device_idx, device_type=device_type) return q_embed, k_embed
Apply rotary positional embedding on query and key. Args: q (Tensor): Query state. k (Tensor): Key state. cos (Tensor): cosine matrix (seq_len, dim). sin (Tensor): sine matrix (seq_len, dim). position_ids (Tensor): Position ids of q and k. position_ids_1d (Tensor): 1d Position ids. q_embed (Tensor): output q, can be same as q k_embed (Tensor): output k, can be same as k Returns: Tuple[Tensor, Tensor]: Embedded query and key.
8,159
import torch import triton import triton.language as tl def rerope_attention_fwd(q1, q2, k1, k2, v, causal, sm_scale, window, BLOCK_M=64): """rerope attention forward.""" # shape constraints Lq, Lk, Lv = q1.shape[-1], k1.shape[-1], v.shape[-1] assert Lq == Lk and Lk == Lv assert Lk in {16, 32, 64, 128} o = torch.empty_like(q1) BLOCK_N = 64 if Lk <= 64 else 32 num_stages = 4 if Lk <= 64 else 3 num_warps = 4 grid = (triton.cdiv(q1.shape[2], BLOCK_M), q1.shape[0] * q1.shape[1], 1) # L = torch.empty((q1.shape[0] * q1.shape[1], q1.shape[2]), # device=q1.device, # dtype=torch.float32) _rerope_fwd_kernel[grid]( q1, q2, k1, k2, v, sm_scale, # L, o, q1.stride(0), q1.stride(1), q1.stride(2), q1.stride(3), k1.stride(0), k1.stride(1), k1.stride(2), k1.stride(3), v.stride(0), v.stride(1), v.stride(2), v.stride(3), o.stride(0), o.stride(1), o.stride(2), o.stride(3), q1.shape[0], q1.shape[1], q1.shape[2], BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, BLOCK_DMODEL=Lk, IS_CAUSAL=causal, WINDOW=window, num_warps=num_warps, num_stages=num_stages) return o def test_rerope(): import torch.utils.benchmark as benchmark Z = 1 H = 40 N_CTX = 2176 D_HEAD = 128 WINDOW = 512 sm_scale = 0.0883883 def torch_attention(q1, q2, k1, k2, v, causal, sm_scale, window): # reference implementation M = torch.tril(torch.ones((N_CTX, N_CTX), device='cuda')) p1 = torch.matmul(q1, k1.transpose(2, 3)) * sm_scale p2 = torch.matmul(q2, k2.transpose(2, 3)) * sm_scale if causal: p1[:, :, M == 0] = float('-inf') p2[:, :, M == 0] = float('-inf') x = torch.arange(N_CTX, dtype=torch.int, device='cuda') M2 = ((x[:, None] - x[None, :]).abs() < window)[None, None, :] p = torch.where(M2, p1, p2) p = torch.softmax(p.float(), dim=-1).half() ref_out = torch.matmul(p, v) return ref_out def torch_attention2(query_states1, query_states2, key_states1, key_states2, value_states, causal, sm_scale, window): query_states1 = query_states1.squeeze(0).contiguous() query_states2 = query_states2.squeeze(0).contiguous() key_states1 = key_states1.squeeze(0).contiguous() key_states2 = key_states2.squeeze(0).contiguous() value_states = value_states.squeeze(0).contiguous() attn_weights1 = torch.matmul( query_states1, key_states1.transpose(1, 2)) * sm_scale attn_weights2 = torch.matmul( query_states2, key_states2.transpose(1, 2)) * sm_scale position_ids = torch.arange( query_states1.shape[1], device=query_states1.device).unsqueeze(0) rectified_mask = (position_ids[:, -N_CTX:, None] - position_ids[:, None]).abs() < window attn_weights = torch.where(rectified_mask, attn_weights1, attn_weights2) if causal: tgt_len = attn_weights.shape[-1] dtype = attn_weights.dtype device = attn_weights.device mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_( mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) attn_weights = attn_weights + mask # upcast attention to fp32 attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to( query_states1.dtype) attn_output = torch.matmul(attn_weights, value_states) return attn_output q1 = torch.empty((Z, H, N_CTX, D_HEAD), dtype=torch.float16, device='cuda').normal_(mean=0., std=0.5).contiguous() q2 = torch.empty((Z, H, N_CTX, D_HEAD), dtype=torch.float16, device='cuda').normal_(mean=0., std=0.5).contiguous() k1 = torch.empty((Z, H, N_CTX, D_HEAD), dtype=torch.float16, device='cuda').normal_(mean=0., std=0.5).contiguous() k2 = torch.empty((Z, H, N_CTX, D_HEAD), dtype=torch.float16, device='cuda').normal_(mean=0., std=0.5).contiguous() v = torch.empty((Z, H, N_CTX, D_HEAD), dtype=torch.float16, device='cuda').normal_(mean=0., std=0.5).contiguous() # q1 = torch.load('/workspace/GitProjects/lmdeploy/q1.pt', # map_location='cuda').contiguous() # q2 = torch.load('/workspace/GitProjects/lmdeploy/q2.pt', # map_location='cuda').contiguous() # k1 = torch.load('/workspace/GitProjects/lmdeploy/k1.pt', # map_location='cuda').contiguous() # k2 = torch.load('/workspace/GitProjects/lmdeploy/k2.pt', # map_location='cuda').contiguous() # v = torch.load('/workspace/GitProjects/lmdeploy/v.pt', # map_location='cuda').contiguous() torch_output = torch_attention(q1, q2, k1, k2, v, True, sm_scale, WINDOW) torch_output2 = torch_attention2(q1, q2, k1, k2, v, True, sm_scale, WINDOW) assert torch.allclose(torch_output, torch_output2, atol=1e-2, rtol=0) for _ in range(100): triton_output = rerope_attention_fwd(q1, q2, k1, k2, v, True, sm_scale, WINDOW) assert torch.allclose( torch_output, triton_output, atol=2e-2, rtol=0) is True def f(fn, q1, q2, k1, k2, v, sm_scale, window): fn(q1, q2, k1, k2, v, True, sm_scale, window) t0 = benchmark.Timer(stmt='f(fn, q1, q2, k1, k2, v, sm_scale, window)', globals={ 'f': f, 'fn': torch_attention2, 'q1': q1, 'q2': q2, 'k1': k1, 'k2': k2, 'v': v, 'sm_scale': sm_scale, 'window': WINDOW }, num_threads=torch.get_num_threads()) print(t0.timeit(20)) import time begin = time.time() LOOP = 100 for _ in range(LOOP): rerope_attention_fwd(q1, q2, k1, k2, v, True, sm_scale, WINDOW) print(time.time() - begin)
null
8,160
import torch import triton import triton.language as tl from torch import Tensor from triton.runtime.jit import get_cuda_stream def _fused_rotary_emb_kernel( Q, K, PostionIds, InvFreq, scaling_factor, OutQ, OutK, stride_bq, stride_sq, stride_hq: tl.constexpr, stride_dq: tl.constexpr, stride_bk, stride_sk, stride_hk: tl.constexpr, stride_dk: tl.constexpr, stride_bp, stride_sp, max_seq_len, BLOCK: tl.constexpr, BLOCK_HQ: tl.constexpr, BLOCK_HK: tl.constexpr, BLOCK_F: tl.constexpr): """fused rotary emb kernel.""" batch_id = tl.program_id(0) seq_block_id = tl.program_id(1) s_off = seq_block_id * BLOCK + tl.arange(0, BLOCK)[:, None] f_off = tl.arange(0, BLOCK_F)[None, :] s_mask = s_off < max_seq_len bp_off = stride_bp * batch_id p_off = bp_off + stride_sp * s_off sq_off = batch_id * stride_bq + s_off * stride_sq q0_off = sq_off + f_off * stride_dq q1_off = q0_off + BLOCK_F * stride_dq sk_off = batch_id * stride_bk + s_off * stride_sk k0_off = sk_off + f_off * stride_dk k1_off = k0_off + BLOCK_F * stride_dk inv_freq = tl.load(InvFreq + f_off).to(tl.float32) position_ids = tl.load(PostionIds + p_off, mask=s_mask).to(tl.float32) position_ids = position_ids / scaling_factor # pos_freq = tl.dot(position_ids, inv_freq) pos_freq = position_ids * inv_freq cos = tl.cos(pos_freq).to(Q.dtype.element_ty) sin = tl.sin(pos_freq).to(Q.dtype.element_ty) for h in range(BLOCK_HQ): q0 = tl.load(Q + q0_off + h * stride_hq, mask=s_mask) q1 = tl.load(Q + q1_off + h * stride_hq, mask=s_mask) q0_out = q0 * cos - q1 * sin tl.store(OutQ + q0_off + h * stride_hq, q0_out, mask=s_mask) q1_out = q1 * cos + q0 * sin tl.store(OutQ + q1_off + h * stride_hq, q1_out, mask=s_mask) for h in range(BLOCK_HK): k0 = tl.load(K + k0_off + h * stride_hk, mask=s_mask) k1 = tl.load(K + k1_off + h * stride_hk, mask=s_mask) k0_out = k0 * cos - k1 * sin tl.store(OutK + k0_off + h * stride_hk, k0_out, mask=s_mask) k1_out = k1 * cos + k0 * sin tl.store(OutK + k1_off + h * stride_hk, k1_out, mask=s_mask) The provided code snippet includes necessary dependencies for implementing the `fused_rotary_emb` function. Write a Python function `def fused_rotary_emb(q: Tensor, k: Tensor, position_ids: torch.LongTensor, inv_freq: Tensor, scaling_factor: float, out_q: Tensor = None, out_k: Tensor = None)` to solve the following problem: Fuse `rotary_embedding` and `apply_rotary_pos_emb`. Here is the function: def fused_rotary_emb(q: Tensor, k: Tensor, position_ids: torch.LongTensor, inv_freq: Tensor, scaling_factor: float, out_q: Tensor = None, out_k: Tensor = None): """Fuse `rotary_embedding` and `apply_rotary_pos_emb`.""" def _kernel_meta(): device = q.device device_idx = device.index device_type = device.type stream = get_cuda_stream(device_idx) return dict(device=device, device_type=device_type, stream=stream) if out_q is None: out_q = torch.empty_like(q) else: assert q.stride() == out_q.stride() if out_k is None: out_k = torch.empty_like(k) else: assert k.stride() == out_k.stride() assert q.dim() == 4 assert k.dim() == 4 assert q.size(0) == position_ids.size(0) BLOCK = 32 BLOCK_HQ = q.size(-2) BLOCK_HK = k.size(-2) BLOCK_F = q.size(-1) // 2 batch_size = q.size(0) max_seq_len = q.size(1) kernel_meta = _kernel_meta() num_warps = 4 grid = (batch_size, triton.cdiv(max_seq_len, BLOCK)) _fused_rotary_emb_kernel[grid](q, k, position_ids, inv_freq, scaling_factor, out_q, out_k, stride_bq=q.stride(0), stride_sq=q.stride(1), stride_hq=q.stride(2), stride_dq=q.stride(3), stride_bk=k.stride(0), stride_sk=k.stride(1), stride_hk=k.stride(2), stride_dk=k.stride(3), stride_bp=position_ids.stride(0), stride_sp=position_ids.stride(1), max_seq_len=max_seq_len, BLOCK=BLOCK, BLOCK_HQ=BLOCK_HQ, BLOCK_HK=BLOCK_HK, BLOCK_F=BLOCK_F, num_warps=num_warps, num_stages=1, **kernel_meta) return out_q, out_k
Fuse `rotary_embedding` and `apply_rotary_pos_emb`.
8,161
import inspect from inspect import Parameter, Signature from typing import Dict, Sequence import psutil The provided code snippet includes necessary dependencies for implementing the `get_cpu_memory` function. Write a Python function `def get_cpu_memory() -> int` to solve the following problem: Returns the total CPU memory of the node in bytes. Here is the function: def get_cpu_memory() -> int: """Returns the total CPU memory of the node in bytes.""" return psutil.virtual_memory().total
Returns the total CPU memory of the node in bytes.
8,162
import inspect from inspect import Parameter, Signature from typing import Dict, Sequence import psutil The provided code snippet includes necessary dependencies for implementing the `bind_sigature` function. Write a Python function `def bind_sigature(input_names: str, args: Sequence, kwargs: Dict)` to solve the following problem: Bind args and kwargs to given input names. Here is the function: def bind_sigature(input_names: str, args: Sequence, kwargs: Dict): """Bind args and kwargs to given input names.""" kind = inspect._ParameterKind.POSITIONAL_OR_KEYWORD sig = Signature([Parameter(name, kind) for name in input_names]) bind = sig.bind(*args, **kwargs) return bind.arguments
Bind args and kwargs to given input names.
8,163
import re from dataclasses import dataclass from typing import Any, Dict, List import torch from torch import Tensor from ..block import LogicalTokenBlocks The provided code snippet includes necessary dependencies for implementing the `_cache_weight` function. Write a Python function `def _cache_weight(cache: Tensor, weight: Tensor, block_table: Tensor)` to solve the following problem: cache weight. Here is the function: def _cache_weight(cache: Tensor, weight: Tensor, block_table: Tensor): """cache weight.""" assert cache.dim() == 2 assert weight.dim() == 2 assert block_table.dim() == 1 rank, feat_size = weight.size() assert cache.size(-1) >= feat_size, ('cache.size(-1) >= feat_size failed.') assert rank <= block_table.size(0), ('rank <= block_table.size(0) failed.') block_table = block_table[:rank] cache[block_table, :feat_size] = weight.to(device=cache.device, dtype=cache.dtype)
cache weight.
8,164
import argparse import os import random from lmdeploy.messages import EngineGenerationConfig, PytorchEngineConfig from lmdeploy.model import MODELS from lmdeploy.tokenizer import Tokenizer from . import engine as tm The provided code snippet includes necessary dependencies for implementing the `valid_str` function. Write a Python function `def valid_str(string, coding='utf-8')` to solve the following problem: decode text according to its encoding type. Here is the function: def valid_str(string, coding='utf-8'): """decode text according to its encoding type.""" invalid_chars = [b'\xef\xbf\xbd'] bstr = bytes(string, coding) for invalid_char in invalid_chars: bstr = bstr.replace(invalid_char, b'') ret = bstr.decode(encoding=coding, errors='ignore') return ret
decode text according to its encoding type.
8,165
import argparse import os import random from lmdeploy.messages import EngineGenerationConfig, PytorchEngineConfig from lmdeploy.model import MODELS from lmdeploy.tokenizer import Tokenizer from . import engine as tm The provided code snippet includes necessary dependencies for implementing the `parse_config` function. Write a Python function `def parse_config()` to solve the following problem: parse arguments. Here is the function: def parse_config(): """parse arguments.""" parser = argparse.ArgumentParser(description='arg parser') parser.add_argument( '--model_path', type=str, default='/models/openbuddy-llama2-13b-v8.1-fp16', help='LLM path, use /models/openbuddy-llama2-13b-v8.1-fp16 by default') parser.add_argument('--model_name', type=str, default='llama2', help='LLM type name, use llama2 by default') parser.add_argument('--max_tokens', type=int, default=50000, help='maximum token length for evaluation') parser.add_argument('--interval', type=int, default=1024, help='interval for evaluation') parser.add_argument('--num_tests', type=int, default=1, help='number of repeat testing for each length') args = parser.parse_args() return args
parse arguments.
8,166
import argparse import os import random from lmdeploy.messages import EngineGenerationConfig, PytorchEngineConfig from lmdeploy.model import MODELS from lmdeploy.tokenizer import Tokenizer from . import engine as tm The provided code snippet includes necessary dependencies for implementing the `generate_prompt_landmark` function. Write a Python function `def generate_prompt_landmark(n_garbage=60000, seed=666)` to solve the following problem: Generates a text file and inserts an passkey at a random position. Here is the function: def generate_prompt_landmark(n_garbage=60000, seed=666): """Generates a text file and inserts an passkey at a random position.""" from numpy import random as nprandom rnd_state = nprandom.get_state() nprandom.seed(seed) n_garbage_prefix = nprandom.randint(0, n_garbage) n_garbage_suffix = n_garbage - n_garbage_prefix task_description = 'There is an important info hidden inside a lot of irrelevant text. Find it and memorize them. I will quiz you about the important information there.' # noqa: E501 garbage = 'The grass is green. The sky is blue. The sun is yellow. Here we go. There and back again.' # noqa: E501 garbage_num = n_garbage // (len(garbage) + 1) + 1 garbage_inf = ' '.join([garbage] * garbage_num) assert len(garbage_inf) >= n_garbage garbage_prefix = garbage_inf[:n_garbage_prefix] garbage_suffix = garbage_inf[:n_garbage_suffix] pass_key = nprandom.randint(1, 50000) information_line = f'The pass key is {pass_key}. Remember it. {pass_key} is the pass key.' # noqa: E501 final_question = 'What is the pass key? The pass key is' lines = [ task_description, garbage_prefix, information_line, garbage_suffix, final_question, ] nprandom.set_state(rnd_state) return '\n'.join(lines), str(pass_key)
Generates a text file and inserts an passkey at a random position.
8,167
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.models.llama.configuration_llama import LlamaConfig from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0)` to solve the following problem: Make causal mask used for bi-directional self-attention. Here is the function: def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0): """Make causal mask used for bi-directional self-attention.""" bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([ torch.zeros( tgt_len, past_key_values_length, dtype=dtype, device=device), mask ], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
Make causal mask used for bi-directional self-attention.
8,168
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.models.llama.configuration_llama import LlamaConfig from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem: Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. Here is the function: def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.""" bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
8,169
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.models.llama.configuration_llama import LlamaConfig from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., :x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2:] return torch.cat((-x2, x1), dim=-1) The provided code snippet includes necessary dependencies for implementing the `apply_rotary_pos_emb` function. Write a Python function `def apply_rotary_pos_emb(q, k, cos, sin, position_ids)` to solve the following problem: Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition. Here is the function: def apply_rotary_pos_emb(q, k, cos, sin, position_ids): """Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition. """ # The first two dimensions of cos and sin are always 1, # so we can `squeeze` them. cos = cos.squeeze(1).squeeze(0) # [seq_len, dim] sin = sin.squeeze(1).squeeze(0) # [seq_len, dim] cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition.
8,170
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.models.llama.configuration_llama import LlamaConfig from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger The provided code snippet includes necessary dependencies for implementing the `repeat_kv` function. Write a Python function `def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor` to solve the following problem: This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) Here is the function: def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
8,171
import math import queue import threading import warnings from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from einops import rearrange from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm2 import InternLM2Config The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0)` to solve the following problem: Make causal mask used for bi-directional self-attention. Here is the function: def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0): """Make causal mask used for bi-directional self-attention.""" bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([ torch.zeros( tgt_len, past_key_values_length, dtype=dtype, device=device), mask ], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
Make causal mask used for bi-directional self-attention.
8,172
import math import queue import threading import warnings from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from einops import rearrange from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm2 import InternLM2Config The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem: Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. Here is the function: def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.""" bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
8,173
import math import queue import threading import warnings from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from einops import rearrange from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm2 import InternLM2Config def rotate_half(x): def apply_rotary_pos_emb(q, k, cos, sin, position_ids): cos = cos[position_ids].unsqueeze(1) sin = sin[position_ids].unsqueeze(1) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
null
8,174
import math import queue import threading import warnings from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from einops import rearrange from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm2 import InternLM2Config The provided code snippet includes necessary dependencies for implementing the `repeat_kv` function. Write a Python function `def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor` to solve the following problem: This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) Here is the function: def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
8,175
import torch.nn as nn from lmdeploy.pytorch.models import QLinear, QRMSNorm LAYER_TYPE_MAP = { 'InternLMForCausalLM': 'InternLMDecoderLayer', 'InternLM2ForCausalLM': 'InternLM2DecoderLayer', 'QWenLMHeadModel': 'QWenBlock', 'BaiChuanForCausalLM': 'DecoderLayer', 'LlamaForCausalLM': 'LlamaDecoderLayer', } NORM_TYPE_MAP = { 'InternLMForCausalLM': 'InternLMRMSNorm', 'InternLM2ForCausalLM': 'InternLM2RMSNorm', 'QWenLMHeadModel': 'RMSNorm', 'BaiChuanForCausalLM': 'RMSNorm', 'LlamaForCausalLM': 'LlamaRMSNorm', } def convert(module, layer_type, norm_type): """Recursively traverses through given PyTorch module and identifies child layers that match the specified layer_type and norm_type for conversion to their Quantized counterparts. The conversion is done using the `convert_decoder_layer` function. """ for child in module.children(): if type(child).__name__ == layer_type: convert_decoder_layer(child, norm_type) else: convert(child, layer_type, norm_type) The provided code snippet includes necessary dependencies for implementing the `convert_to_qmodules` function. Write a Python function `def convert_to_qmodules(model)` to solve the following problem: Convert all Linear and RMSNorm in the decoder layers of the model into their Quantized versions (QLinear, QRMSNorm). Here is the function: def convert_to_qmodules(model): """Convert all Linear and RMSNorm in the decoder layers of the model into their Quantized versions (QLinear, QRMSNorm).""" layer_type = LAYER_TYPE_MAP[type(model).__name__] norm_type = NORM_TYPE_MAP[type(model).__name__] convert(model, layer_type, norm_type) return
Convert all Linear and RMSNorm in the decoder layers of the model into their Quantized versions (QLinear, QRMSNorm).
8,176
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from transformers import PreTrainedModel from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_baichuan import BaiChuanConfig The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0)` to solve the following problem: Make causal mask used for bi-directional self-attention. Here is the function: def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0): """Make causal mask used for bi-directional self-attention.""" bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([ torch.zeros( tgt_len, past_key_values_length, dtype=dtype, device=device), mask ], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
Make causal mask used for bi-directional self-attention.
8,177
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from transformers import PreTrainedModel from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_baichuan import BaiChuanConfig The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem: Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. Here is the function: def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.""" bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
8,178
import math from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import CrossEntropyLoss from transformers import PreTrainedModel from transformers.activations import ACT2FN from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_baichuan import BaiChuanConfig def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., :x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2:] return torch.cat((-x2, x1), dim=-1) The provided code snippet includes necessary dependencies for implementing the `apply_rotary_pos_emb` function. Write a Python function `def apply_rotary_pos_emb(q, k, cos, sin, position_ids)` to solve the following problem: Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition. Here is the function: def apply_rotary_pos_emb(q, k, cos, sin, position_ids): """Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition. """ # The first two dimensions of cos and sin are always 1, # so we can `squeeze` them. cos = cos.squeeze(1).squeeze(0) # [seq_len, dim] sin = sin.squeeze(1).squeeze(0) # [seq_len, dim] cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition.
8,179
import math import queue import threading from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.generation.streamers import BaseStreamer from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm import InternLMConfig The provided code snippet includes necessary dependencies for implementing the `_make_causal_mask` function. Write a Python function `def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0)` to solve the following problem: Make causal mask used for bi-directional self-attention. Here is the function: def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0): """Make causal mask used for bi-directional self-attention.""" bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) mask_cond = torch.arange(mask.size(-1), device=device) mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) mask = mask.to(dtype) if past_key_values_length > 0: mask = torch.cat([ torch.zeros( tgt_len, past_key_values_length, dtype=dtype, device=device), mask ], dim=-1) return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
Make causal mask used for bi-directional self-attention.
8,180
import math import queue import threading from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.generation.streamers import BaseStreamer from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm import InternLMConfig The provided code snippet includes necessary dependencies for implementing the `_expand_mask` function. Write a Python function `def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None)` to solve the following problem: Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. Here is the function: def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): """Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.""" bsz, src_len = mask.size() tgt_len = tgt_len if tgt_len is not None else src_len expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) inverted_mask = 1.0 - expanded_mask return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
8,181
import math import queue import threading from typing import List, Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.generation.streamers import BaseStreamer from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast) from transformers.modeling_utils import PreTrainedModel from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings) from lmdeploy.pytorch.modeling.convert_to_qmodules import convert_to_qmodules from lmdeploy.utils import get_logger from .configuration_internlm import InternLMConfig def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., :x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2:] return torch.cat((-x2, x1), dim=-1) The provided code snippet includes necessary dependencies for implementing the `apply_rotary_pos_emb` function. Write a Python function `def apply_rotary_pos_emb(q, k, cos, sin, position_ids)` to solve the following problem: Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition. Here is the function: def apply_rotary_pos_emb(q, k, cos, sin, position_ids): """Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition. """ # The first two dimensions of cos and sin are always 1, so we can # `squeeze` them. cos = cos.squeeze(1).squeeze(0) # [seq_len, dim] sin = sin.squeeze(1).squeeze(0) # [seq_len, dim] cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
Apply rotary positional embeddings to query and key tensors. This function applies the cosine and sine positional embeddings on the input query (q) and key (k) tensors using element-wise multiplication and addition.
8,182
import enum import time from copy import deepcopy from dataclasses import dataclass, field from typing import Any, Dict, List import torch from torch import Tensor from lmdeploy.messages import EngineGenerationConfig from lmdeploy.utils import get_logger from .block import LogicalTokenBlocks _SEQ_COUNT = 0 The provided code snippet includes necessary dependencies for implementing the `_new_msg_id` function. Write a Python function `def _new_msg_id()` to solve the following problem: get a new message id. Here is the function: def _new_msg_id(): """get a new message id.""" global _SEQ_COUNT seq_id = _SEQ_COUNT _SEQ_COUNT += 1 return seq_id
get a new message id.
8,183
from dataclasses import dataclass, field from typing import Any, Dict import torch The provided code snippet includes necessary dependencies for implementing the `_get_torch_dtype` function. Write a Python function `def _get_torch_dtype(config: Any, default: str = 'float16')` to solve the following problem: Get the torch dtype from the model config. Args: config: Config of the hf model. default (str): default device type. Here is the function: def _get_torch_dtype(config: Any, default: str = 'float16'): """Get the torch dtype from the model config. Args: config: Config of the hf model. default (str): default device type. """ torch_dtype = getattr(config, 'torch_dtype', default) # torch_dtype in config could be none torch_dtype = torch_dtype or default return eval(f'torch.{torch_dtype}')
Get the torch dtype from the model config. Args: config: Config of the hf model. default (str): default device type.