method_name stringlengths 3 45 | method_body stringlengths 9 6.25k | full_code stringlengths 35 7.02k | docstring stringlengths 18 4.7k ⌀ |
|---|---|---|---|
get_cumulative_logprob | return self.data.cumulative_logprob | def get_cumulative_logprob(self) ->float:
return self.data.cumulative_logprob | null |
forward | intermediate_parallel, _ = self.dense_h_to_4h(hidden_states)
intermediate_parallel = self.activation_func(intermediate_parallel)
output, _ = self.dense_4h_to_h(intermediate_parallel)
return output | def forward(self, hidden_states):
intermediate_parallel, _ = self.dense_h_to_4h(hidden_states)
intermediate_parallel = self.activation_func(intermediate_parallel)
output, _ = self.dense_4h_to_h(intermediate_parallel)
return output | null |
get_supported_act_dtypes | return [torch.half] | def get_supported_act_dtypes(self) ->List[torch.dtype]:
return [torch.half] | null |
from_sampling_metadata | prompt_tokens: List[List[int]] = []
output_tokens: List[List[int]] = []
top_ks: List[int] = []
temperatures: List[float] = []
top_ps: List[float] = []
min_ps: List[float] = []
presence_penalties: List[float] = []
frequency_penalties: List[float] = []
repetition_penalties: List[float] = []
do_penalties = False
do_top_p_... | @classmethod
def from_sampling_metadata(cls, sampling_metadata: 'SamplingMetadata',
vocab_size: int, device: torch.device, dtype: torch.dtype) ->Tuple[
'SamplingTensors', bool, bool, bool]:
prompt_tokens: List[List[int]] = []
output_tokens: List[List[int]] = []
top_ks: List[int] = []
temperature... | null |
__init__ | super().__init__()
self.config = config
assert config.tie_word_embeddings
self.linear_method = linear_method
self.transformer = MPTModel(config, linear_method)
self.lm_head_weight = self.transformer.wte.weight
self.sampler = Sampler(config.vocab_size) | def __init__(self, config: MPTConfig, linear_method: Optional[
LinearMethodBase]=None):
super().__init__()
self.config = config
assert config.tie_word_embeddings
self.linear_method = linear_method
self.transformer = MPTModel(config, linear_method)
self.lm_head_weight = self.transformer.wte.w... | null |
generate | outputs: List[Tuple[List[int], str]] = []
for prompt in prompts:
input_ids = self.tokenizer(prompt, return_tensors='pt').input_ids
output_ids = self.model.generate(input_ids.cuda(), use_cache=True, **kwargs
)
output_str = self.tokenizer.batch_decode(output_ids,
skip_special_tokens=True, clea... | def generate(self, prompts: List[str], **kwargs) ->List[Tuple[List[int], str]]:
outputs: List[Tuple[List[int], str]] = []
for prompt in prompts:
input_ids = self.tokenizer(prompt, return_tensors='pt').input_ids
output_ids = self.model.generate(input_ids.cuda(), use_cache=True,
**kwar... | null |
sample | next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | def sample(self, hidden_states: torch.Tensor, sampling_metadata:
SamplingMetadata) ->Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | null |
generate_beam_search | beam_search_params = SamplingParams(n=beam_width, use_beam_search=True,
temperature=0.0, max_tokens=max_tokens)
outputs = self.generate(prompts, beam_search_params)
return outputs | def generate_beam_search(self, prompts: List[str], beam_width: int,
max_tokens: int) ->List[Tuple[List[int], str]]:
beam_search_params = SamplingParams(n=beam_width, use_beam_search=True,
temperature=0.0, max_tokens=max_tokens)
outputs = self.generate(prompts, beam_search_params)
return outputs | null |
get_scaled_act_names | return ['gelu', 'gelu_fast', 'gelu_new', 'gelu_pytorch_tanh'] | def get_scaled_act_names(self) ->List[str]:
return ['gelu', 'gelu_fast', 'gelu_new', 'gelu_pytorch_tanh'] | null |
get_act_fn | """Get an activation function by name."""
act_fn_name = act_fn_name.lower()
if act_fn_name not in _ACTIVATION_REGISTRY:
raise ValueError(f'Activation function {act_fn_name!r} is not supported.')
act_fn = _ACTIVATION_REGISTRY[act_fn_name]
if quant_config is not None and act_fn_name in quant_config.get_scaled_act_nam... | def get_act_fn(act_fn_name: str, quant_config: Optional[QuantizationConfig]
=None, intermediate_size: Optional[int]=None, input_is_parallel: bool=
True, params_dtype: Optional[torch.dtype]=None) ->nn.Module:
"""Get an activation function by name."""
act_fn_name = act_fn_name.lower()
if act_fn_name n... | Get an activation function by name. |
weight_loader | param_data = param.data
if self.input_is_parallel:
tp_rank = get_tensor_model_parallel_rank()
shard_size = param_data.shape[0]
start_idx = tp_rank * shard_size
loaded_weight = loaded_weight.narrow(0, start_idx, shard_size)
assert param_data.shape == loaded_weight.shape
param_data.copy_(loaded_weight) | def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor):
param_data = param.data
if self.input_is_parallel:
tp_rank = get_tensor_model_parallel_rank()
shard_size = param_data.shape[0]
start_idx = tp_rank * shard_size
loaded_weight = loaded_weight.narrow(0, start... | null |
__init__ | super().__init__()
self.gate_up_proj = MergedColumnParallelLinear(hidden_size, [
intermediate_size] * 2, bias=False, linear_method=linear_method)
self.down_proj = RowParallelLinear(intermediate_size, hidden_size, bias=
False, linear_method=linear_method)
if hidden_act != 'silu':
raise ValueError(
f'... | def __init__(self, hidden_size: int, intermediate_size: int, hidden_act:
str, linear_method: Optional[LinearMethodBase]=None):
super().__init__()
self.gate_up_proj = MergedColumnParallelLinear(hidden_size, [
intermediate_size] * 2, bias=False, linear_method=linear_method)
self.down_proj = RowPar... | null |
get_linear_method | """Get the linear method to use for the quantized linear layer."""
raise NotImplementedError | @abstractmethod
def get_linear_method(self) ->LinearMethodBase:
"""Get the linear method to use for the quantized linear layer."""
raise NotImplementedError | Get the linear method to use for the quantized linear layer. |
_read_prompts | prompts = []
with open(filename, 'r') as f:
prompt = f.readline()
prompts.append(prompt)
return prompts | def _read_prompts(filename: str) ->str:
prompts = []
with open(filename, 'r') as f:
prompt = f.readline()
prompts.append(prompt)
return prompts | null |
forward | return self.decoder(input_ids, positions, kv_caches, input_metadata) | def forward(self, input_ids: torch.Tensor, positions: torch.Tensor,
kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor:
return self.decoder(input_ids, positions, kv_caches, input_metadata) | null |
__init__ | self.scaling_factor = scaling_factor
super().__init__(head_size, rotary_dim, max_position_embeddings, base,
is_neox_style) | def __init__(self, head_size: int, rotary_dim: int, max_position_embeddings:
int, base: int, is_neox_style: bool, scaling_factor: float) ->None:
self.scaling_factor = scaling_factor
super().__init__(head_size, rotary_dim, max_position_embeddings, base,
is_neox_style) | null |
__init__ | self.scheduler_config = scheduler_config
self.cache_config = cache_config
self.prompt_limit = min(self.scheduler_config.max_model_len, self.
scheduler_config.max_num_batched_tokens)
self.policy = PolicyFactory.get_policy(policy_name='fcfs')
self.block_manager = BlockSpaceManager(block_size=self.cache_config.
bl... | def __init__(self, scheduler_config: SchedulerConfig, cache_config: CacheConfig
) ->None:
self.scheduler_config = scheduler_config
self.cache_config = cache_config
self.prompt_limit = min(self.scheduler_config.max_model_len, self.
scheduler_config.max_num_batched_tokens)
self.policy = Policy... | null |
__init__ | self.quant_config = quant_config | def __init__(self, quant_config: AWQConfig):
self.quant_config = quant_config | null |
test_rotary_embedding | if rotary_dim is None:
rotary_dim = head_size
torch.random.manual_seed(seed)
torch.cuda.manual_seed(seed)
gpu_id = f'cuda:{device}'
if rotary_dim is None:
rotary_dim = head_size
rope = get_rope(head_size, rotary_dim, max_position, base, is_neox_style)
rope = rope.to(dtype=dtype, device=gpu_id)
positions = torch... | @pytest.mark.parametrize('is_neox_style', IS_NEOX_STYLE)
@pytest.mark.parametrize('batch_size', BATCH_SIZES)
@pytest.mark.parametrize('seq_len', SEQ_LENS)
@pytest.mark.parametrize('num_heads', NUM_HEADS)
@pytest.mark.parametrize('head_size', HEAD_SIZES)
@pytest.mark.parametrize('rotary_dim', ROTARY_DIMS)
@pytest.mark.p... | null |
__init__ | self.vocab_size = vocab_size
n_embed = kwargs.pop('n_embed', None)
self.hidden_size = hidden_size if n_embed is None else n_embed
self.n_layer = n_layer
self.n_head = n_head
self.layer_norm_epsilon = layer_norm_epsilon
self.initializer_range = initializer_range
self.use_cache = use_cache
self.hidden_dropout = hidden_dr... | def __init__(self, vocab_size=250880, hidden_size=64, n_layer=2, n_head=8,
layer_norm_epsilon=1e-05, initializer_range=0.02, use_cache=True,
bos_token_id=1, eos_token_id=2, hidden_dropout=0.0, attention_dropout=
0.0, multi_query=True, n_head_kv=None, alibi=False, bias=False,
parallel_attn=False, new_dec... | null |
forward | qkv, _ = self.qkv_proj(hidden_states)
q, k, v = qkv.chunk(chunks=3, dim=-1)
q, k = self.rotary_emb(positions, q, k)
k_cache, v_cache = kv_cache
attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata)
output, _ = self.o_proj(attn_output)
return output | def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor,
kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor:
qkv, _ = self.qkv_proj(hidden_states)
q, k, v = qkv.chunk(chunks=3, dim=-1)
q, k = self.rotary_emb(positions, q, k)
k_cache, v_cache = kv_cache
attn_output = ... | null |
is_empty | return not self.scheduled_seq_groups and not self.blocks_to_swap_in and not self.blocks_to_swap_out and not self.blocks_to_copy | def is_empty(self) ->bool:
return (not self.scheduled_seq_groups and not self.blocks_to_swap_in and
not self.blocks_to_swap_out and not self.blocks_to_copy) | null |
generate_beam_search | outputs = self.generate(prompts, do_sample=False, max_new_tokens=max_tokens,
num_beams=beam_width, num_return_sequences=beam_width)
for i in range(len(outputs)):
output_ids, output_str = outputs[i]
for j in range(len(output_ids)):
output_ids[j] = [x for x in output_ids[j] if x != self.tokenizer.
... | def generate_beam_search(self, prompts: List[str], beam_width: int,
max_tokens: int) ->List[Tuple[List[int], str]]:
outputs = self.generate(prompts, do_sample=False, max_new_tokens=
max_tokens, num_beams=beam_width, num_return_sequences=beam_width)
for i in range(len(outputs)):
output_ids, o... | null |
append_token_id | assert token_id in logprobs
self._append_tokens_to_blocks([token_id])
self.output_logprobs.append(logprobs)
self.data.append_token_id(token_id, logprobs[token_id]) | def append_token_id(self, token_id: int, logprobs: Dict[int, float]) ->None:
assert token_id in logprobs
self._append_tokens_to_blocks([token_id])
self.output_logprobs.append(logprobs)
self.data.append_token_id(token_id, logprobs[token_id]) | null |
forward | hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
return hidden_states | def forward(self, input_ids: torch.Tensor, positions: torch.Tensor,
kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor:
hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
return hidden_states | null |
forward | hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
return hidden_states | def forward(self, input_ids: torch.Tensor, positions: torch.Tensor,
kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor:
hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
return hidden_states | null |
weight_loader | param_data = param.data
output_dim = getattr(param, 'output_dim', None)
if loaded_shard_id is None:
if output_dim is None:
assert param_data.shape == loaded_weight.shape
param_data.copy_(loaded_weight)
return
shard_offsets = [('q', 0, self.total_num_heads * self.head_size), ('k',
... | def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor,
loaded_shard_id: Optional[str]=None):
param_data = param.data
output_dim = getattr(param, 'output_dim', None)
if loaded_shard_id is None:
if output_dim is None:
assert param_data.shape == loaded_weight.shape
... | null |
_init_cache | """Profiles the memory usage and initializes the KV cache."""
num_blocks = self._run_workers('profile_num_available_blocks', block_size=
self.cache_config.block_size, gpu_memory_utilization=self.cache_config.
gpu_memory_utilization, cpu_swap_space=self.cache_config.swap_space_bytes)
num_gpu_blocks = min(b[0] fo... | def _init_cache(self) ->None:
"""Profiles the memory usage and initializes the KV cache."""
num_blocks = self._run_workers('profile_num_available_blocks',
block_size=self.cache_config.block_size, gpu_memory_utilization=
self.cache_config.gpu_memory_utilization, cpu_swap_space=self.
cache... | Profiles the memory usage and initializes the KV cache. |
sample | next_tokens = self.sampler(self.lm_head_weight, hidden_states,
sampling_metadata)
return next_tokens | def sample(self, hidden_states: torch.Tensor, sampling_metadata:
SamplingMetadata) ->Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head_weight, hidden_states,
sampling_metadata)
return next_tokens | null |
_compute_cos_sin_cache | inv_freq = self._compute_inv_freq(self.base)
max_len = self.max_position_embeddings * self.scaling_factor
t = torch.arange(max_len, dtype=torch.float, device='cuda')
t = t / self.scaling_factor
freqs = torch.einsum('i,j -> ij', t, inv_freq)
cos = freqs.cos()
sin = freqs.sin()
cache = torch.cat((cos, sin), dim=-1)
retur... | def _compute_cos_sin_cache(self) ->torch.Tensor:
inv_freq = self._compute_inv_freq(self.base)
max_len = self.max_position_embeddings * self.scaling_factor
t = torch.arange(max_len, dtype=torch.float, device='cuda')
t = t / self.scaling_factor
freqs = torch.einsum('i,j -> ij', t, inv_freq)
cos = ... | null |
test_api_server | """
Run the API server and test it.
We run both the server and requests in separate processes.
We test that the server can handle incoming requests, including
multiple requests at the same time, and that it can handle requests
being cancelled without crashing.
"""
with Pool(32) as pool:
pr... | def test_api_server(api_server):
"""
Run the API server and test it.
We run both the server and requests in separate processes.
We test that the server can handle incoming requests, including
multiple requests at the same time, and that it can handle requests
being cancelled without crashing.
... | Run the API server and test it.
We run both the server and requests in separate processes.
We test that the server can handle incoming requests, including
multiple requests at the same time, and that it can handle requests
being cancelled without crashing. |
generate | self.request_id = request_id | def generate(self, request_id):
self.request_id = request_id | null |
get_hipcc_rocm_version | result = subprocess.run(['hipcc', '--version'], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True)
if result.returncode != 0:
print("Error running 'hipcc --version'")
return None
match = re.search('HIP version: (\\S+)', result.stdout)
if match:
return match.group(1)
else:
print('Could not ... | def get_hipcc_rocm_version():
result = subprocess.run(['hipcc', '--version'], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True)
if result.returncode != 0:
print("Error running 'hipcc --version'")
return None
match = re.search('HIP version: (\\S+)', result.stdout)
if ma... | null |
__init__ | super().__init__()
self.config = config
self.embed_in = VocabParallelEmbedding(config.vocab_size, config.hidden_size)
self.layers = nn.ModuleList([GPTNeoXLayer(config, linear_method) for _ in
range(config.num_hidden_layers)])
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.
layer_norm_eps) | def __init__(self, config: GPTNeoXConfig, linear_method: Optional[
LinearMethodBase]=None):
super().__init__()
self.config = config
self.embed_in = VocabParallelEmbedding(config.vocab_size, config.
hidden_size)
self.layers = nn.ModuleList([GPTNeoXLayer(config, linear_method) for _ in
... | null |
__init__ | assert dtype in _STR_DTYPE_TO_TORCH_DTYPE
torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=
torch_dtype, trust_remote_code=True).cuda()
if tokenizer_name is None:
tokenizer_name = model_name
self.tokenizer = get_tokenizer(tokenizer_name, tr... | def __init__(self, model_name: str, tokenizer_name: Optional[str]=None,
dtype: str='half') ->None:
assert dtype in _STR_DTYPE_TO_TORCH_DTYPE
torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]
self.model = AutoModelForCausalLM.from_pretrained(model_name,
torch_dtype=torch_dtype, trust_remote_code=Tru... | null |
main | print(args)
llm = LLM(model=args.model, tokenizer=args.tokenizer, quantization=args.
quantization, tensor_parallel_size=args.tensor_parallel_size,
trust_remote_code=args.trust_remote_code, dtype=args.dtype,
enforce_eager=args.enforce_eager)
sampling_params = SamplingParams(n=args.n, temperature=0.0 if args.... | def main(args: argparse.Namespace):
print(args)
llm = LLM(model=args.model, tokenizer=args.tokenizer, quantization=args
.quantization, tensor_parallel_size=args.tensor_parallel_size,
trust_remote_code=args.trust_remote_code, dtype=args.dtype,
enforce_eager=args.enforce_eager)
samplin... | null |
_swap | with torch.cuda.stream(self.cache_stream):
for i in range(self.num_layers):
src_key_cache, src_value_cache = src[i]
dst_key_cache, dst_value_cache = dst[i]
cache_ops.swap_blocks(src_key_cache, dst_key_cache, src_to_dst)
cache_ops.swap_blocks(src_value_cache, dst_value_cache, src_to_d... | def _swap(self, src: List[KVCache], dst: List[KVCache], src_to_dst: Dict[
int, int]) ->None:
with torch.cuda.stream(self.cache_stream):
for i in range(self.num_layers):
src_key_cache, src_value_cache = src[i]
dst_key_cache, dst_value_cache = dst[i]
cache_ops.swap_bloc... | null |
get_streaming_response | for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False,
delimiter=b'\x00'):
if chunk:
data = json.loads(chunk.decode('utf-8'))
output = data['text']
yield output | def get_streaming_response(response: requests.Response) ->Iterable[List[str]]:
for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False,
delimiter=b'\x00'):
if chunk:
data = json.loads(chunk.decode('utf-8'))
output = data['text']
yield output | null |
_get_graph_batch_size | if batch_size <= 2:
return batch_size
elif batch_size <= 4:
return 4
else:
return (batch_size + 7) // 8 * 8 | def _get_graph_batch_size(batch_size: int) ->int:
if batch_size <= 2:
return batch_size
elif batch_size <= 4:
return 4
else:
return (batch_size + 7) // 8 * 8 | null |
get_tensor_model_parallel_group | """Get the tensor model parallel group the caller rank belongs to."""
assert _TENSOR_MODEL_PARALLEL_GROUP is not None, 'tenosr model parallel group is not initialized'
return _TENSOR_MODEL_PARALLEL_GROUP | def get_tensor_model_parallel_group():
"""Get the tensor model parallel group the caller rank belongs to."""
assert _TENSOR_MODEL_PARALLEL_GROUP is not None, 'tenosr model parallel group is not initialized'
return _TENSOR_MODEL_PARALLEL_GROUP | Get the tensor model parallel group the caller rank belongs to. |
forward | hidden_states = self.wte(input_ids)
for i in range(len(self.h)):
layer = self.h[i]
hidden_states = layer(position_ids, hidden_states, kv_caches[i],
input_metadata)
hidden_states = self.ln_f(hidden_states)
return hidden_states | def forward(self, input_ids: torch.Tensor, position_ids: torch.Tensor,
kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor:
hidden_states = self.wte(input_ids)
for i in range(len(self.h)):
layer = self.h[i]
hidden_states = layer(position_ids, hidden_states, kv_caches[i],
... | null |
get_min_capability | """Minimum GPU capability to support the quantization method.
E.g., 70 for Volta, 75 for Turing, 80 for Ampere.
This requirement is due to the custom CUDA kernels used by the
quantization method.
"""
raise NotImplementedError | @abstractmethod
def get_min_capability(self) ->int:
"""Minimum GPU capability to support the quantization method.
E.g., 70 for Volta, 75 for Turing, 80 for Ampere.
This requirement is due to the custom CUDA kernels used by the
quantization method.
"""
raise NotImplementedError | Minimum GPU capability to support the quantization method.
E.g., 70 for Volta, 75 for Turing, 80 for Ampere.
This requirement is due to the custom CUDA kernels used by the
quantization method. |
capture | assert self.graph is None
self.model(input_ids, positions, kv_caches, input_metadata)
torch.cuda.synchronize()
self.graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(self.graph, pool=memory_pool):
hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
torch.cuda.synchronize()
self.input_buff... | def capture(self, input_ids: torch.Tensor, positions: torch.Tensor,
kv_caches: List[KVCache], input_metadata: InputMetadata, memory_pool
) ->None:
assert self.graph is None
self.model(input_ids, positions, kv_caches, input_metadata)
torch.cuda.synchronize()
self.graph = torch.cuda.CUDAGraph()
... | null |
__init__ | super().__init__()
self.gate_up_proj = MergedColumnParallelLinear(hidden_size, [
intermediate_size] * 2, bias=False, linear_method=linear_method)
self.down_proj = RowParallelLinear(intermediate_size, hidden_size, bias=
False, linear_method=linear_method)
if hidden_act != 'silu':
raise ValueError(
f'... | def __init__(self, hidden_size: int, intermediate_size: int, hidden_act:
str, linear_method: Optional[LinearMethodBase]=None):
super().__init__()
self.gate_up_proj = MergedColumnParallelLinear(hidden_size, [
intermediate_size] * 2, bias=False, linear_method=linear_method)
self.down_proj = RowPar... | null |
__init__ | self.device = device
self.block_size = block_size
self.num_blocks = num_blocks
self.free_blocks: BlockTable = []
for i in range(num_blocks):
block = PhysicalTokenBlock(device=device, block_number=i, block_size=
block_size)
self.free_blocks.append(block) | def __init__(self, device: Device, block_size: int, num_blocks: int) ->None:
self.device = device
self.block_size = block_size
self.num_blocks = num_blocks
self.free_blocks: BlockTable = []
for i in range(num_blocks):
block = PhysicalTokenBlock(device=device, block_number=i,
bloc... | null |
get_name | return 'squeezellm' | def get_name(self) ->str:
return 'squeezellm' | null |
_make_tensor_with_pad | padded_x = [_pad_to_max(x_i, max_len, pad) for x_i in x]
return torch.tensor(padded_x, dtype=dtype, device=device, pin_memory=
pin_memory and str(device) == 'cpu') | def _make_tensor_with_pad(x: List[List[int]], max_len: int, pad: int, dtype:
torch.dtype, device: Union[str, torch.device]='cuda', pin_memory: bool=
False) ->torch.Tensor:
padded_x = [_pad_to_max(x_i, max_len, pad) for x_i in x]
return torch.tensor(padded_x, dtype=dtype, device=device, pin_memory=
... | null |
sample_requests | if fixed_output_len is not None and fixed_output_len < 4:
raise ValueError('output_len too small')
with open(dataset_path) as f:
dataset = json.load(f)
dataset = [data for data in dataset if len(data['conversations']) >= 2]
dataset = [(data['conversations'][0]['value'], data['conversations'][1][
'value']) f... | def sample_requests(dataset_path: str, num_requests: int, tokenizer:
PreTrainedTokenizerBase, fixed_output_len: Optional[int]) ->List[Tuple[
str, int, int]]:
if fixed_output_len is not None and fixed_output_len < 4:
raise ValueError('output_len too small')
with open(dataset_path) as f:
d... | null |
set | self.flag = True | def set(self):
self.flag = True | null |
load_weights | stacked_params_mapping = [('qkv_proj', 'q_proj', 'q'), ('qkv_proj',
'k_proj', 'k'), ('qkv_proj', 'v_proj', 'v'), ('gate_up_proj',
'gate_proj', 0), ('gate_up_proj', 'up_proj', 1)]
params_dict = dict(self.named_parameters())
for name, loaded_weight in hf_model_weights_iterator(model_name_or_path,
cache_dir, l... | def load_weights(self, model_name_or_path: str, cache_dir: Optional[str]=
None, load_format: str='auto', revision: Optional[str]=None):
stacked_params_mapping = [('qkv_proj', 'q_proj', 'q'), ('qkv_proj',
'k_proj', 'k'), ('qkv_proj', 'v_proj', 'v'), ('gate_up_proj',
'gate_proj', 0), ('gate_up_pro... | null |
forward | layernorm_output = self.input_layernorm(hidden_states)
attention_output = self.self_attention(hidden_states=layernorm_output,
position_ids=position_ids, kv_cache=kv_cache, input_metadata=input_metadata
)
if self.apply_residual_connection_post_layernorm:
residual = layernorm_output
else:
residual = hidde... | def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor,
kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor:
layernorm_output = self.input_layernorm(hidden_states)
attention_output = self.self_attention(hidden_states=layernorm_output,
position_ids=position_ids, kv_cac... | null |
_verify_cuda_graph | if self.max_context_len_to_capture is None:
self.max_context_len_to_capture = self.max_model_len
self.max_context_len_to_capture = min(self.max_context_len_to_capture, self
.max_model_len) | def _verify_cuda_graph(self) ->None:
if self.max_context_len_to_capture is None:
self.max_context_len_to_capture = self.max_model_len
self.max_context_len_to_capture = min(self.max_context_len_to_capture,
self.max_model_len) | null |
forward | hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
return hidden_states | def forward(self, input_ids: torch.Tensor, positions: torch.Tensor,
kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor:
hidden_states = self.model(input_ids, positions, kv_caches, input_metadata)
return hidden_states | null |
__init__ | self.request_id = request_id
self.prompt = prompt
self.prompt_token_ids = prompt_token_ids
self.prompt_logprobs = prompt_logprobs
self.outputs = outputs
self.finished = finished | def __init__(self, request_id: str, prompt: str, prompt_token_ids: List[int
], prompt_logprobs: Optional[PromptLogprobs], outputs: List[
CompletionOutput], finished: bool) ->None:
self.request_id = request_id
self.prompt = prompt
self.prompt_token_ids = prompt_token_ids
self.prompt_logprobs = pr... | null |
forward | if residual is None:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
else:
hidden_states, residual = self.input_layernorm(hidden_states, residual)
hidden_states = self.self_attn(positions=positions, hidden_states=
hidden_states, kv_cache=kv_cache, input_metadata=input_metada... | def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor,
kv_cache: KVCache, input_metadata: InputMetadata, residual: Optional[
torch.Tensor]) ->Tuple[torch.Tensor, torch.Tensor]:
if residual is None:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
... | null |
__init__ | super().__init__()
assert config.embedding_fraction == 1.0
assert config.norm_type == 'low_precision_layernorm'
self.wte = VocabParallelEmbedding(config.vocab_size, config.d_model)
self.blocks = nn.ModuleList([MPTBlock(config, linear_method) for _ in range
(config.n_layers)])
self.norm_f = nn.LayerNorm(config.d_mod... | def __init__(self, config: MPTConfig, linear_method: Optional[
LinearMethodBase]=None):
super().__init__()
assert config.embedding_fraction == 1.0
assert config.norm_type == 'low_precision_layernorm'
self.wte = VocabParallelEmbedding(config.vocab_size, config.d_model)
self.blocks = nn.ModuleList... | null |
test_models | hf_model = hf_runner(model, dtype=dtype)
hf_outputs = hf_model.generate_greedy(example_long_prompts, max_tokens)
del hf_model
vllm_model = vllm_runner(model, dtype=dtype)
vllm_outputs = vllm_model.generate_greedy(example_long_prompts, max_tokens)
del vllm_model
for i in range(len(example_long_prompts)):
hf_output_i... | @pytest.mark.parametrize('model', MODELS)
@pytest.mark.parametrize('dtype', ['bfloat16'])
@pytest.mark.parametrize('max_tokens', [128])
def test_models(hf_runner, vllm_runner, example_long_prompts, model: str,
dtype: str, max_tokens: int) ->None:
hf_model = hf_runner(model, dtype=dtype)
hf_outputs = hf_mode... | null |
create_logprobs | """Create OpenAI-style logprobs."""
logprobs = LogProbs()
last_token_len = 0
if num_output_top_logprobs:
logprobs.top_logprobs = []
for i, token_id in enumerate(token_ids):
step_top_logprobs = top_logprobs[i]
if step_top_logprobs is not None:
token_logprob = step_top_logprobs[token_id]
else:
... | def create_logprobs(token_ids: List[int], top_logprobs: Optional[List[
Optional[Dict[int, float]]]]=None, num_output_top_logprobs: Optional[
int]=None, initial_text_offset: int=0) ->LogProbs:
"""Create OpenAI-style logprobs."""
logprobs = LogProbs()
last_token_len = 0
if num_output_top_logprobs:... | Create OpenAI-style logprobs. |
get_pipeline_model_parallel_next_rank | """Return the global rank that follows the caller in the pipeline"""
assert _PIPELINE_GLOBAL_RANKS is not None, 'Pipeline parallel group is not initialized'
rank_in_pipeline = get_pipeline_model_parallel_rank()
world_size = get_pipeline_model_parallel_world_size()
return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline + 1) % ... | def get_pipeline_model_parallel_next_rank():
"""Return the global rank that follows the caller in the pipeline"""
assert _PIPELINE_GLOBAL_RANKS is not None, 'Pipeline parallel group is not initialized'
rank_in_pipeline = get_pipeline_model_parallel_rank()
world_size = get_pipeline_model_parallel_world_s... | Return the global rank that follows the caller in the pipeline |
__init__ | super().__init__()
self.config = config
self.linear_method = linear_method
self.embd = PhiEmbedding(config)
self.h = nn.ModuleList([PhiLayer(config, linear_method) for _ in range(
config.num_hidden_layers)]) | def __init__(self, config: PretrainedConfig, linear_method: Optional[
LinearMethodBase]=None):
super().__init__()
self.config = config
self.linear_method = linear_method
self.embd = PhiEmbedding(config)
self.h = nn.ModuleList([PhiLayer(config, linear_method) for _ in range(
config.num_hi... | null |
hf_model_weights_iterator | hf_folder, hf_weights_files, use_safetensors = prepare_hf_model_weights(
model_name_or_path, cache_dir=cache_dir, load_format=load_format,
fall_back_to_pt=fall_back_to_pt, revision=revision)
if load_format == 'npcache':
assert use_safetensors is False
np_folder = os.path.join(hf_folder, 'np')
os.mak... | def hf_model_weights_iterator(model_name_or_path: str, cache_dir: Optional[
str]=None, load_format: str='auto', revision: Optional[str]=None,
fall_back_to_pt: Optional[bool]=True) ->Iterator[Tuple[str, torch.Tensor]]:
hf_folder, hf_weights_files, use_safetensors = prepare_hf_model_weights(
model_nam... | null |
sample | next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | def sample(self, hidden_states: torch.Tensor, sampling_metadata:
SamplingMetadata) ->Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | null |
create_error_response | return JSONResponse(ErrorResponse(message=message, type=
'invalid_request_error').dict(), status_code=status_code.value) | def create_error_response(status_code: HTTPStatus, message: str
) ->JSONResponse:
return JSONResponse(ErrorResponse(message=message, type=
'invalid_request_error').dict(), status_code=status_code.value) | null |
forward | hidden_states, _ = self.fc_in(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states, _ = self.fc_out(hidden_states)
return hidden_states | def forward(self, hidden_states: torch.Tensor) ->torch.Tensor:
hidden_states, _ = self.fc_in(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states, _ = self.fc_out(hidden_states)
return hidden_states | null |
can_swap_out | blocks = self._get_physical_blocks(seq_group)
return len(blocks) <= self.cpu_allocator.get_num_free_blocks() | def can_swap_out(self, seq_group: SequenceGroup) ->bool:
blocks = self._get_physical_blocks(seq_group)
return len(blocks) <= self.cpu_allocator.get_num_free_blocks() | null |
forward | del position_ids
qkv, _ = self.Wqkv(hidden_states)
if self.clip_qkv is not None:
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
if self.qk_ln:
q = self.q_ln(q)
k = self.k_ln(k)
k_cache, v_cache = kv_cache
attn_output = self.attn(q, k,... | def forward(self, position_ids: torch.Tensor, hidden_states: torch.Tensor,
kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor:
del position_ids
qkv, _ = self.Wqkv(hidden_states)
if self.clip_qkv is not None:
qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
q, k, v = qkv.split(... | null |
_process_sequence_group_outputs | prompt_logprobs = outputs.prompt_logprobs
if prompt_logprobs is not None:
seq_group.prompt_logprobs = prompt_logprobs
samples = outputs.samples
parent_seqs = seq_group.get_seqs(status=SequenceStatus.RUNNING)
existing_finished_seqs = seq_group.get_finished_seqs()
parent_child_dict = {parent_seq.seq_id: [] for parent... | def _process_sequence_group_outputs(self, seq_group: SequenceGroup, outputs:
SequenceGroupOutput) ->None:
prompt_logprobs = outputs.prompt_logprobs
if prompt_logprobs is not None:
seq_group.prompt_logprobs = prompt_logprobs
samples = outputs.samples
parent_seqs = seq_group.get_seqs(status=Se... | null |
destroy_model_parallel | """Set the groups to none."""
global _TENSOR_MODEL_PARALLEL_GROUP
_TENSOR_MODEL_PARALLEL_GROUP = None
global _PIPELINE_MODEL_PARALLEL_GROUP
_PIPELINE_MODEL_PARALLEL_GROUP = None
global _PIPELINE_GLOBAL_RANKS
_PIPELINE_GLOBAL_RANKS = None | def destroy_model_parallel():
"""Set the groups to none."""
global _TENSOR_MODEL_PARALLEL_GROUP
_TENSOR_MODEL_PARALLEL_GROUP = None
global _PIPELINE_MODEL_PARALLEL_GROUP
_PIPELINE_MODEL_PARALLEL_GROUP = None
global _PIPELINE_GLOBAL_RANKS
_PIPELINE_GLOBAL_RANKS = None | Set the groups to none. |
generate | req_outputs = self.model.generate(prompts, sampling_params=sampling_params)
outputs = []
for req_output in req_outputs:
prompt_str = req_output.prompt
prompt_ids = req_output.prompt_token_ids
req_sample_output_ids = []
req_sample_output_strs = []
for sample in req_output.outputs:
output_str ... | def generate(self, prompts: List[str], sampling_params: SamplingParams) ->List[
Tuple[List[int], str]]:
req_outputs = self.model.generate(prompts, sampling_params=sampling_params)
outputs = []
for req_output in req_outputs:
prompt_str = req_output.prompt
prompt_ids = req_output.prompt_to... | null |
_preempt | if preemption_mode is None:
if seq_group.get_max_num_running_seqs() == 1:
preemption_mode = PreemptionMode.RECOMPUTE
else:
preemption_mode = PreemptionMode.SWAP
if preemption_mode == PreemptionMode.RECOMPUTE:
self._preempt_by_recompute(seq_group)
elif preemption_mode == PreemptionMode.SWAP:
... | def _preempt(self, seq_group: SequenceGroup, blocks_to_swap_out: Dict[int,
int], preemption_mode: Optional[PreemptionMode]=None) ->None:
if preemption_mode is None:
if seq_group.get_max_num_running_seqs() == 1:
preemption_mode = PreemptionMode.RECOMPUTE
else:
preemption_m... | null |
get_response | data = json.loads(response.content)
output = data['text']
return output | def get_response(response: requests.Response) ->List[str]:
data = json.loads(response.content)
output = data['text']
return output | null |
__repr__ | return f'RequestOutput(request_id={self.request_id}, prompt={self.prompt!r}, prompt_token_ids={self.prompt_token_ids}, prompt_logprobs={self.prompt_logprobs}, outputs={self.outputs}, finished={self.finished})' | def __repr__(self) ->str:
return (
f'RequestOutput(request_id={self.request_id}, prompt={self.prompt!r}, prompt_token_ids={self.prompt_token_ids}, prompt_logprobs={self.prompt_logprobs}, outputs={self.outputs}, finished={self.finished})'
) | null |
forward | gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
x, _ = self.down_proj(x)
return x | def forward(self, x):
gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
x, _ = self.down_proj(x)
return x | null |
__init__ | self.scheduled_seq_groups = scheduled_seq_groups
self.prompt_run = prompt_run
self.num_batched_tokens = num_batched_tokens
self.blocks_to_swap_in = blocks_to_swap_in
self.blocks_to_swap_out = blocks_to_swap_out
self.blocks_to_copy = blocks_to_copy
assert not (blocks_to_swap_in and blocks_to_swap_out)
self.ignored_seq_g... | def __init__(self, scheduled_seq_groups: List[SequenceGroup], prompt_run:
bool, num_batched_tokens: int, blocks_to_swap_in: Dict[int, int],
blocks_to_swap_out: Dict[int, int], blocks_to_copy: Dict[int, List[int]
], ignored_seq_groups: List[SequenceGroup]) ->None:
self.scheduled_seq_groups = scheduled_se... | null |
get_num_kv_heads | """Returns the number of KV heads per GPU."""
total_num_kv_heads = self.get_total_num_kv_heads()
return max(1, total_num_kv_heads // parallel_config.tensor_parallel_size) | def get_num_kv_heads(self, parallel_config: 'ParallelConfig') ->int:
"""Returns the number of KV heads per GPU."""
total_num_kv_heads = self.get_total_num_kv_heads()
return max(1, total_num_kv_heads // parallel_config.tensor_parallel_size) | Returns the number of KV heads per GPU. |
__init__ | super().__init__()
self.hidden_size = hidden_size
tensor_model_parallel_world_size = get_tensor_model_parallel_world_size()
self.total_num_heads = num_heads
assert self.total_num_heads % tensor_model_parallel_world_size == 0
self.num_heads = self.total_num_heads // tensor_model_parallel_world_size
self.head_dim = hidde... | def __init__(self, hidden_size: int, num_heads: int, position_embedding:
str, rope_theta: float=10000, max_position_embeddings: int=8192,
linear_method: Optional[LinearMethodBase]=None):
super().__init__()
self.hidden_size = hidden_size
tensor_model_parallel_world_size = get_tensor_model_parallel_wo... | null |
__init__ | super().__init__()
self.config: ChatGLMConfig = config
self.linear_method = linear_method
self.transformer = ChatGLMModel(config, linear_method)
self.lm_head_weight = self.transformer.output_layer.weight
self.sampler = Sampler(config.padded_vocab_size) | def __init__(self, config: ChatGLMConfig, linear_method: Optional[
LinearMethodBase]=None):
super().__init__()
self.config: ChatGLMConfig = config
self.linear_method = linear_method
self.transformer = ChatGLMModel(config, linear_method)
self.lm_head_weight = self.transformer.output_layer.weight
... | null |
test_load_chat_template | template = '../../examples/template_chatml.jinja'
mock_args = Namespace(chat_template=template)
tokenizer = MockTokenizer()
load_chat_template(mock_args, tokenizer)
template_content = tokenizer.chat_template
assert template_content is not None
assert template_content == """{% for message in messages %}{{'<|im_start|>' ... | def test_load_chat_template():
template = '../../examples/template_chatml.jinja'
mock_args = Namespace(chat_template=template)
tokenizer = MockTokenizer()
load_chat_template(mock_args, tokenizer)
template_content = tokenizer.chat_template
assert template_content is not None
assert template_c... | null |
sample | next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | def sample(self, hidden_states: torch.Tensor, sampling_metadata:
SamplingMetadata) ->Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | null |
forward | gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
x, _ = self.down_proj(x)
return x | def forward(self, x):
gate_up, _ = self.gate_up_proj(x)
x = self.act_fn(gate_up)
x, _ = self.down_proj(x)
return x | null |
get_key_block_shape | element_size = torch.tensor([], dtype=self.dtype).element_size()
x = 16 // element_size
return self.num_heads, self.head_size // x, self.block_size, x | def get_key_block_shape(self) ->Tuple[int, int, int, int]:
element_size = torch.tensor([], dtype=self.dtype).element_size()
x = 16 // element_size
return self.num_heads, self.head_size // x, self.block_size, x | null |
sample | next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | def sample(self, hidden_states: torch.Tensor, sampling_metadata:
SamplingMetadata) ->Optional[SamplerOutput]:
next_tokens = self.sampler(self.lm_head.weight, hidden_states,
sampling_metadata)
return next_tokens | null |
__init__ | logger.info(
f'Initializing an LLM engine with config: model={model_config.model!r}, tokenizer={model_config.tokenizer!r}, tokenizer_mode={model_config.tokenizer_mode}, revision={model_config.revision}, tokenizer_revision={model_config.tokenizer_revision}, trust_remote_code={model_config.trust_remote_code}, dtype={... | def __init__(self, model_config: ModelConfig, cache_config: CacheConfig,
parallel_config: ParallelConfig, scheduler_config: SchedulerConfig,
placement_group: Optional['PlacementGroup'], log_stats: bool) ->None:
logger.info(
f'Initializing an LLM engine with config: model={model_config.model!r}, toke... | null |
forward | qkv, _ = self.query_key_value(hidden_states)
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
q, k = self.rotary_emb(position_ids, q, k)
key_cache, value_cache = kv_cache
context_layer = self.attn(q, k, v, key_cache, value_cache, input_metadata)
attn_output, _ = self.dense(context_layer)
return at... | def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor,
kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor:
qkv, _ = self.query_key_value(hidden_states)
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
q, k = self.rotary_emb(position_ids, q, k)
... | null |
_get_bin_counts_and_mask | bin_counts = torch.zeros((num_seqs, vocab_size + 1), dtype=torch.long,
device=tokens.device)
bin_counts.scatter_add_(1, tokens, torch.ones_like(tokens))
bin_counts = bin_counts[:, :vocab_size]
mask = bin_counts > 0
return bin_counts, mask | def _get_bin_counts_and_mask(tokens: torch.Tensor, vocab_size: int,
num_seqs: int) ->Tuple[torch.Tensor, torch.Tensor]:
bin_counts = torch.zeros((num_seqs, vocab_size + 1), dtype=torch.long,
device=tokens.device)
bin_counts.scatter_add_(1, tokens, torch.ones_like(tokens))
bin_counts = bin_counts... | null |
__init__ | super().__init__()
self.config = config
assert not config.add_cross_attention
self.embed_dim = config.hidden_size
self.wte = VocabParallelEmbedding(config.vocab_size, self.embed_dim)
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
self.h = nn.ModuleList([GPTBigCodeBlock(config, linear_method) fo... | def __init__(self, config: GPTBigCodeConfig, linear_method: Optional[
LinearMethodBase]=None):
super().__init__()
self.config = config
assert not config.add_cross_attention
self.embed_dim = config.hidden_size
self.wte = VocabParallelEmbedding(config.vocab_size, self.embed_dim)
self.wpe = nn.... | null |
forward | if residual is None:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
else:
hidden_states, residual = self.input_layernorm(hidden_states, residual)
hidden_states = self.self_attn(positions=positions, hidden_states=
hidden_states, kv_cache=kv_cache, input_metadata=input_metada... | def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor,
kv_cache: KVCache, input_metadata: InputMetadata, residual: Optional[
torch.Tensor]) ->Tuple[torch.Tensor, torch.Tensor]:
if residual is None:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
... | null |
get_block_table | block_table = self.block_tables[seq.seq_id]
return [block.block_number for block in block_table] | def get_block_table(self, seq: Sequence) ->List[int]:
block_table = self.block_tables[seq.seq_id]
return [block.block_number for block in block_table] | null |
__init__ | self.counter = start | def __init__(self, start: int=0) ->None:
self.counter = start | null |
__post_init__ | if self.tokenizer is None:
self.tokenizer = self.model | def __post_init__(self):
if self.tokenizer is None:
self.tokenizer = self.model | null |
get_linear_method | return AWQLinearMethod(self) | def get_linear_method(self) ->'AWQLinearMethod':
return AWQLinearMethod(self) | null |
get_pipeline_model_parallel_last_rank | """Return the global rank of the last process in the pipeline for the
current tensor parallel group"""
assert _PIPELINE_GLOBAL_RANKS is not None, 'Pipeline parallel group is not initialized'
last_rank_local = get_pipeline_model_parallel_world_size() - 1
return _PIPELINE_GLOBAL_RANKS[last_rank_local] | def get_pipeline_model_parallel_last_rank():
"""Return the global rank of the last process in the pipeline for the
current tensor parallel group"""
assert _PIPELINE_GLOBAL_RANKS is not None, 'Pipeline parallel group is not initialized'
last_rank_local = get_pipeline_model_parallel_world_size() - 1
r... | Return the global rank of the last process in the pipeline for the
current tensor parallel group |
num_seqs | return len(self.get_seqs(status)) | def num_seqs(self, status: Optional[SequenceStatus]=None) ->int:
return len(self.get_seqs(status)) | null |
get_tokenizer | """Gets a tokenizer for the given model name via Huggingface."""
if tokenizer_mode == 'slow':
if kwargs.get('use_fast', False):
raise ValueError(
'Cannot use the fast tokenizer in slow tokenizer mode.')
kwargs['use_fast'] = False
try:
tokenizer = AutoTokenizer.from_pretrained(tokenizer_n... | def get_tokenizer(tokenizer_name: str, *args, tokenizer_mode: str='auto',
trust_remote_code: bool=False, tokenizer_revision: Optional[str]=None,
**kwargs) ->Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
"""Gets a tokenizer for the given model name via Huggingface."""
if tokenizer_mode == 'slow':
... | Gets a tokenizer for the given model name via Huggingface. |
__init__ | self.weight_bits = weight_bits
self.group_size = group_size
self.zero_point = zero_point
if self.weight_bits != 4:
raise ValueError(
f'Currently, only 4-bit weight quantization is supported for AWQ, but got {self.weight_bits} bits.'
)
self.pack_factor = 32 // self.weight_bits | def __init__(self, weight_bits: int, group_size: int, zero_point: bool) ->None:
self.weight_bits = weight_bits
self.group_size = group_size
self.zero_point = zero_point
if self.weight_bits != 4:
raise ValueError(
f'Currently, only 4-bit weight quantization is supported for AWQ, but g... | null |
apply_weights | qweight = weights['qweight']
lookup_table = weights['lookup_table']
out_shape = x.shape[:-1] + (qweight.shape[-1],)
reshaped_x = x.reshape(-1, x.shape[-1])
if is_hip():
out_f = torch.zeros(out_shape, device='cuda', dtype=torch.float)
ops.squeezellm_gemm(reshaped_x, qweight, out_f, lookup_table)
out = out_f.... | def apply_weights(self, weights: Dict[str, Any], x: torch.Tensor, bias:
Optional[torch.Tensor]=None) ->torch.Tensor:
qweight = weights['qweight']
lookup_table = weights['lookup_table']
out_shape = x.shape[:-1] + (qweight.shape[-1],)
reshaped_x = x.reshape(-1, x.shape[-1])
if is_hip():
ou... | null |
get_output_len | return self.data.get_output_len() | def get_output_len(self) ->int:
return self.data.get_output_len() | null |
__init__ | super().__init__()
self.hidden_size = config.hidden_size
rope_theta = getattr(config, 'rope_theta', 10000)
rope_scaling = getattr(config, 'rope_scaling', None)
max_position_embeddings = getattr(config, 'max_position_embeddings', 8192)
self.self_attn = YiAttention(hidden_size=self.hidden_size, num_heads=config
.num_... | def __init__(self, config: YiConfig, linear_method: Optional[
LinearMethodBase]=None) ->None:
super().__init__()
self.hidden_size = config.hidden_size
rope_theta = getattr(config, 'rope_theta', 10000)
rope_scaling = getattr(config, 'rope_scaling', None)
max_position_embeddings = getattr(config, ... | null |
head_dim | return self.hidden_size // self.n_head | @property
def head_dim(self):
return self.hidden_size // self.n_head | null |
_append_slot | for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
ret = self.block_manager.append_slot(seq)
if ret is not None:
src_block, dst_block = ret
if src_block in blocks_to_copy:
blocks_to_copy[src_block].append(dst_block)
else:
blocks_to_copy[src_block] = [ds... | def _append_slot(self, seq_group: SequenceGroup, blocks_to_copy: Dict[int,
List[int]]) ->None:
for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
ret = self.block_manager.append_slot(seq)
if ret is not None:
src_block, dst_block = ret
if src_block in blocks_to_... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.