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 ... | 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... | 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 rev... | 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 ... | 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 inclu... | 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 inclu... | 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():
... | 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():
... | 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 inclu... | 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:
... | 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 inclu... | 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.rn... | 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.rn... | 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.rn... | 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.rn... | 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.rn... | 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.rn... | 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.rn... | 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... | 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 ... | 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 filte... | 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_w... | 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... | 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 loggi... | 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 pr... | 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
... | 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
... | 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. - temperatur... |
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
... | 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... |
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
... | 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 t... |
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
... | 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 t... |
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
... | 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
... | 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
... | 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 fo... |
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
... | 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 fo... |
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, GenerationCon... | 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 ... | 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.... | 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, ... | 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, ... | 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, ... | 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, ... | 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, ... | 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 fo... |
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, ... | 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 t... |
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, ... | 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 (Li... |
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:
... | 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 effe... | 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... |
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... | 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... | 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... | 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 cur... | 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-vari... | 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-vari... | 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.htm... | 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... | 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... | 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... | 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... | 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 ... | 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... |
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... | 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 implementin... | 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 implementin... | 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
... | 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, Sch... | 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... | 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 b... |
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. |
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,
str... | 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 fo... |
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,
... | 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,... | 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_s... | 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_tab... | 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... | 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 fac... | 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... | 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
... | 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 rota... | 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 sa... |
8,159 | import torch
import triton
import triton.language as tl
def rerope_attention_fwd(q1,
q2,
k1,
k2,
v,
causal,
sm_scale,
window,
... | 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,
... | 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 m... | 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 follo... | 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, ... | 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. Wr... | 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.... | 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_landmar... | 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 (BaseModelOu... | 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 (BaseModelOu... | 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 (BaseModelOu... | 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 (BaseModelOu... | 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 transf... | 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 transf... | 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 transf... | 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 transf... | 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... | 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,
... | 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,
... | 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,
... | 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 BaseStream... | 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 BaseStream... | 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 BaseStream... | 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 provide... | 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 to... | Get the torch dtype from the model config. Args: config: Config of the hf model. default (str): default device type. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.