id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
8,184 | import torch
import triton
import triton.language as tl
def _add_kernel(A, B, C, size, BLOCK: tl.constexpr):
"""add kernel."""
prog_id = tl.program_id(0)
offs = prog_id * BLOCK + tl.arange(0, BLOCK)
a = tl.load(A + offs, mask=offs < size)
b = tl.load(B + offs, mask=offs < size)
tl.store(C + offs... | custom add one. |
8,185 | import asyncio
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Dict, List, Union
import torch
import torch.distributed as dist
from torch import multiprocessing as mp
from torch.distributed._tensor import DeviceMesh, Replicate, distribute_tensor
from transformers import Auto... | unparam lora weight. We don't want to move weight of lora to gpu. |
8,186 | import asyncio
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Dict, List, Union
import torch
import torch.distributed as dist
from torch import multiprocessing as mp
from torch.distributed._tensor import DeviceMesh, Replicate, distribute_tensor
from transformers import Auto... | Start model loops for tensor parallel model inference. Args: rank (int): Distribution rank. model_path (int): Path of the hugging face model. Could be local or online. model_config (ModelConfig): The config of the model. cache_config (CacheConfig): The config of the cache. in_que (mp.Queue): Input queue. Used to receiv... |
8,187 | import asyncio
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Dict, List, Union
import torch
import torch.distributed as dist
from torch import multiprocessing as mp
from torch.distributed._tensor import DeviceMesh, Replicate, distribute_tensor
from transformers import Auto... | Start the tensor parallel process. Args: rank (int): The distribution rank. world_size (int): The distribution world size. func (Callable): The function to be called in the process. args (List): The arguments of the func. kwargs (Dict): The keyword arguments of the func. |
8,188 | import asyncio
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Dict, List, Union
import torch
import torch.distributed as dist
from torch import multiprocessing as mp
from torch.distributed._tensor import DeviceMesh, Replicate, distribute_tensor
from transformers import Auto... | get response. |
8,189 | import asyncio
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Dict, List, Union
import torch
import torch.distributed as dist
from torch import multiprocessing as mp
from torch.distributed._tensor import DeviceMesh, Replicate, distribute_tensor
from transformers import Auto... | get response. |
8,190 | import asyncio
import os
from dataclasses import asdict, dataclass, field
from typing import Any, Callable, Dict, List, Union
import torch
import torch.distributed as dist
from torch import multiprocessing as mp
from torch.distributed._tensor import DeviceMesh, Replicate, distribute_tensor
from transformers import Auto... | create model agent. |
8,191 | import asyncio
import enum
from dataclasses import dataclass, field
from queue import Empty, Queue
from threading import Lock, Thread
from typing import Any, Awaitable, Callable, Dict, List
from lmdeploy.messages import ResponseType
from lmdeploy.utils import get_logger
logger = get_logger('lmdeploy')
def _raise_excep... | null |
8,192 | import asyncio
import enum
from dataclasses import dataclass, field
from queue import Empty, Queue
from threading import Lock, Thread
from typing import Any, Awaitable, Callable, Dict, List
from lmdeploy.messages import ResponseType
from lmdeploy.utils import get_logger
logger = get_logger('lmdeploy')
def _ignore_exce... | null |
8,193 | import asyncio
import enum
from dataclasses import dataclass, field
from queue import Empty, Queue
from threading import Lock, Thread
from typing import Any, Awaitable, Callable, Dict, List
from lmdeploy.messages import ResponseType
from lmdeploy.utils import get_logger
logger = get_logger('lmdeploy')
The provided cod... | run untile complete. |
8,194 | from typing import Dict, List, Tuple
import torch
from torch.distributed._tensor import DeviceMesh
from lmdeploy.utils import get_logger
from ..config import CacheConfig, ModelConfig
The provided code snippet includes necessary dependencies for implementing the `_get_dtype_size` function. Write a Python function `def ... | get size of the given dtype. Args: dtype (torch.dtype): Data type. Return: int: size in bytes. |
8,195 | from dataclasses import asdict, dataclass
from typing import Dict, List
import torch
from transformers.generation.logits_process import LogitsWarper
from ..messages import SchedulerSequence
The provided code snippet includes necessary dependencies for implementing the `_process_temperature` function. Write a Python fu... | process temperature. |
8,196 | from dataclasses import asdict, dataclass
from typing import Dict, List
import torch
from transformers.generation.logits_process import LogitsWarper
from ..messages import SchedulerSequence
The provided code snippet includes necessary dependencies for implementing the `_process_bad_words` function. Write a Python func... | process bad words. |
8,197 | from dataclasses import asdict, dataclass
from typing import Dict, List
import torch
from transformers.generation.logits_process import LogitsWarper
from ..messages import SchedulerSequence
The provided code snippet includes necessary dependencies for implementing the `_process_repetition_penalty` function. Write a Py... | process repetition penalty. |
8,198 | from dataclasses import asdict, dataclass
from typing import Dict, List
import torch
from transformers.generation.logits_process import LogitsWarper
from ..messages import SchedulerSequence
The provided code snippet includes necessary dependencies for implementing the `_filter_topk_sorted` function. Write a Python fun... | filter topk on sorted scores. |
8,199 | from dataclasses import asdict, dataclass
from typing import Dict, List
import torch
from transformers.generation.logits_process import LogitsWarper
from ..messages import SchedulerSequence
The provided code snippet includes necessary dependencies for implementing the `_filter_topp_sorted` function. Write a Python fun... | filter topp on sorted scores. |
8,200 | from dataclasses import asdict, dataclass
from typing import Dict, List
import torch
from transformers.generation.logits_process import LogitsWarper
from ..messages import SchedulerSequence
def multinomial_sampling(scores: torch.Tensor,
seeds: torch.LongTensor,
offsets... | sampling. |
8,201 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | perform div up. |
8,202 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | null |
8,203 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | tensorlize block_offsets. |
8,204 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | get adapter ids. |
8,205 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | Add new session. Args: session_id (int): The session id to add. |
8,206 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | End the given session. |
8,207 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | Stop current streaming inference. |
8,208 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | Add new session. Args: session_id (int): The session id to add. |
8,209 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | End the given session. |
8,210 | import asyncio
import os
from dataclasses import dataclass
from typing import Any, Dict, List
import torch
from lmdeploy.messages import (EngineGenerationConfig, PytorchEngineConfig,
ResponseType)
from lmdeploy.tokenizer import Tokenizer
from lmdeploy.utils import get_logger, get_model, l... | Stop current streaming inference. |
8,211 | from dataclasses import dataclass
import numpy as np
def _div_up(x, n):
"""perform div up."""
return (x + n - 1) // n
The provided code snippet includes necessary dependencies for implementing the `_round_up` function. Write a Python function `def _round_up(x, n)` to solve the following problem:
perform round ... | perform round up. |
8,212 | from typing import List, Optional, Tuple
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.utils.checkpoint
from torch.distributed._tensor import DeviceMesh, Shard, distribute_tensor
from transformers.modeling_outputs import BaseModelOutputWithPast
from ..dist_utils import (colwise_parall... | Split a tensor along its last dimension. Arguments: tensor: input tensor. num_partitions: number of partitions to split the tensor contiguous_split_chunks: If True, make each chunk contiguous in memory. Returns: A list of Tensors |
8,213 | from typing import List, Optional, Tuple
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.utils.checkpoint
from torch.distributed._tensor import DeviceMesh, Shard, distribute_tensor
from transformers.modeling_outputs import BaseModelOutputWithPast
from ..dist_utils import (colwise_parall... | null |
8,214 | from typing import List, Optional, Tuple, Union
import torch
import torch.distributed as dist
import transformers
from packaging import version
from torch import nn
from torch.distributed._tensor import DeviceMesh
from transformers.modeling_outputs import BaseModelOutputWithPast
from ..dist_utils import (colwise_parall... | Applies Rotary Position Embedding to the query and key tensors. |
8,215 | from typing import List, Optional, Tuple, Union
import torch
import torch.distributed as dist
from torch import nn
from torch.distributed._tensor import DeviceMesh, Shard, distribute_tensor
from transformers.modeling_outputs import BaseModelOutputWithPast
from ..dist_utils import (colwise_parallelize_linear_fn,
... | A function for attention partition. |
8,216 | import math
from typing import Any, Callable, Optional, Sequence, Tuple
import numpy as np
import torch
from torch import Tensor
from ..kernels import apply_rotary_pos_emb, fill_kv_cache, rerope_attention_fwd
The provided code snippet includes necessary dependencies for implementing the `repeat_kv` function. Write a P... | This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (num_key_value_heads, seqlen, head_dim) to (num_attention_heads, seqlen, head_dim) |
8,217 | import math
from typing import Any, Callable, Optional, Sequence, Tuple
import numpy as np
import torch
from torch import Tensor
from ..kernels import apply_rotary_pos_emb, fill_kv_cache, rerope_attention_fwd
The provided code snippet includes necessary dependencies for implementing the `generate_batched_mask` functio... | Generate batched mask. |
8,218 | import math
from typing import Any, Callable, Optional, Sequence, Tuple
import numpy as np
import torch
from torch import Tensor
from ..kernels import apply_rotary_pos_emb, fill_kv_cache, rerope_attention_fwd
def get_slopes(n: int):
"""Get alibi slopes."""
def _get_interleave_power_of_2(n):
start = 2**(... | Get alibi bias. |
8,219 | import math
from typing import Any, Callable, Optional, Sequence, Tuple
import numpy as np
import torch
from torch import Tensor
from ..kernels import apply_rotary_pos_emb, fill_kv_cache, rerope_attention_fwd
def quant_kv(key: torch.Tensor, value: torch.Tensor, out_type: torch.dtype):
"""Quantize key and value of a... | Attention module forward with ReRoPE. Args: hidden_states (Tensor): Input of attention layer. history_lengths (Sequence): Cache lengths of each data in batch. block_offsets (Tensor): Block table of the key/value caches, used by paged attention. num_heads (int): numbers of query heads. num_kv_heads (int): numbers of key... |
8,220 | from typing import List, Optional, Tuple, Union
import torch
import torch.distributed as dist
from torch import nn
from torch.distributed._tensor import DeviceMesh
from transformers.modeling_outputs import BaseModelOutputWithPast
from ..dist_utils import (colwise_parallelize_linear_fn,
rowwise... | null |
8,221 | import torch
The provided code snippet includes necessary dependencies for implementing the `batch_tensor` function. Write a Python function `def batch_tensor(inputs: torch.Tensor, seq_length: torch.LongTensor)` to solve the following problem:
Convert continuoused tensor to batched tensor. Args: inputs (Tensor): conti... | Convert continuoused tensor to batched tensor. Args: inputs (Tensor): continuoused tensor. seq_length (Tensor): length of each sequence. Return: Tensor: batched tensor. |
8,222 | from typing import Any, List, Tuple
import torch
from .layout_convert import continuous_tensor, page_cache
def make_model_inputs(input_ids: torch.Tensor,
block_offsets: torch.Tensor,
seq_length: torch.Tensor = None,
history_length: List[int] = None):
... | make step context. |
8,223 | import argparse
import copy
import json
import os
import shutil
import torch
from mmengine.utils import mkdir_or_exist
def parse_args():
parser = argparse.ArgumentParser(
description='Convert a hugging face model to the smallest sharded one')
parser.add_argument('src_dir', help='the directory of the mo... | null |
8,224 | import torch
from torch import nn
from lmdeploy.lite.quantization.awq import (FC_FCS_MAP, NORM_FCS_MAP,
quant_weights, smooth_layers)
from lmdeploy.lite.utils import collect_target_modules
from .calibrate import calibrate
LAYER_TYPE_MAP = {
'InternLMForCausalLM': 'InternL... | Perform weight quantization using AWQ algorithm. Args: model (str): The path of model in hf format. work_dir (str): The working directory to save results. calib_dataset (str): The calibration dataset name. calib_samples (int): The number of samples for calibration. calib_seqlen (int): The sequence length for calibratio... |
8,225 | import os.path as osp
import shutil
import fire
import torch
from torch import nn
import lmdeploy
from lmdeploy.lite.apis.calibrate import calibrate
from lmdeploy.lite.quantization.awq import (FC_FCS_MAP, NORM_FCS_MAP,
smooth_layers)
from lmdeploy.lite.utils import collect_ta... | null |
8,226 | import os
from pathlib import Path
from typing import Union
import numpy as np
import torch
def _export_weight(into: str,
kv_qparams: np.array,
out_path: str,
tm_params: dict = None):
"""Save kv_qparams to disk or copy to tm_params."""
if tm_params is Non... | Export symmetric quantization parameters to specified directory. |
8,227 | import os
from pathlib import Path
from typing import Union
import numpy as np
import torch
def _export_weight(into: str,
kv_qparams: np.array,
out_path: str,
tm_params: dict = None):
"""Save kv_qparams to disk or copy to tm_params."""
if tm_params is Non... | Export asymmetric quantization parameters to specified directory. |
8,228 | from typing import List
import torch
NORM_FCS_MAP = {
'LlamaDecoderLayer': {
'input_layernorm':
['self_attn.k_proj', 'self_attn.q_proj', 'self_attn.v_proj'],
'post_attention_layernorm': ['mlp.gate_proj', 'mlp.up_proj']
},
'InternLMDecoderLayer': {
'input_layernorm':
[... | Check if the smooth function is supported by inspecting layer type. |
8,229 | import json
import os
import shutil
from huggingface_hub import snapshot_download
from lmdeploy.turbomind.utils import get_hf_config_content
def get_hf_config_content(pretrained_model_name_or_path, **kwargs) -> dict:
"""Get config content of a hf model."""
config_path = get_hf_config_path(pretrained_model_name... | Export hf lmdeploy model and config.json. |
8,230 | import numpy as np
import torch
def set_seed(seed):
np.random.seed(seed)
torch.random.manual_seed(seed) | null |
8,231 | import numpy as np
import torch
def get_wikitext2(tokenizer, nsamples, seed, seqlen):
"""Load Wikitext-2 train and test datasets and tokenize.
Args:
tokenizer: Tokenizer to encode text.
nsamples: Number of samples to take from train set.
seed: Random seed for sampling.
seqlen: Ma... | Get calibration data loaders for a dataset. Args: name: Dataset name ('wikitext2', 'ptb', 'c4', etc). tokenizer: Tokenizer to encode text. nsamples: Number of samples to take from train set. seed: Random seed for sampling. seqlen: Maximum sequence length. Returns: train_loader: List of sampled and tokenized training ex... |
8,232 | from typing import Dict, List, Tuple, Union
from torch import nn
def collect_target_modules(model: nn.Module,
target: Union[str, type],
skip_names: List[str] = [],
prefix: str = '') -> Dict[str, nn.Module]:
"""Collects the specific tar... | Collects weights of the specific target modules from the model. Args: model : The PyTorch module from which to collect the weights of target modules. target : The specific target whose weights to be collected. It can be a class of a module or the name of a module. skip_names : Names of modules to be skipped during weig... |
8,233 | from typing import Dict, List, Tuple, Union
from torch import nn
The provided code snippet includes necessary dependencies for implementing the `bimap_name_mod` function. Write a Python function `def bimap_name_mod( name2mod_mappings: List[Dict[str, nn.Module]] ) -> Tuple[Dict[str, nn.Module], Dict[nn.Module, str]... | Generates bidirectional maps from module names to module instances and vice versa. Args: name2mod_mappings : List of dictionaries each mapping from module names to module instances. Returns: Two dictionaries providing bidirectional mappings between module names and module instances. |
8,234 | from typing import NamedTuple, Optional
import torch
class QParams(NamedTuple):
"""A class to hold the quantization parameters."""
scales: torch.Tensor
zero_points: Optional[torch.Tensor]
The provided code snippet includes necessary dependencies for implementing the `cal_qparams_per_channel_absmax` functio... | Calculate quantization parameters for each channel using absolute max value. |
8,235 | from typing import NamedTuple, Optional
import torch
class QParams(NamedTuple):
"""A class to hold the quantization parameters."""
scales: torch.Tensor
zero_points: Optional[torch.Tensor]
def precise_round(x):
return x.sign() * (x.abs() + 0.5).floor()
The provided code snippet includes necessary depend... | Calculate quantization parameters for each channel using min and max values. |
8,236 | from typing import NamedTuple, Optional
import torch
class QParams(NamedTuple):
"""A class to hold the quantization parameters."""
scales: torch.Tensor
zero_points: Optional[torch.Tensor]
The provided code snippet includes necessary dependencies for implementing the `cal_qparams_per_group_absmax` function.... | Calculate quantization parameters for each group using absolute max value. |
8,237 | from typing import NamedTuple, Optional
import torch
class QParams(NamedTuple):
"""A class to hold the quantization parameters."""
scales: torch.Tensor
zero_points: Optional[torch.Tensor]
def precise_round(x):
return x.sign() * (x.abs() + 0.5).floor()
The provided code snippet includes necessary depend... | Calculate quantization parameters for each group using min and max values. |
8,238 | from typing import NamedTuple, Optional
import torch
class QParams(NamedTuple):
"""A class to hold the quantization parameters."""
scales: torch.Tensor
zero_points: Optional[torch.Tensor]
def precise_round(x):
return x.sign() * (x.abs() + 0.5).floor()
The provided code snippet includes necessary depend... | Calculate quantization parameters for the entire tensor using min and max values. |
8,239 | from typing import NamedTuple, Optional
import torch
class QParams(NamedTuple):
"""A class to hold the quantization parameters."""
scales: torch.Tensor
zero_points: Optional[torch.Tensor]
The provided code snippet includes necessary dependencies for implementing the `cal_qparams_per_tensor_absmax` function... | Calculate quantization parameters for the entire tensor using absolute max value. |
8,240 | import torch
from transformers import AutoConfig, AutoModelForCausalLM
from lmdeploy.pytorch.accel import LoadNoInit
class LoadNoInit:
"""Initialize model without parameter initialization."""
def __init__(self):
self.constant_ = torch.nn.init.constant_
self.zeros_ = torch.nn.init.zeros_
... | null |
8,241 | from typing import Any, Dict, List, Tuple, Union
import torch
The provided code snippet includes necessary dependencies for implementing the `split_decoder_layer_inputs` function. Write a Python function `def split_decoder_layer_inputs( *args: Union[torch.Tensor, Any], **kwargs: Union[torch.Tensor, Any] ) -> Tuple... | This function splits batched decoder layer inputs into individual elements. Args: *args (Union[torch.Tensor, Any]): Positional arguments which could be a mix of tensors and other types. **kwargs (Union[torch.Tensor, Any]): Keyword arguments which could be a mix of tensors and other types. Returns: Tuple[List[List[Any]]... |
8,242 | from typing import Any, Dict, List, Tuple, Union
import torch
The provided code snippet includes necessary dependencies for implementing the `concat_decoder_layer_outputs` function. Write a Python function `def concat_decoder_layer_outputs( batch_outputs: List[Tuple[Any]]) -> Tuple[Any]` to solve the following... | This function concatenates individual decoder layer outputs into a batched output. Args: batch_outputs (List[Tuple[Any]]): A list of tuples, where each tuple represents the output from an individual element in the batch. Returns: Tuple[Any]: A tuple representing the batched output. |
8,243 | import inspect
import re
import warnings
from contextlib import contextmanager
from functools import partial
from typing import List
import torch
from torch import nn
from lmdeploy.lite.defaults import KV_CACHE_SIGNATURE, OFFLOAD_MOD
def offload_kv_cache(model: nn.Module, device: str = 'cuda') -> None:
"""Offloads ... | Memory efficient inference context manager. Moves model to device for inference, with option to offload specific modules. Args: model (nn.Module): Model for inference offload (bool): Whether to offload modules device (str): Device for inference Yields: None |
8,244 | from .chat import SubCliChat
from .cli import CLI
from .lite import SubCliLite
from .serve import SubCliServe
class SubCliChat(object):
_help = 'Chat with pytorch or turbomind engine.'
_desc = _help
parser = CLI.subparsers.add_parser('chat', help=_help, description=_desc)
subparsers = parser.add_subpar... | The entry point of running LMDeploy CLI. |
8,245 | import argparse
from typing import List
The provided code snippet includes necessary dependencies for implementing the `convert_args` function. Write a Python function `def convert_args(args)` to solve the following problem:
Convert args to dict format.
Here is the function:
def convert_args(args):
"""Convert ar... | Convert args to dict format. |
8,246 | import argparse
from typing import List
The provided code snippet includes necessary dependencies for implementing the `get_lora_adapters` function. Write a Python function `def get_lora_adapters(adapters: List[str])` to solve the following problem:
Parse lora adapers from cli input. Args: adapters (List[str]): CLI in... | Parse lora adapers from cli input. Args: adapters (List[str]): CLI input string of lora adapter path(s). Returns: Dict[str,str] or None: Parsed lora adapter path(s). |
8,247 | import os
import sys
import pytorch_sphinx_theme
from m2r import MdInclude
from recommonmark.transform import AutoStructify
from sphinx.builders.html import StandaloneHTMLBuilder
def setup(app):
app.add_config_value('no_underscore_emphasis', False, 'env')
app.add_config_value('m2r_parse_relative_links', False,... | null |
8,249 | import argparse
import os
import random
from contextlib import contextmanager
from dataclasses import dataclass, field
from itertools import count
from pathlib import Path
from threading import Lock
from typing import List, Tuple
import gradio as gr
from packaging.version import Version, parse
from qwen_model import Qw... | null |
8,250 | import argparse
import os
import random
from contextlib import contextmanager
from dataclasses import dataclass, field
from itertools import count
from pathlib import Path
from threading import Lock
from typing import List, Tuple
import gradio as gr
from packaging.version import Version, parse
from qwen_model import Qw... | Load preprocessor and llm inference engine. |
8,251 | import argparse
import os
import random
from contextlib import contextmanager
from dataclasses import dataclass, field
from itertools import count
from pathlib import Path
from threading import Lock
from typing import List, Tuple
import gradio as gr
from packaging.version import Version, parse
from qwen_model import Qw... | null |
8,252 | import os
from pathlib import Path
import torch
from transformers import AutoModel, AutoTokenizer
from xcomposer_model import InternLMXComposerTemplate
def get_attr(m, key):
keys = key.split('.')
for key in keys:
m = getattr(m, key)
return m | null |
8,253 | import argparse
import csv
import json
import os
import random
import time
from queue import Queue
from threading import Thread
from typing import List, Tuple, Union
import numpy as np
from tqdm import tqdm
from lmdeploy.cli.utils import ArgumentHelper, DefaultsAndTypesHelpFormatter
from lmdeploy.messages import (Engin... | null |
8,254 | import argparse
import csv
import json
import os
import random
import time
from queue import Queue
from threading import Thread
from typing import List, Tuple, Union
import numpy as np
from tqdm import tqdm
from lmdeploy.cli.utils import ArgumentHelper, DefaultsAndTypesHelpFormatter
from lmdeploy.messages import (Engin... | null |
8,255 | import csv
import json
import random
import time
from queue import Queue
from threading import Thread
from typing import List, Tuple
import fire
import numpy as np
from tqdm import tqdm
from lmdeploy.serve.turbomind.chatbot import Chatbot
from lmdeploy.tokenizer import Tokenizer
class Tokenizer:
"""Tokenize prompt... | null |
8,256 | import argparse
import csv
import os
import time
from dataclasses import dataclass
from queue import Queue
from threading import Thread
from typing import List, Union
import numpy as np
from pynvml import (NVMLError, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex,
nvmlDeviceGetMemoryInfo, nvmlDevice... | null |
8,257 | import argparse
import csv
import os
import time
from dataclasses import dataclass
from queue import Queue
from threading import Thread
from typing import List, Union
import numpy as np
from pynvml import (NVMLError, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex,
nvmlDeviceGetMemoryInfo, nvmlDevice... | null |
8,258 | import argparse
import csv
import os
import time
from dataclasses import dataclass
from queue import Queue
from threading import Thread
from typing import List, Union
import numpy as np
from pynvml import (NVMLError, nvmlDeviceGetCount, nvmlDeviceGetHandleByIndex,
nvmlDeviceGetMemoryInfo, nvmlDevice... | null |
8,259 | import csv
import logging
import os
import time
from typing import Optional
import fire
import torch
from transformers import AutoModelForCausalLM, GenerationConfig
from lmdeploy.pytorch.accel import LoadNoInit
from lmdeploy.utils import get_logger
class LoadNoInit:
"""Initialize model without parameter initializa... | null |
8,260 | import csv
import logging
import os
import time
from typing import Optional
import fire
import torch
from transformers import AutoModelForCausalLM, GenerationConfig
from lmdeploy.pytorch.accel import LoadNoInit
from lmdeploy.utils import get_logger
def accel_deepspeed(model, max_out_tokens, tp_size=1):
import deep... | null |
8,261 | import csv
import json
import random
import time
from queue import Queue
from threading import Thread
from typing import List, Tuple
import fire
import numpy as np
from tqdm import tqdm
from lmdeploy.serve.openai.api_client import APIClient
from lmdeploy.tokenizer import Tokenizer
class Tokenizer:
"""Tokenize prom... | null |
8,262 | import json
import pickle
import time
from pathlib import Path
import fire
import numpy as np
from transformers import AutoTokenizer
from lmdeploy.pytorch.decode import Engine
The provided code snippet includes necessary dependencies for implementing the `benchmark` function. Write a Python function `def benchmark(mod... | Benchmark using ShareGPT data. Please download `ShareGPT_V3_unfiltered_cleaned_split.json` as data for this benchmark. |
8,263 | import math
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
def sort_pack_padded_sequence(input, lengths):
sorted_lengths, indices = torch.sort(lengths, descending=True)
tmp = pack_padded_sequence(input[indices], sort... | null |
8,264 | import math
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence
def repeat_tensor(x, n):
return x.unsqueeze(0).repeat(n, *([1] * len(x.shape))) | null |
8,265 | import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio import transforms
from torchlibrosa.augmentation import SpecAugmentation
from .utils import mean_with_lens, max_with_lens, \
init, pack_wrapper, generate_length_mask, PositionalEncoding
def init(m, method="ka... | Initialize a Linear or Convolutional layer. |
8,266 | import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio import transforms
from torchlibrosa.augmentation import SpecAugmentation
from .utils import mean_with_lens, max_with_lens, \
init, pack_wrapper, generate_length_mask, PositionalEncoding
The provided code snip... | Initialize a Batchnorm layer. |
8,267 | import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio import transforms
from torchlibrosa.augmentation import SpecAugmentation
from .utils import mean_with_lens, max_with_lens, \
init, pack_wrapper, generate_length_mask, PositionalEncoding
class LinearSoftPool(nn... | parse_poolingfunction A heler function to parse any temporal pooling Pooling is done on dimension 1 :param poolingfunction_name: :param **kwargs: |
8,268 | import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio import transforms
from torchlibrosa.augmentation import SpecAugmentation
from .utils import mean_with_lens, max_with_lens, \
init, pack_wrapper, generate_length_mask, PositionalEncoding
def mean_with_lens(fea... | null |
8,269 | import math
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio import transforms
from torchlibrosa.augmentation import SpecAugmentation
from .utils import mean_with_lens, max_with_lens, \
init, pack_wrapper, generate_length_mask, PositionalEncoding
def conv_conv_block(in... | null |
8,270 | import json
from tqdm import tqdm
import logging
import pickle
from collections import Counter
import re
import fire
def build_vocab(input_json: str,
threshold: int,
keep_punctuation: bool,
host_address: str,
character_level: bool = False,
... | null |
8,271 | import json
from tqdm import tqdm
import logging
import pickle
from collections import Counter
import re
import fire
def build_vocab(input_json: str,
output_json: str,
threshold: int,
keep_punctuation: bool,
character_level: bool = False,
z... | null |
8,272 | import json
from tqdm import tqdm
import logging
import pickle
from collections import Counter
import re
import fire
def build_vocab(input_json: str,
output_json: str,
threshold: int,
keep_punctuation: bool,
host_address: str,
character_lev... | null |
8,273 | import json
from tqdm import tqdm
import re
import fire
The provided code snippet includes necessary dependencies for implementing the `tokenize_caption` function. Write a Python function `def tokenize_caption(input_json: str, keep_punctuation: bool = False, host_address: str ... | Build vocabulary from csv file with a given threshold to drop all counts < threshold Args: input_json(string): Preprossessed json file. Structure like this: { 'audios': [ { 'audio_id': 'xxx', 'captions': [ { 'caption': 'xxx', 'cap_id': 'xxx' } ] }, ... ] } threshold (int): Threshold to drop all words with counts < thre... |
8,274 | import os
import sys
import logging
from typing import Callable, Dict, Union
import yaml
import torch
from torch.optim.swa_utils import AveragedModel as torch_average_model
import numpy as np
import pandas as pd
from pprint import pformat
def load_dict_from_csv(csv, cols):
df = pd.read_csv(csv, sep="\t")
outpu... | null |
8,275 | import os
import sys
import logging
from typing import Callable, Dict, Union
import yaml
import torch
from torch.optim.swa_utils import AveragedModel as torch_average_model
import numpy as np
import pandas as pd
from pprint import pformat
def init_logger(filename, level="INFO"):
formatter = logging.Formatter(
... | null |
8,276 | import os
import sys
import logging
from typing import Callable, Dict, Union
import yaml
import torch
from torch.optim.swa_utils import AveragedModel as torch_average_model
import numpy as np
import pandas as pd
from pprint import pformat
The provided code snippet includes necessary dependencies for implementing the `... | pprint_dict :param outputfun: function to use, defaults to sys.stdout :param in_dict: dict to print |
8,277 | import os
import sys
import logging
from typing import Callable, Dict, Union
import yaml
import torch
from torch.optim.swa_utils import AveragedModel as torch_average_model
import numpy as np
import pandas as pd
from pprint import pformat
def load_config(config_file):
with open(config_file, "r") as reader:
... | null |
8,278 | import os
import sys
import logging
from typing import Callable, Dict, Union
import yaml
import torch
from torch.optim.swa_utils import AveragedModel as torch_average_model
import numpy as np
import pandas as pd
from pprint import pformat
def store_yaml(config, config_file):
with open(config_file, "w") as con_writ... | null |
8,279 | import os
import sys
import logging
from typing import Callable, Dict, Union
import yaml
import torch
from torch.optim.swa_utils import AveragedModel as torch_average_model
import numpy as np
import pandas as pd
from pprint import pformat
def fix_batchnorm(model: torch.nn.Module):
def inner(module):
class_... | null |
8,280 | import copy
import json
import numpy as np
import fire
def evaluate_annotation(key2refs, scorer):
if scorer.method() == "Bleu":
scores = np.array([ 0.0 for n in range(4) ])
else:
scores = 0
num_cap_per_audio = len(next(iter(key2refs.values())))
for i in range(num_cap_per_audio):
... | null |
8,281 | import copy
import json
import numpy as np
import fire
def evaluate_prediction(key2pred, key2refs, scorer):
if scorer.method() == "Bleu":
scores = np.array([ 0.0 for n in range(4) ])
else:
scores = 0
num_cap_per_audio = len(next(iter(key2refs.values())))
for i in range(num_cap_per_audi... | null |
8,282 | import numpy as np
import pandas as pd
import torch
from gensim.models import FastText
from tqdm import tqdm
import fire
import sys
import os
from utils.build_vocab import Vocabulary
def create_embedding(caption_file: str,
vocab_file: str,
embed_size: int,
... | null |
8,283 | import os
import sys
import copy
import pickle
import numpy as np
import pandas as pd
import fire
def coco_score(refs, pred, scorer):
if scorer.method() == "Bleu":
scores = np.array([ 0.0 for n in range(4) ])
else:
scores = 0
num_cap_per_audio = len(refs[list(refs.keys())[0]])
for i in... | null |
8,284 | import os
import sys
import copy
import pickle
import numpy as np
import pandas as pd
import fire
def embedding_score(refs, pred, scorer):
num_cap_per_audio = len(refs[list(refs.keys())[0]])
scores = 0
for i in range(num_cap_per_audio):
res = {key: [refs[key][i],] for key in refs.keys() if len(re... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.