method_name
stringlengths
3
45
method_body
stringlengths
9
6.25k
full_code
stringlengths
35
7.02k
docstring
stringlengths
18
4.7k
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_workers_ray
if self.parallel_config.tensor_parallel_size == 1: num_gpus = self.cache_config.gpu_memory_utilization else: num_gpus = 1 self.driver_dummy_worker: RayWorkerVllm = None self.workers: List[RayWorkerVllm] = [] driver_ip = get_ip() for bundle_id, bundle in enumerate(placement_group.bundle_specs): if not bundle...
def _init_workers_ray(self, placement_group: 'PlacementGroup', ** ray_remote_kwargs): if self.parallel_config.tensor_parallel_size == 1: num_gpus = self.cache_config.gpu_memory_utilization else: num_gpus = 1 self.driver_dummy_worker: RayWorkerVllm = None self.workers: List[RayWorkerV...
null
_check_if_gpu_supports_dtype
if torch_dtype == torch.bfloat16: compute_capability = torch.cuda.get_device_capability() if compute_capability[0] < 8: gpu_name = torch.cuda.get_device_name() raise ValueError( f'Bfloat16 is only supported on GPUs with compute capability of at least 8.0. Your {gpu_name} GPU has comp...
def _check_if_gpu_supports_dtype(torch_dtype: torch.dtype): if torch_dtype == torch.bfloat16: compute_capability = torch.cuda.get_device_capability() if compute_capability[0] < 8: gpu_name = torch.cuda.get_device_name() raise ValueError( f'Bfloat16 is only sup...
null
initialize_engine
"""Initialize the LLMEngine from the command line arguments.""" engine_args = EngineArgs.from_cli_args(args) return LLMEngine.from_engine_args(engine_args)
def initialize_engine(args: argparse.Namespace) ->LLMEngine: """Initialize the LLMEngine from the command line arguments.""" engine_args = EngineArgs.from_cli_args(args) return LLMEngine.from_engine_args(engine_args)
Initialize the LLMEngine from the command line arguments.
__init__
super().__init__() hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.self_attention = FalconAttention(config, linear_method) self.mlp = FalconMLP(config, linear_method) self.config = config if config.new_decoder_architecture: self.ln_attn = LayerNorm(hidden_size, eps=config.layer_nor...
def __init__(self, config: FalconConfig, linear_method: Optional[ LinearMethodBase]=None): super().__init__() hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.self_attention = FalconAttention(config, linear_method) self.mlp = FalconMLP(config, linear_method) ...
null
_init_engine
return MockEngine()
def _init_engine(self, *args, **kwargs): return MockEngine()
null
sample
head = self.lm_head.linear next_tokens = self.sampler(head.weight, hidden_states, sampling_metadata, head.bias) return next_tokens
def sample(self, hidden_states: torch.Tensor, sampling_metadata: SamplingMetadata) ->Optional[SamplerOutput]: head = self.lm_head.linear next_tokens = self.sampler(head.weight, hidden_states, sampling_metadata, head.bias) return next_tokens
null
test_reshape_and_cache
random.seed(seed) torch.random.manual_seed(seed) torch.cuda.manual_seed(seed) gpu_id = f'cuda:{device}' num_slots = block_size * num_blocks slot_mapping = random.sample(range(num_slots), num_tokens) slot_mapping = torch.tensor(slot_mapping, dtype=torch.long, device=gpu_id) qkv = torch.randn(num_tokens, 3, num_heads, he...
@pytest.mark.parametrize('num_tokens', NUM_TOKENS) @pytest.mark.parametrize('num_heads', NUM_HEADS) @pytest.mark.parametrize('head_size', HEAD_SIZES) @pytest.mark.parametrize('block_size', BLOCK_SIZES) @pytest.mark.parametrize('num_blocks', NUM_BLOCKS) @pytest.mark.parametrize('dtype', DTYPES) @pytest.mark.parametrize(...
null
get_len
return self.data.get_len()
def get_len(self) ->int: return self.data.get_len()
null
get_special_tokens_mask
""" Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optiona...
def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) ->List[ int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the toke...
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequenc...
add_global_metrics_labels
labels.update(kwargs)
def add_global_metrics_labels(**kwargs): labels.update(kwargs)
null
forward
qkv, _ = self.qkv_proj(hidden_states) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], 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.split([self.q_size, self.kv_size, self.kv_size], dim=-1) q, k = self.rotary_emb(positions, q, k) k_cache, v_ca...
null
model_parallel_is_initialized
"""Check if tensor and pipeline parallel groups are initialized.""" return _TENSOR_MODEL_PARALLEL_GROUP is not None and _PIPELINE_MODEL_PARALLEL_GROUP is not None
def model_parallel_is_initialized(): """Check if tensor and pipeline parallel groups are initialized.""" return (_TENSOR_MODEL_PARALLEL_GROUP is not None and _PIPELINE_MODEL_PARALLEL_GROUP is not None)
Check if tensor and pipeline parallel groups are initialized.
swap_in
self._swap(self.cpu_cache, self.gpu_cache, src_to_dst)
def swap_in(self, src_to_dst: Dict[int, int]) ->None: self._swap(self.cpu_cache, self.gpu_cache, src_to_dst)
null
__init__
self.is_prompt = is_prompt self.max_context_len = max_context_len self.slot_mapping = slot_mapping self.context_lens = context_lens self.block_tables = block_tables self.use_cuda_graph = use_cuda_graph self.attn_bias = None
def __init__(self, is_prompt: bool, slot_mapping: torch.Tensor, max_context_len: Optional[int], context_lens: Optional[torch.Tensor], block_tables: Optional[torch.Tensor], use_cuda_graph: bool) ->None: self.is_prompt = is_prompt self.max_context_len = max_context_len self.slot_mapping = slot_mapping...
null
_append_logical_block
block = LogicalTokenBlock(block_number=len(self.logical_token_blocks), block_size=self.block_size) self.logical_token_blocks.append(block)
def _append_logical_block(self) ->None: block = LogicalTokenBlock(block_number=len(self.logical_token_blocks), block_size=self.block_size) self.logical_token_blocks.append(block)
null
__init__
self.step_calls = 0 self.add_request_calls = 0 self.abort_request_calls = 0 self.request_id = None
def __init__(self): self.step_calls = 0 self.add_request_calls = 0 self.abort_request_calls = 0 self.request_id = None
null
forward
qkv, _ = self.query_key_value(hidden_states) q, k, v = qkv.chunk(chunks=3, dim=-1) q, k = self.rotary_emb(position_ids, q, k) k_cache, v_cache = kv_cache attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata) output, _ = self.dense(attn_output) return output
def forward(self, position_ids: torch.Tensor, hidden_states: torch.Tensor, kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor: qkv, _ = self.query_key_value(hidden_states) q, k, v = qkv.chunk(chunks=3, dim=-1) q, k = self.rotary_emb(position_ids, q, k) k_cache, v_cache = kv_cache a...
null
from_engine_args
"""Creates an LLM engine from the engine arguments.""" engine_configs = engine_args.create_engine_configs() parallel_config = engine_configs[2] placement_group = initialize_cluster(parallel_config) engine = cls(*engine_configs, placement_group, log_stats=not engine_args. disable_log_stats) return engine
@classmethod def from_engine_args(cls, engine_args: EngineArgs) ->'LLMEngine': """Creates an LLM engine from the engine arguments.""" engine_configs = engine_args.create_engine_configs() parallel_config = engine_configs[2] placement_group = initialize_cluster(parallel_config) engine = cls(*engine_co...
Creates an LLM engine from the engine arguments.
abort_seq_group
if isinstance(request_id, str): request_id = request_id, request_ids = set(request_id) for state_queue in [self.waiting, self.running, self.swapped]: for seq_group in reversed(state_queue): if seq_group.request_id in request_ids: state_queue.remove(seq_group) for seq in seq_group...
def abort_seq_group(self, request_id: Union[str, Iterable[str]]) ->None: if isinstance(request_id, str): request_id = request_id, request_ids = set(request_id) for state_queue in [self.waiting, self.running, self.swapped]: for seq_group in reversed(state_queue): if seq_group.requ...
null
forward
hidden_states = self.embed_in(input_ids) for i in range(len(self.layers)): layer = self.layers[i] hidden_states = layer(position_ids, hidden_states, kv_caches[i], input_metadata) hidden_states = self.final_layer_norm(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.embed_in(input_ids) for i in range(len(self.layers)): layer = self.layers[i] hidden_states = layer(position_ids, hidden_states,...
null
get_vocab
"""Returns vocab as a dict""" vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab
def get_vocab(self): """Returns vocab as a dict""" vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab
Returns vocab as a dict
forward
del kv_caches self.input_buffers['input_ids'].copy_(input_ids, non_blocking=True) self.input_buffers['positions'].copy_(positions, non_blocking=True) self.input_buffers['slot_mapping'].copy_(input_metadata.slot_mapping, non_blocking=True) self.input_buffers['context_lens'].copy_(input_metadata.context_lens, non...
def forward(self, input_ids: torch.Tensor, positions: torch.Tensor, kv_caches: List[Tuple[torch.Tensor, torch.Tensor]], input_metadata: InputMetadata) ->torch.Tensor: del kv_caches self.input_buffers['input_ids'].copy_(input_ids, non_blocking=True) self.input_buffers['positions'].copy_(positions, no...
null
get_sliding_window
return getattr(self.hf_config, 'sliding_window', None)
def get_sliding_window(self) ->Optional[int]: return getattr(self.hf_config, 'sliding_window', None)
null
step
"""Performs one decoding iteration and returns newly generated results. This function performs one decoding iteration of the engine. It first schedules the sequences to be executed in the next iteration and the token blocks to be swapped in/out/copy. Then, it executes the model and upda...
def step(self) ->List[RequestOutput]: """Performs one decoding iteration and returns newly generated results. This function performs one decoding iteration of the engine. It first schedules the sequences to be executed in the next iteration and the token blocks to be swapped in/out/copy. Th...
Performs one decoding iteration and returns newly generated results. This function performs one decoding iteration of the engine. It first schedules the sequences to be executed in the next iteration and the token blocks to be swapped in/out/copy. Then, it executes the model and updates the scheduler with the model ou...
get_pipeline_model_parallel_prev_rank
"""Return the global rank that preceeds 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_prev_rank(): """Return the global rank that preceeds 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_...
Return the global rank that preceeds the caller in the pipeline
create_weights
"""Create weights for a linear layer.""" raise NotImplementedError
@abstractmethod def create_weights(self, input_size_per_partition: int, output_size_per_partition: int, input_size: int, output_size: int, params_dtype: torch.dtype) ->Dict[str, Any]: """Create weights for a linear layer.""" raise NotImplementedError
Create weights for a linear layer.
get_num_free_gpu_blocks
return self.gpu_allocator.get_num_free_blocks()
def get_num_free_gpu_blocks(self) ->int: return self.gpu_allocator.get_num_free_blocks()
null
_schedule
blocks_to_swap_in: Dict[int, int] = {} blocks_to_swap_out: Dict[int, int] = {} blocks_to_copy: Dict[int, List[int]] = {} now = time.monotonic() if not self.swapped: ignored_seq_groups: List[SequenceGroup] = [] scheduled: List[SequenceGroup] = [] num_curr_seqs = sum(seq_group.get_max_num_running_seqs() for s...
def _schedule(self) ->SchedulerOutputs: blocks_to_swap_in: Dict[int, int] = {} blocks_to_swap_out: Dict[int, int] = {} blocks_to_copy: Dict[int, List[int]] = {} now = time.monotonic() if not self.swapped: ignored_seq_groups: List[SequenceGroup] = [] scheduled: List[SequenceGroup] = [...
null
get_last_token_id
assert self.num_tokens > 0 return self.token_ids[self.num_tokens - 1]
def get_last_token_id(self) ->int: assert self.num_tokens > 0 return self.token_ids[self.num_tokens - 1]
null
forward
if residual is not None: ops.fused_add_rms_norm(x, residual, self.weight.data, self.variance_epsilon ) return x, residual out = torch.empty_like(x) ops.rms_norm(out, x, self.weight.data, self.variance_epsilon) return out
def forward(self, x: torch.Tensor, residual: Optional[torch.Tensor]=None ) ->Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: if residual is not None: ops.fused_add_rms_norm(x, residual, self.weight.data, self. variance_epsilon) return x, residual out = torch.empty_like(x)...
null
get_supported_act_dtypes
return [torch.half]
@classmethod def get_supported_act_dtypes(cls) ->List[torch.dtype]: return [torch.half]
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 current_shard_offset = 0 shard_offsets = [] for i, output_size in enume...
def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor, loaded_shard_id: Optional[int]=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
propagate_exception
"""Propagate an exception to request streams (all if request_id is None).""" if request_id is not None: self._request_streams[request_id].put(exc) else: for stream in self._request_streams.values(): stream.put(exc)
def propagate_exception(self, exc: Exception, request_id: Optional[str]=None ) ->None: """Propagate an exception to request streams (all if request_id is None).""" if request_id is not None: self._request_streams[request_id].put(exc) else: for stream in self._request_streams.valu...
Propagate an exception to request streams (all if request_id is None).
get_token_ids
return self.data.get_token_ids()
def get_token_ids(self) ->List[int]: return self.data.get_token_ids()
null
add_cli_args
"""Shared CLI arguments for vLLM engine.""" parser.add_argument('--model', type=str, default='facebook/opt-125m', help= 'name or path of the huggingface model to use') parser.add_argument('--tokenizer', type=str, default=EngineArgs.tokenizer, help='name or path of the huggingface tokenizer to use') parser.add_a...
@staticmethod def add_cli_args(parser: argparse.ArgumentParser) ->argparse.ArgumentParser: """Shared CLI arguments for vLLM engine.""" parser.add_argument('--model', type=str, default='facebook/opt-125m', help='name or path of the huggingface model to use') parser.add_argument('--tokenizer', type=st...
Shared CLI arguments for vLLM engine.
__repr__
return f'SqueezeLLMConfig(weight_bits={self.weight_bits})'
def __repr__(self) ->str: return f'SqueezeLLMConfig(weight_bits={self.weight_bits})'
null
__init__
self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.initializer_range = initializer_range ...
def __init__(self, vocab_size=64000, hidden_size=4096, intermediate_size= 11008, num_hidden_layers=32, num_attention_heads=32, hidden_act='silu', max_position_embeddings=4096, initializer_range=0.02, rms_norm_eps= 1e-06, use_cache=True, pad_token_id=0, bos_token_id=1, eos_token_id=2, tie_word_embeddings...
null
test_gelu_new
torch.random.manual_seed(seed) torch.cuda.manual_seed(seed) gpu_id = f'cuda:{device}' x = torch.randn(num_tokens, d, dtype=dtype, device=gpu_id) layer = NewGELU() out = layer(x) ref_out = layer._forward(x) assert torch.allclose(out, ref_out, atol=1e-05, rtol=1e-05)
@pytest.mark.parametrize('num_tokens', NUM_TOKENS) @pytest.mark.parametrize('d', D) @pytest.mark.parametrize('dtype', DTYPES) @pytest.mark.parametrize('seed', SEEDS) @pytest.mark.parametrize('device', DEVICES) @torch.inference_mode() def test_gelu_new(num_tokens: int, d: int, dtype: torch.dtype, seed: int, device: ...
null
prepare_input_tensors
if self.is_driver_worker: is_prompt = seq_group_metadata_list[0].is_prompt if is_prompt: input_tokens, input_positions, input_metadata, prompt_lens = (self. _prepare_prompt(seq_group_metadata_list)) else: input_tokens, input_positions, input_metadata = self._prepare_decode( ...
def prepare_input_tensors(self, seq_group_metadata_list: Optional[List[ SequenceGroupMetadata]]) ->Tuple[torch.Tensor, torch.Tensor, InputMetadata, SamplingMetadata]: if self.is_driver_worker: is_prompt = seq_group_metadata_list[0].is_prompt if is_prompt: input_tokens, input_posi...
null
__init__
super().__init__() self.config = config self.embed_dim = config.n_embd self.wte = VocabParallelEmbedding(config.vocab_size, self.embed_dim) self.h = nn.ModuleList([GPTJBlock(config, linear_method) for _ in range( config.n_layer)]) self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
def __init__(self, config: GPTJConfig, linear_method: Optional[ LinearMethodBase]=None): super().__init__() self.config = config self.embed_dim = config.n_embd self.wte = VocabParallelEmbedding(config.vocab_size, self.embed_dim) self.h = nn.ModuleList([GPTJBlock(config, linear_method) for _ in r...
null
rotary
return not self.alibi
@property def rotary(self): return not self.alibi
null
forward
qkv, _ = self.Wqkv(hidden_states) q, k, v = qkv.chunk(chunks=3, dim=-1) q, k = self.rotary_emb(position_ids, q, k) k_cache, v_cache = kv_cache attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata) output, _ = self.out_proj(attn_output) return output
def forward(self, position_ids: torch.Tensor, hidden_states: torch.Tensor, kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor: qkv, _ = self.Wqkv(hidden_states) q, k, v = qkv.chunk(chunks=3, dim=-1) q, k = self.rotary_emb(position_ids, q, k) k_cache, v_cache = kv_cache attn_output ...
null
forward
residual = hidden_states if self.do_layer_norm_before: hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states = self.self_attn(hidden_states=hidden_states, kv_cache= kv_cache, input_metadata=input_metadata) hidden_states = residual + hidden_states if not self.do_layer_norm_before: hidden_sta...
def forward(self, hidden_states: torch.Tensor, kv_cache: KVCache, input_metadata: InputMetadata) ->torch.Tensor: residual = hidden_states if self.do_layer_norm_before: hidden_states = self.self_attn_layer_norm(hidden_states) hidden_states = self.self_attn(hidden_states=hidden_states, kv_cache= ...
null
_beam_search_sample
sample_idx = 0 results = [] for seq_group, is_prompt in zip(selected_seq_groups, is_prompts): seq_ids, sampling_params = seq_group num_parent_seqs = len(seq_ids) beam_width = sampling_params.best_of seq_group_logprobs = logprobs[sample_idx:sample_idx + num_parent_seqs] if is_prompt: assert n...
def _beam_search_sample(selected_seq_groups: List[Tuple[List[int], SamplingParams]], is_prompts: List[bool], seq_data: Dict[int, SequenceData], logprobs: torch.Tensor) ->List[Tuple[List[int], List[int]]]: sample_idx = 0 results = [] for seq_group, is_prompt in zip(selected_seq_groups, is_prompts): ...
null
get_from_keys
"""Get a value from the model's quantization config.""" for key in keys: if key in config: return config[key] raise ValueError( f"Cannot find any of {keys} in the model's quantization config.")
@staticmethod def get_from_keys(config: Dict[str, Any], keys: List[str]) ->Any: """Get a value from the model's quantization config.""" for key in keys: if key in config: return config[key] raise ValueError( f"Cannot find any of {keys} in the model's quantization config.")
Get a value from the model's quantization config.
get_pipeline_model_parallel_group
"""Get the pipeline model parallel group the caller rank belongs to.""" assert _PIPELINE_MODEL_PARALLEL_GROUP is not None, 'pipeline model parallel group is not initialized' return _PIPELINE_MODEL_PARALLEL_GROUP
def get_pipeline_model_parallel_group(): """Get the pipeline model parallel group the caller rank belongs to.""" assert _PIPELINE_MODEL_PARALLEL_GROUP is not None, 'pipeline model parallel group is not initialized' return _PIPELINE_MODEL_PARALLEL_GROUP
Get the pipeline model parallel group the caller rank belongs to.
__init__
super().__init__(*args, **kwargs, disable=True)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, disable=True)
null
__init__
self.cache_config = cache_config self.model_config = model_config self.parallel_config = parallel_config self.head_size = model_config.get_head_size() self.num_layers = model_config.get_num_layers(parallel_config) self.num_heads = model_config.get_num_kv_heads(parallel_config) self.dtype = model_config.dtype self.block...
def __init__(self, cache_config: CacheConfig, model_config: ModelConfig, parallel_config: ParallelConfig) ->None: self.cache_config = cache_config self.model_config = model_config self.parallel_config = parallel_config self.head_size = model_config.get_head_size() self.num_layers = model_config....
null
_prune_hidden_states
hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) return hidden_states.index_select(0, sampling_metadata.selected_token_indices)
def _prune_hidden_states(hidden_states: torch.Tensor, sampling_metadata: SamplingMetadata) ->torch.Tensor: hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) return hidden_states.index_select(0, sampling_metadata. selected_token_indices)
null
__init__
self.model_config = model_config self.parallel_config = parallel_config self.scheduler_config = scheduler_config self.local_rank = local_rank self.rank = rank self.distributed_init_method = distributed_init_method self.is_driver_worker = is_driver_worker if self.is_driver_worker: assert self.rank == 0, 'The driver ...
def __init__(self, model_config: ModelConfig, parallel_config: ParallelConfig, scheduler_config: SchedulerConfig, local_rank: int, rank: int, distributed_init_method: str, is_driver_worker: bool=False ) ->None: self.model_config = model_config self.parallel_config = parallel_config self.schedule...
null
__init__
logging.Formatter.__init__(self, fmt, datefmt)
def __init__(self, fmt, datefmt=None): logging.Formatter.__init__(self, fmt, datefmt)
null
__init__
self.pipeline_parallel_size = pipeline_parallel_size self.tensor_parallel_size = tensor_parallel_size self.worker_use_ray = worker_use_ray self.max_parallel_loading_workers = max_parallel_loading_workers self.world_size = pipeline_parallel_size * tensor_parallel_size if self.world_size > 1: self.worker_use_ray = Tr...
def __init__(self, pipeline_parallel_size: int, tensor_parallel_size: int, worker_use_ray: bool, max_parallel_loading_workers: Optional[int]=None ) ->None: self.pipeline_parallel_size = pipeline_parallel_size self.tensor_parallel_size = tensor_parallel_size self.worker_use_ray = worker_use_ray s...
null
has_unfinished_seqs
return self.waiting or self.running or self.swapped
def has_unfinished_seqs(self) ->bool: return self.waiting or self.running or self.swapped
null
_verify_quantization
supported_quantization = ['awq', 'gptq', 'squeezellm'] rocm_not_supported_quantization = ['awq'] if self.quantization is not None: self.quantization = self.quantization.lower() hf_quant_config = getattr(self.hf_config, 'quantization_config', None) if hf_quant_config is not None: hf_quant_method = str(hf_quant_c...
def _verify_quantization(self) ->None: supported_quantization = ['awq', 'gptq', 'squeezellm'] rocm_not_supported_quantization = ['awq'] if self.quantization is not None: self.quantization = self.quantization.lower() hf_quant_config = getattr(self.hf_config, 'quantization_config', None) if hf...
null
__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, max_position_embeddings: int, rope_theta: float=10000, rope_scaling: Optional[Dict[str, Any]]=None, linear_method: Optional[LinearMethodBase ]=None): super().__init__() self.hidden_size = hidden_size tensor_model_parallel_world_size = get_tens...
null
_compute_inv_freq
"""Compute the inverse frequency.""" inv_freq = 1.0 / base ** (torch.arange(0, self.rotary_dim, 2, dtype=torch. float, device='cuda') / self.rotary_dim) return inv_freq
def _compute_inv_freq(self, base: Union[int, float]) ->torch.Tensor: """Compute the inverse frequency.""" inv_freq = 1.0 / base ** (torch.arange(0, self.rotary_dim, 2, dtype= torch.float, device='cuda') / self.rotary_dim) return inv_freq
Compute the inverse frequency.
parse_args
parser = argparse.ArgumentParser(description= 'vLLM OpenAI-Compatible RESTful API server.') parser.add_argument('--host', type=str, default=None, help='host name') parser.add_argument('--port', type=int, default=8000, help='port number') parser.add_argument('--allow-credentials', action='store_true', help= 'all...
def parse_args(): parser = argparse.ArgumentParser(description= 'vLLM OpenAI-Compatible RESTful API server.') parser.add_argument('--host', type=str, default=None, help='host name') parser.add_argument('--port', type=int, default=8000, help='port number') parser.add_argument('--allow-credentials...
null
generate_greedy
greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens) outputs = self.generate(prompts, greedy_params) return [(output_ids[0], output_str[0]) for output_ids, output_str in outputs]
def generate_greedy(self, prompts: List[str], max_tokens: int) ->List[Tuple [List[int], str]]: greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens) outputs = self.generate(prompts, greedy_params) return [(output_ids[0], output_str[0]) for output_ids, output_str in outputs]
null
__repr__
return f'SequenceOutput(parent_seq_id={self.parent_seq_id}, output_token={self.output_token}, logprobs={self.logprobs})'
def __repr__(self) ->str: return ( f'SequenceOutput(parent_seq_id={self.parent_seq_id}, output_token={self.output_token}, logprobs={self.logprobs})' )
null
prepare_hf_model_weights
is_local = os.path.isdir(model_name_or_path) use_safetensors = False if load_format == 'auto': allow_patterns = ['*.safetensors', '*.bin'] elif load_format == 'safetensors': use_safetensors = True allow_patterns = ['*.safetensors'] elif load_format == 'pt': allow_patterns = ['*.pt'] elif load_format == ...
def prepare_hf_model_weights(model_name_or_path: str, cache_dir: Optional[ str]=None, load_format: str='auto', fall_back_to_pt: bool=True, revision: Optional[str]=None) ->Tuple[str, List[str], bool]: is_local = os.path.isdir(model_name_or_path) use_safetensors = False if load_format == 'auto': ...
null
__init__
super().__init__() self.total_num_heads = config.num_attention_heads self.hidden_size = config.hidden_size self.head_size = self.hidden_size // self.total_num_heads self.bias = getattr(config, 'attention_bias', True) tensor_model_parallel_world_size = get_tensor_model_parallel_world_size() assert self.total_num_heads %...
def __init__(self, config: GPTNeoXConfig, linear_method: Optional[ LinearMethodBase]=None): super().__init__() self.total_num_heads = config.num_attention_heads self.hidden_size = config.hidden_size self.head_size = self.hidden_size // self.total_num_heads self.bias = getattr(config, 'attention_...
null
_get_alibi_slopes
next_power_of_2 = 2 ** math.ceil(math.log2(total_num_heads)) m = torch.arange(1, next_power_of_2 + 1, dtype=torch.float32) m = m.mul(alibi_bias_max / next_power_of_2) slopes = 1.0 / torch.pow(2, m) if next_power_of_2 != total_num_heads: slopes = torch.concat([slopes[1::2], slopes[::2]])[:total_num_heads] return slo...
def _get_alibi_slopes(total_num_heads: int, alibi_bias_max: int ) ->torch.Tensor: next_power_of_2 = 2 ** math.ceil(math.log2(total_num_heads)) m = torch.arange(1, next_power_of_2 + 1, dtype=torch.float32) m = m.mul(alibi_bias_max / next_power_of_2) slopes = 1.0 / torch.pow(2, m) if next_power_of...
null
__init__
super().__init__() self.hidden_size = config.hidden_size rope_theta = getattr(config, 'rope_theta', 10000) self.self_attn = MixtralAttention(hidden_size=self.hidden_size, num_heads= config.num_attention_heads, max_position=config.max_position_embeddings, num_kv_heads=config.num_key_value_heads, rope_theta=rope_...
def __init__(self, config: MixtralConfig, linear_method: Optional[ LinearMethodBase]=None) ->None: super().__init__() self.hidden_size = config.hidden_size rope_theta = getattr(config, 'rope_theta', 10000) self.self_attn = MixtralAttention(hidden_size=self.hidden_size, num_heads=config.num_a...
null
__init__
""" AquilaRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def __init__(self, hidden_size, eps=1e-06): """ AquilaRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
AquilaRMSNorm is equivalent to T5LayerNorm
__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 = InternLMAttention(hidden_size=self.hidden_size, num_heads= config.num_attention_heads, bias=config.bias, rope_theta=r...
def __init__(self, config: LlamaConfig, 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) self.self_attn = InternL...
null
num_finished_seqs
return len(self.get_finished_seqs())
def num_finished_seqs(self) ->int: return len(self.get_finished_seqs())
null
__init__
super().__init__() self.hidden_size = config.hidden_size self.total_num_heads = config.n_head self.head_dim = self.hidden_size // self.total_num_heads assert self.head_dim * self.total_num_heads == self.hidden_size tp_world_size = get_tensor_model_parallel_world_size() assert self.total_num_heads % tp_world_size == 0 s...
def __init__(self, config: BloomConfig, linear_method: Optional[ LinearMethodBase]=None): super().__init__() self.hidden_size = config.hidden_size self.total_num_heads = config.n_head self.head_dim = self.hidden_size // self.total_num_heads assert self.head_dim * self.total_num_heads == self.hid...
null
__init__
super().__init__() hidden_size = config.hidden_size self.c_fc = ColumnParallelLinear(hidden_size, intermediate_size, bias=True, linear_method=linear_method) self.c_proj = RowParallelLinear(intermediate_size, hidden_size, bias=True, linear_method=linear_method) quant_config = getattr(linear_method, 'quant_config...
def __init__(self, intermediate_size: int, config: GPTBigCodeConfig, linear_method: Optional[LinearMethodBase]=None): super().__init__() hidden_size = config.hidden_size self.c_fc = ColumnParallelLinear(hidden_size, intermediate_size, bias= True, linear_method=linear_method) self.c_proj = Ro...
null
forward
hidden_states, _ = self.dense_h_to_4h(hidden_states) hidden_states = self.act(hidden_states) hidden_states, _ = self.dense_4h_to_h(hidden_states) return hidden_states
def forward(self, hidden_states): hidden_states, _ = self.dense_h_to_4h(hidden_states) hidden_states = self.act(hidden_states) hidden_states, _ = self.dense_4h_to_h(hidden_states) return hidden_states
null
free_seq
self.block_manager.free(seq)
def free_seq(self, seq: Sequence) ->None: self.block_manager.free(seq)
null
get_vllm_version
version = find_version(get_path('vllm', '__init__.py')) if _is_hip(): hipcc_version = get_hipcc_rocm_version() if hipcc_version != MAIN_CUDA_VERSION: rocm_version_str = hipcc_version.replace('.', '')[:3] version += f'+rocm{rocm_version_str}' else: cuda_version = str(nvcc_cuda_version) if...
def get_vllm_version() ->str: version = find_version(get_path('vllm', '__init__.py')) if _is_hip(): hipcc_version = get_hipcc_rocm_version() if hipcc_version != MAIN_CUDA_VERSION: rocm_version_str = hipcc_version.replace('.', '')[:3] version += f'+rocm{rocm_version_str}' ...
null
forward
inputs_embeds = self.embed_tokens(input_ids) pos_embeds = self.embed_positions(positions) if self.project_in is not None: inputs_embeds, _ = self.project_in(inputs_embeds) hidden_states = inputs_embeds + pos_embeds for i in range(len(self.layers)): layer = self.layers[i] hidden_states = layer(hidden_states,...
def forward(self, input_ids: torch.Tensor, positions: torch.Tensor, kv_caches: List[KVCache], input_metadata: InputMetadata) ->torch.Tensor: inputs_embeds = self.embed_tokens(input_ids) pos_embeds = self.embed_positions(positions) if self.project_in is not None: inputs_embeds, _ = self.project_i...
null
convert_bin_to_safetensor_file
loaded = torch.load(pt_filename, map_location='cpu') if 'state_dict' in loaded: loaded = loaded['state_dict'] shared = _shared_pointers(loaded) for shared_weights in shared: for name in shared_weights[1:]: loaded.pop(name) loaded = {k: v.contiguous() for k, v in loaded.items()} dirname = os.path.dirname...
def convert_bin_to_safetensor_file(pt_filename: str, sf_filename: str) ->None: loaded = torch.load(pt_filename, map_location='cpu') if 'state_dict' in loaded: loaded = loaded['state_dict'] shared = _shared_pointers(loaded) for shared_weights in shared: for name in shared_weights[1:]: ...
null
set_tokenizer
self.llm_engine.tokenizer = tokenizer
def set_tokenizer(self, tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast]) ->None: self.llm_engine.tokenizer = tokenizer
null
get_total_num_kv_heads
"""Returns the total number of KV heads.""" falcon_model_types = ['falcon', 'RefinedWeb', 'RefinedWebModel'] new_decoder_arch_falcon = (self.hf_config.model_type in falcon_model_types and getattr(self.hf_config, 'new_decoder_architecture', False)) if not new_decoder_arch_falcon and getattr(self.hf_config, 'multi_qu...
def get_total_num_kv_heads(self) ->int: """Returns the total number of KV heads.""" falcon_model_types = ['falcon', 'RefinedWeb', 'RefinedWebModel'] new_decoder_arch_falcon = (self.hf_config.model_type in falcon_model_types and getattr(self.hf_config, 'new_decoder_architecture', False)) ...
Returns the total number of KV heads.
__init__
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance( bos_token, str) else bos_token eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance( eos_token, str) else eos_token unk_token = AddedToken...
def __init__(self, vocab_file, unk_token='<unk>', bos_token='<s>', eos_token='</s>', pad_token=None, sp_model_kwargs: Optional[Dict[str, Any]]=None, add_bos_token=True, add_eos_token=False, clean_up_tokenization_spaces=False, **kwargs): self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_...
null
main
"""Main function that sets up and runs the prompt processing.""" engine = initialize_engine(args) test_prompts = create_test_prompts() process_requests(engine, test_prompts)
def main(args: argparse.Namespace): """Main function that sets up and runs the prompt processing.""" engine = initialize_engine(args) test_prompts = create_test_prompts() process_requests(engine, test_prompts)
Main function that sets up and runs the prompt processing.
_raise_exception_on_finish
msg = ( 'Task finished unexpectedly. This should never happen! Please open an issue on Github.' ) try: try: task.result() except asyncio.CancelledError: return except Exception as exc: raise AsyncEngineDeadError(msg + ' See stack trace above for the actual cause.'...
def _raise_exception_on_finish(task: asyncio.Task, request_tracker: 'RequestTracker') ->None: msg = ( 'Task finished unexpectedly. This should never happen! Please open an issue on Github.' ) try: try: task.result() except asyncio.CancelledError: retur...
null
initialize_dummy_weights
"""Initialize model weights with random values. The model weights must be randomly initialized for accurate performance measurements. Additionally, the model weights should not cause NaNs in the forward pass. We empirically found that initializing the weights with values between -1e-3 and 1e-3 works we...
def initialize_dummy_weights(model: torch.nn.Module, low: float=-0.001, high: float=0.001) ->None: """Initialize model weights with random values. The model weights must be randomly initialized for accurate performance measurements. Additionally, the model weights should not cause NaNs in the forwa...
Initialize model weights with random values. The model weights must be randomly initialized for accurate performance measurements. Additionally, the model weights should not cause NaNs in the forward pass. We empirically found that initializing the weights with values between -1e-3 and 1e-3 works well for most models.
get_policy
return cls._POLICY_REGISTRY[policy_name](**kwargs)
@classmethod def get_policy(cls, policy_name: str, **kwargs) ->Policy: return cls._POLICY_REGISTRY[policy_name](**kwargs)
null
from_cli_args
attrs = [attr.name for attr in dataclasses.fields(cls)] engine_args = cls(**{attr: getattr(args, attr) for attr in attrs}) return engine_args
@classmethod def from_cli_args(cls, args: argparse.Namespace) ->'EngineArgs': attrs = [attr.name for attr in dataclasses.fields(cls)] engine_args = cls(**{attr: getattr(args, attr) for attr in attrs}) return engine_args
null
create_test_prompts
"""Create a list of test prompts with their sampling parameters.""" return [('A robot may not injure a human being', SamplingParams(temperature =0.0, logprobs=1, prompt_logprobs=1)), ('To be or not to be,', SamplingParams(temperature=0.8, top_k=5, presence_penalty=0.2)), ( 'What is the meaning of life?', Sa...
def create_test_prompts() ->List[Tuple[str, SamplingParams]]: """Create a list of test prompts with their sampling parameters.""" return [('A robot may not injure a human being', SamplingParams( temperature=0.0, logprobs=1, prompt_logprobs=1)), ( 'To be or not to be,', SamplingParams(temperature...
Create a list of test prompts with their sampling parameters.
_process_model_outputs
scheduled_seq_groups = scheduler_outputs.scheduled_seq_groups for seq_group, outputs in zip(scheduled_seq_groups, output): self._process_sequence_group_outputs(seq_group, outputs) self.scheduler.free_finished_seq_groups() request_outputs: List[RequestOutput] = [] for seq_group in (scheduled_seq_groups + scheduler_o...
def _process_model_outputs(self, output: SamplerOutput, scheduler_outputs: SchedulerOutputs) ->List[RequestOutput]: scheduled_seq_groups = scheduler_outputs.scheduled_seq_groups for seq_group, outputs in zip(scheduled_seq_groups, output): self._process_sequence_group_outputs(seq_group, outputs) ...
null
__init__
super().__init__() self.config = config self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size vocab_size = (config.vocab_size + 63) // 64 * 64 self.embed_tokens = VocabParallelEmbedding(vocab_size, config.hidden_size) self.layers = nn.ModuleList([InternLMDecoderLayer(config, linear_method) for ...
def __init__(self, config: LlamaConfig, linear_method: Optional[ LinearMethodBase]=None): super().__init__() self.config = config self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size vocab_size = (config.vocab_size + 63) // 64 * 64 self.embed_tokens = VocabParallelEmbed...
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
get_cpu_memory
"""Returns the total CPU memory of the node in bytes.""" return psutil.virtual_memory().total
def get_cpu_memory() ->int: """Returns the total CPU memory of the node in bytes.""" return psutil.virtual_memory().total
Returns the total CPU memory of the node in bytes.
load_model
self.model = get_model(self.model_config)
def load_model(self) ->None: self.model = get_model(self.model_config)
null
__init__
super().__init__() self.embed_dim = config.hidden_size self.word_embeddings = VocabParallelEmbedding(config.vocab_size, self.embed_dim ) self.word_embeddings_layernorm = nn.LayerNorm(self.embed_dim, eps=config. layer_norm_epsilon) self.h = nn.ModuleList([BloomBlock(config, linear_method) for _ in range( con...
def __init__(self, config: BloomConfig, linear_method: Optional[ LinearMethodBase]=None): super().__init__() self.embed_dim = config.hidden_size self.word_embeddings = VocabParallelEmbedding(config.vocab_size, self. embed_dim) self.word_embeddings_layernorm = nn.LayerNorm(self.embed_dim, eps...
null
_compute_cos_sin_cache
max_len = self.max_position_embeddings * self.scaling_factor base = self.base * (self.scaling_factor * max_len / self. max_position_embeddings - (self.scaling_factor - 1)) ** (self. rotary_dim / (self.rotary_dim - 2)) inv_freq = self._compute_inv_freq(base) t = torch.arange(max_len, dtype=torch.float, device='c...
def _compute_cos_sin_cache(self) ->torch.Tensor: max_len = self.max_position_embeddings * self.scaling_factor base = self.base * (self.scaling_factor * max_len / self. max_position_embeddings - (self.scaling_factor - 1)) ** (self. rotary_dim / (self.rotary_dim - 2)) inv_freq = self._compute_...
null
random_uuid
return str(uuid.uuid4().hex)
def random_uuid() ->str: return str(uuid.uuid4().hex)
null
__init__
self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads if num_key_value_heads is None: num_key_value_heads = num_attention_...
def __init__(self, vocab_size=64000, hidden_size=4096, intermediate_size= 11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=4, hidden_act='silu', max_position_embeddings=4096, initializer_range=0.02, rms_norm_eps=1e-05, use_cache=True, pad_token_id=0, bos_token_id=1, eos_token_id=...
null
copy
key_caches = [key_cache for key_cache, _ in self.gpu_cache] value_caches = [value_cache for _, value_cache in self.gpu_cache] cache_ops.copy_blocks(key_caches, value_caches, src_to_dsts)
def copy(self, src_to_dsts: Dict[int, List[int]]) ->None: key_caches = [key_cache for key_cache, _ in self.gpu_cache] value_caches = [value_cache for _, value_cache in self.gpu_cache] cache_ops.copy_blocks(key_caches, value_caches, src_to_dsts)
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.model = LLM(model=model_name, tokenizer=tokenizer_name, trust_remote_code=True, dtype=dtype, swap_space=0)
def __init__(self, model_name: str, tokenizer_name: Optional[str]=None, dtype: str='half') ->None: self.model = LLM(model=model_name, tokenizer=tokenizer_name, trust_remote_code=True, dtype=dtype, swap_space=0)
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
forward
x, bias = self.dense_h_to_4h(x) if bias is not None: x += bias x = self.act(x) x, bias = self.dense_4h_to_h(x) return x, bias
def forward(self, x: torch.Tensor) ->torch.Tensor: x, bias = self.dense_h_to_4h(x) if bias is not None: x += bias x = self.act(x) x, bias = self.dense_4h_to_h(x) return x, bias
null
divide
"""Ensure that numerator is divisible by the denominator and return the division value.""" ensure_divisibility(numerator, denominator) return numerator // denominator
def divide(numerator, denominator): """Ensure that numerator is divisible by the denominator and return the division value.""" ensure_divisibility(numerator, denominator) return numerator // denominator
Ensure that numerator is divisible by the denominator and return the division value.
test_multi_process_tensor_parallel
set_start_method('spawn', force=True) distributed_init_port = get_open_port() processes = [] for rank in range(tensor_parallel_size): p = Process(target=test_target, args=(tensor_parallel_size, rank, distributed_init_port)) p.start() processes.append(p) for p in processes: p.join() assert all(p....
@pytest.mark.skipif(torch.cuda.device_count() < 2, reason= 'Need at least 2 GPUs to run the test.') @pytest.mark.parametrize('tensor_parallel_size', [2]) @pytest.mark.parametrize('test_target', [all_reduce_test_worker, all_gather_test_worker]) def test_multi_process_tensor_parallel(tensor_parallel_size, test_ta...
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