method_name
stringlengths
3
45
method_body
stringlengths
9
6.25k
full_code
stringlengths
35
7.02k
docstring
stringlengths
18
4.7k
start_background_loop
"""Start the background loop.""" if self.is_running: raise RuntimeError('Background loop is already running.') self._request_tracker.init_event() self._background_loop_unshielded = asyncio.get_event_loop().create_task(self .run_engine_loop()) self._background_loop_unshielded.add_done_callback(partial( _rais...
def start_background_loop(self) ->None: """Start the background loop.""" if self.is_running: raise RuntimeError('Background loop is already running.') self._request_tracker.init_event() self._background_loop_unshielded = asyncio.get_event_loop().create_task( self.run_engine_loop()) s...
Start the background loop.
forward
x = self.norm_1(hidden_states) x = self.attn(position_ids=position_ids, hidden_states=x, kv_cache=kv_cache, input_metadata=input_metadata) hidden_states = hidden_states + x x = self.norm_2(hidden_states) x = self.ffn(x) hidden_states = hidden_states + x return hidden_states
def forward(self, position_ids: torch.Tensor, hidden_states: torch.Tensor, kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor: x = self.norm_1(hidden_states) x = self.attn(position_ids=position_ids, hidden_states=x, kv_cache= kv_cache, input_metadata=input_metadata) hidden_states =...
null
__eq__
if not isinstance(other, SequenceGroupOutput): raise NotImplementedError() return self.samples == other.samples and self.prompt_logprobs == other.prompt_logprobs
def __eq__(self, other: object) ->bool: if not isinstance(other, SequenceGroupOutput): raise NotImplementedError() return (self.samples == other.samples and self.prompt_logprobs == other .prompt_logprobs)
null
test_sampler_all_greedy
set_random_seed(seed) batch_size = random.randint(1, 256) input_tensor, fake_logits, sampler, model_runner = _prepare_test(batch_size) seq_group_metadata_list = [] prompt_lens = [] for i in range(batch_size): seq_group_metadata_list.append(SequenceGroupMetadata(request_id= f'test_{i}', is_prompt=True, seq_d...
@pytest.mark.parametrize('seed', RANDOM_SEEDS) def test_sampler_all_greedy(seed: int): set_random_seed(seed) batch_size = random.randint(1, 256) input_tensor, fake_logits, sampler, model_runner = _prepare_test(batch_size ) seq_group_metadata_list = [] prompt_lens = [] for i in range(batc...
null
get_pipeline_model_parallel_world_size
"""Return world size for the pipeline model parallel group.""" return torch.distributed.get_world_size(group= get_pipeline_model_parallel_group())
def get_pipeline_model_parallel_world_size(): """Return world size for the pipeline model parallel group.""" return torch.distributed.get_world_size(group= get_pipeline_model_parallel_group())
Return world size for the pipeline model parallel group.
_yarn_find_correction_dim
return dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi) ) / (2 * math.log(base))
def _yarn_find_correction_dim(num_rotations: int, dim: int, base: float= 10000, max_position_embeddings: int=2048) ->float: return dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi)) / (2 * math.log(base))
null
forward
hidden_states = self.transformer(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.transformer(input_ids, positions, kv_caches, input_metadata) return hidden_states
null
__init__
super().__init__() self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads self.sliding_window = sliding_window if alibi_slopes is not None: alibi_slopes = torch.tensor(alibi_slopes, dtype=torch.float32) self.register_bu...
def __init__(self, num_heads: int, head_size: int, scale: float, num_kv_heads: Optional[int]=None, alibi_slopes: Optional[List[float]]= None, sliding_window: Optional[int]=None) ->None: super().__init__() self.num_heads = num_heads self.head_size = head_size self.scale = float(scale) self.nu...
null
num_unfinished_seqs
return len(self.get_unfinished_seqs())
def num_unfinished_seqs(self) ->int: return len(self.get_unfinished_seqs())
null
ref_single_query_cached_kv_attention
num_query_heads = query.shape[1] num_kv_heads = value_cache.shape[1] head_size = value_cache.shape[2] block_size = value_cache.shape[3] num_seqs = query.shape[0] block_tables = block_tables.cpu().tolist() context_lens = context_lens.cpu().tolist() for i in range(num_seqs): q = query[i].unsqueeze(0) block_table ...
def ref_single_query_cached_kv_attention(output: torch.Tensor, query: torch .Tensor, num_queries_per_kv: int, key_cache: torch.Tensor, value_cache: torch.Tensor, block_tables: torch.Tensor, context_lens: torch.Tensor, scale: float, alibi_slopes: Optional[torch.Tensor]) ->None: num_query_heads = query.sh...
null
forward
hidden_states = self.transformer(input_ids, positions, kv_caches, input_metadata) return hidden_states
def forward(self, input_ids: torch.LongTensor, positions: torch.Tensor, kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor: hidden_states = self.transformer(input_ids, positions, kv_caches, input_metadata) return hidden_states
null
get_max_shared_memory_bytes
"""Returns the maximum shared memory per thread block in bytes.""" cudaDevAttrMaxSharedMemoryPerBlockOptin = 97 if not is_hip() else 74 max_shared_mem = cuda_utils.get_device_attribute( cudaDevAttrMaxSharedMemoryPerBlockOptin, gpu) return int(max_shared_mem)
def get_max_shared_memory_bytes(gpu: int=0) ->int: """Returns the maximum shared memory per thread block in bytes.""" cudaDevAttrMaxSharedMemoryPerBlockOptin = 97 if not is_hip() else 74 max_shared_mem = cuda_utils.get_device_attribute( cudaDevAttrMaxSharedMemoryPerBlockOptin, gpu) return int(ma...
Returns the maximum shared memory per thread block in bytes.
load_model
self.model_runner.load_model()
def load_model(self): self.model_runner.load_model()
null
__init__
super().__init__() self.config = config self.linear_method = linear_method self.gpt_neox = GPTNeoXModel(config, linear_method) self.embed_out = ParallelLMHead(config.vocab_size, config.hidden_size) self.sampler = Sampler(config.vocab_size)
def __init__(self, config, linear_method: Optional[LinearMethodBase]=None): super().__init__() self.config = config self.linear_method = linear_method self.gpt_neox = GPTNeoXModel(config, linear_method) self.embed_out = ParallelLMHead(config.vocab_size, config.hidden_size) self.sampler = Sampler...
null
pick_ith
logits[len(token_ids)] = float('inf') return logits
def pick_ith(token_ids, logits): logits[len(token_ids)] = float('inf') return logits
null
forward
hidden_states, _ = self.c_fc(hidden_states) hidden_states = self.act(hidden_states) hidden_states, _ = self.c_proj(hidden_states) return hidden_states
def forward(self, hidden_states: torch.Tensor) ->torch.Tensor: hidden_states, _ = self.c_fc(hidden_states) hidden_states = self.act(hidden_states) hidden_states, _ = self.c_proj(hidden_states) return hidden_states
null
_multinomial
if num_samples > 1: probs = probs[:, None, :].expand(probs.shape[0], num_samples, probs. shape[1]).contiguous().view(-1, probs.shape[1]) q = torch.empty_like(probs).exponential_(1) return probs.div_(q).argmax(dim=1).view(-1, num_samples)
def _multinomial(probs: torch.Tensor, num_samples: int): if num_samples > 1: probs = probs[:, None, :].expand(probs.shape[0], num_samples, probs .shape[1]).contiguous().view(-1, probs.shape[1]) q = torch.empty_like(probs).exponential_(1) return probs.div_(q).argmax(dim=1).view(-1, num_sa...
null
__init__
if config.hidden_size == 4096: super().__init__(config, 'ROPE', linear_method) else: super().__init__(config, 'ALIBI', linear_method)
def __init__(self, config, linear_method: Optional[LinearMethodBase]=None): if config.hidden_size == 4096: super().__init__(config, 'ROPE', linear_method) else: super().__init__(config, 'ALIBI', linear_method)
null
split_tensor_along_last_dim
""" 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...
def split_tensor_along_last_dim(tensor: torch.Tensor, num_partitions: int, contiguous_split_chunks: bool=False) ->Sequence[torch.Tensor]: """ Split a tensor along its last dimension. Arguments: tensor: input tensor. num_partitions: number of partitions to split the tensor ...
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
_tokenize
"""Returns a tokenized string.""" return self.sp_model.encode(text, out_type=str)
def _tokenize(self, text): """Returns a tokenized string.""" return self.sp_model.encode(text, out_type=str)
Returns a tokenized string.
weight_loader
tp_rank = get_tensor_model_parallel_rank() output_dim = getattr(param, 'output_dim', None) param_data = param.data if output_dim is not None: shard_size = param_data.shape[output_dim] start_idx = tp_rank * shard_size loaded_weight = loaded_weight.narrow(output_dim, start_idx, shard_size) assert param_data.s...
def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor): tp_rank = get_tensor_model_parallel_rank() output_dim = getattr(param, 'output_dim', None) param_data = param.data if output_dim is not None: shard_size = param_data.shape[output_dim] start_idx = tp_rank * shard_size...
null
is_empty
return self.num_tokens == 0
def is_empty(self) ->bool: return self.num_tokens == 0
null
get_new_and_finished_requests
"""Get the new requests and finished requests to be sent to the engine.""" new_requests: List[Dict] = [] finished_requests: Set[str] = set() while not self._finished_requests.empty(): request_id = self._finished_requests.get_nowait() finished_requests.add(request_id) self._request_streams.pop(reques...
def get_new_and_finished_requests(self) ->Tuple[List[Dict], Set[str]]: """Get the new requests and finished requests to be sent to the engine.""" new_requests: List[Dict] = [] finished_requests: Set[str] = set() while not self._finished_requests.empty(): request_id = self._finished_reque...
Get the new requests and finished requests to be sent to the engine.
__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 = AquilaAttention(hidden_size=self.hidden_size, num_heads= config....
def __init__(self, config: AquilaConfig, linear_method: Optional[ LinearMethodBase]=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, 'ma...
null
forward
hidden_states = self.embed_tokens(input_ids) residual = None for i in range(len(self.layers)): layer = self.layers[i] hidden_states, residual = layer(positions, hidden_states, kv_caches[i], input_metadata, residual) hidden_states, _ = self.norm(hidden_states, residual) 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.embed_tokens(input_ids) residual = None for i in range(len(self.layers)): layer = self.layers[i] hidden_states, residual = lay...
null
__init__
super().__init__() self.hidden_size = config.hidden_size rope_theta = getattr(config, 'rope_theta', 10000) max_position_embeddings = getattr(config, 'max_position_embeddings', 8192) self.self_attn = BaiChuanAttention(hidden_size=self.hidden_size, num_heads= config.num_attention_heads, position_embedding=position_em...
def __init__(self, config: BaiChuanConfig, position_embedding: str, linear_method: Optional[LinearMethodBase]=None): super().__init__() self.hidden_size = config.hidden_size rope_theta = getattr(config, 'rope_theta', 10000) max_position_embeddings = getattr(config, 'max_position_embeddings', 8192) ...
null
__init__
if max_num_batched_tokens is not None: self.max_num_batched_tokens = max_num_batched_tokens else: self.max_num_batched_tokens = max(max_model_len, 2048) self.max_num_seqs = max_num_seqs self.max_model_len = max_model_len self.max_paddings = max_paddings self._verify_args()
def __init__(self, max_num_batched_tokens: Optional[int], max_num_seqs: int, max_model_len: int, max_paddings: int) ->None: if max_num_batched_tokens is not None: self.max_num_batched_tokens = max_num_batched_tokens else: self.max_num_batched_tokens = max(max_model_len, 2048) self.max_nu...
null
capture_model
assert not self.model_config.enforce_eager logger.info( "Capturing the model for CUDA graphs. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or use '--enforce-eager' in the CLI." ) logger.info( 'CUDA graphs can take additional 1~...
@torch.inference_mode() def capture_model(self, kv_caches: List[KVCache]) ->None: assert not self.model_config.enforce_eager logger.info( "Capturing the model for CUDA graphs. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or...
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__
super().__init__() self.config = config self.linear_method = linear_method self.transformer = GPT2Model(config, linear_method) self.lm_head_weight = self.transformer.wte.weight self.sampler = Sampler(config.vocab_size)
def __init__(self, config: GPT2Config, linear_method: Optional[ LinearMethodBase]=None): super().__init__() self.config = config self.linear_method = linear_method self.transformer = GPT2Model(config, linear_method) self.lm_head_weight = self.transformer.wte.weight self.sampler = Sampler(con...
null
forward
attn_input = self.input_layernorm(hidden_states) attn_output = self.attention(position_ids=position_ids, hidden_states= attn_input, kv_cache=kv_cache, input_metadata=input_metadata) if self.use_parallel_residual: mlp_input = self.post_attention_layernorm(hidden_states) mlp_output = self.mlp(mlp_input) h...
def forward(self, position_ids: torch.Tensor, hidden_states: torch.Tensor, kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor: attn_input = self.input_layernorm(hidden_states) attn_output = self.attention(position_ids=position_ids, hidden_states= attn_input, kv_cache=kv_cache, input_me...
null