Skip to content

vllm.model_executor.models.gpt2

Inference-only GPT-2 model compatible with HuggingFace weights.

GPT2Attention

Bases: Module

Source code in vllm/model_executor/models/gpt2.py
class GPT2Attention(nn.Module):

    def __init__(
        self,
        config: GPT2Config,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ):
        super().__init__()
        self.hidden_size = config.hidden_size
        total_num_heads = config.num_attention_heads
        tensor_model_parallel_world_size = (
            get_tensor_model_parallel_world_size())
        assert total_num_heads % tensor_model_parallel_world_size == 0
        self.num_heads = total_num_heads // tensor_model_parallel_world_size
        self.head_dim = self.hidden_size // total_num_heads
        self.scale = self.head_dim**-0.5

        self.c_attn = QKVParallelLinear(
            self.hidden_size,
            self.head_dim,
            total_num_heads,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.c_attn",
        )
        self.c_proj = RowParallelLinear(
            self.hidden_size,
            self.hidden_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.c_proj",
        )
        self.attn = Attention(self.num_heads,
                              self.head_dim,
                              scale=self.scale,
                              cache_config=cache_config,
                              quant_config=quant_config,
                              prefix=f"{prefix}.attn")

    def forward(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
        qkv, _ = self.c_attn(hidden_states)
        q, k, v = qkv.chunk(chunks=3, dim=-1)
        attn_output = self.attn(q, k, v)
        attn_output, _ = self.c_proj(attn_output)
        return attn_output

attn instance-attribute

attn = Attention(
    num_heads,
    head_dim,
    scale=scale,
    cache_config=cache_config,
    quant_config=quant_config,
    prefix=f"{prefix}.attn",
)

c_attn instance-attribute

c_attn = QKVParallelLinear(
    hidden_size,
    head_dim,
    total_num_heads,
    bias=True,
    quant_config=quant_config,
    prefix=f"{prefix}.c_attn",
)

c_proj instance-attribute

c_proj = RowParallelLinear(
    hidden_size,
    hidden_size,
    bias=True,
    quant_config=quant_config,
    prefix=f"{prefix}.c_proj",
)

head_dim instance-attribute

head_dim = hidden_size // total_num_heads

hidden_size instance-attribute

hidden_size = hidden_size

num_heads instance-attribute

num_heads = (
    total_num_heads // tensor_model_parallel_world_size
)

scale instance-attribute

scale = head_dim ** -0.5

__init__

__init__(
    config: GPT2Config,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
)
Source code in vllm/model_executor/models/gpt2.py
def __init__(
    self,
    config: GPT2Config,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
):
    super().__init__()
    self.hidden_size = config.hidden_size
    total_num_heads = config.num_attention_heads
    tensor_model_parallel_world_size = (
        get_tensor_model_parallel_world_size())
    assert total_num_heads % tensor_model_parallel_world_size == 0
    self.num_heads = total_num_heads // tensor_model_parallel_world_size
    self.head_dim = self.hidden_size // total_num_heads
    self.scale = self.head_dim**-0.5

    self.c_attn = QKVParallelLinear(
        self.hidden_size,
        self.head_dim,
        total_num_heads,
        bias=True,
        quant_config=quant_config,
        prefix=f"{prefix}.c_attn",
    )
    self.c_proj = RowParallelLinear(
        self.hidden_size,
        self.hidden_size,
        bias=True,
        quant_config=quant_config,
        prefix=f"{prefix}.c_proj",
    )
    self.attn = Attention(self.num_heads,
                          self.head_dim,
                          scale=self.scale,
                          cache_config=cache_config,
                          quant_config=quant_config,
                          prefix=f"{prefix}.attn")

forward

forward(hidden_states: Tensor) -> Tensor
Source code in vllm/model_executor/models/gpt2.py
def forward(
    self,
    hidden_states: torch.Tensor,
) -> torch.Tensor:
    qkv, _ = self.c_attn(hidden_states)
    q, k, v = qkv.chunk(chunks=3, dim=-1)
    attn_output = self.attn(q, k, v)
    attn_output, _ = self.c_proj(attn_output)
    return attn_output

GPT2Block

Bases: Module

Source code in vllm/model_executor/models/gpt2.py
class GPT2Block(nn.Module):

    def __init__(
        self,
        config: GPT2Config,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ):
        super().__init__()
        hidden_size = config.hidden_size
        inner_dim = (config.n_inner if config.n_inner is not None else 4 *
                     hidden_size)

        self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
        self.attn = GPT2Attention(config,
                                  cache_config,
                                  quant_config,
                                  prefix=f"{prefix}.attn")
        self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
        self.mlp = GPT2MLP(inner_dim,
                           config,
                           quant_config,
                           prefix=f"{prefix}.mlp")

    def forward(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor:
        residual = hidden_states
        hidden_states = self.ln_1(hidden_states)
        attn_output = self.attn(hidden_states=hidden_states)
        # residual connection
        hidden_states = attn_output + residual

        residual = hidden_states
        hidden_states = self.ln_2(hidden_states)
        feed_forward_hidden_states = self.mlp(hidden_states)
        # residual connection
        hidden_states = residual + feed_forward_hidden_states
        return hidden_states

attn instance-attribute

attn = GPT2Attention(
    config,
    cache_config,
    quant_config,
    prefix=f"{prefix}.attn",
)

ln_1 instance-attribute

ln_1 = LayerNorm(hidden_size, eps=layer_norm_epsilon)

ln_2 instance-attribute

ln_2 = LayerNorm(hidden_size, eps=layer_norm_epsilon)

mlp instance-attribute

mlp = GPT2MLP(
    inner_dim, config, quant_config, prefix=f"{prefix}.mlp"
)

__init__

__init__(
    config: GPT2Config,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
)
Source code in vllm/model_executor/models/gpt2.py
def __init__(
    self,
    config: GPT2Config,
    cache_config: Optional[CacheConfig] = None,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
):
    super().__init__()
    hidden_size = config.hidden_size
    inner_dim = (config.n_inner if config.n_inner is not None else 4 *
                 hidden_size)

    self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
    self.attn = GPT2Attention(config,
                              cache_config,
                              quant_config,
                              prefix=f"{prefix}.attn")
    self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
    self.mlp = GPT2MLP(inner_dim,
                       config,
                       quant_config,
                       prefix=f"{prefix}.mlp")

forward

forward(hidden_states: Tensor) -> Tensor
Source code in vllm/model_executor/models/gpt2.py
def forward(
    self,
    hidden_states: torch.Tensor,
) -> torch.Tensor:
    residual = hidden_states
    hidden_states = self.ln_1(hidden_states)
    attn_output = self.attn(hidden_states=hidden_states)
    # residual connection
    hidden_states = attn_output + residual

    residual = hidden_states
    hidden_states = self.ln_2(hidden_states)
    feed_forward_hidden_states = self.mlp(hidden_states)
    # residual connection
    hidden_states = residual + feed_forward_hidden_states
    return hidden_states

GPT2ForSequenceClassification

Bases: Module

GPT2 Model for sequence classification.

This class expands GPT2Model with pooling and score functions - last token is being used for classification.

Attributes:

Name Type Description
transformer

An instance of GPT2Model used for forward operations.

score

A layer for calculating logits.

_pooler

An instance of Pooler used for pooling operations.

Source code in vllm/model_executor/models/gpt2.py
class GPT2ForSequenceClassification(nn.Module):
    """GPT2 Model for sequence classification.

    This class expands GPT2Model with pooling and score functions - last token
    is being used for classification.

    Attributes:
        transformer: An instance of GPT2Model used for forward operations.
        score: A layer for calculating logits.
        _pooler: An instance of Pooler used for pooling operations.
    """

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = vllm_config.model_config.hf_config
        self.transformer = GPT2Model(vllm_config=vllm_config,
                                     prefix=maybe_prefix(prefix, "gpt2"))
        self.score = nn.Linear(config.n_embd, config.num_labels, bias=False)
        pooler_config = vllm_config.model_config.pooler_config
        self._pooler = Pooler.from_config_with_defaults(
            pooler_config,
            pooling_type=PoolingType.LAST,
            normalize=False,
            softmax=True)

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
        loader = AutoWeightsLoader(self)
        return loader.load_weights(weights)

    def pooler(
        self,
        hidden_states: torch.Tensor,
        pooling_metadata: PoolingMetadata,
    ) -> Optional[PoolerOutput]:
        return self._pooler(hidden_states, pooling_metadata)

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors] = None,
        inputs_embeds: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        hidden_states = self.transformer(
            input_ids=input_ids,
            position_ids=positions,
            inputs_embeds=inputs_embeds,
            intermediate_tensors=intermediate_tensors)
        logits = self.score(hidden_states)
        return logits

_pooler instance-attribute

_pooler = from_config_with_defaults(
    pooler_config,
    pooling_type=LAST,
    normalize=False,
    softmax=True,
)

score instance-attribute

score = Linear(n_embd, num_labels, bias=False)

transformer instance-attribute

transformer = GPT2Model(
    vllm_config=vllm_config,
    prefix=maybe_prefix(prefix, "gpt2"),
)

__init__

__init__(*, vllm_config: VllmConfig, prefix: str = '')
Source code in vllm/model_executor/models/gpt2.py
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
    super().__init__()
    config = vllm_config.model_config.hf_config
    self.transformer = GPT2Model(vllm_config=vllm_config,
                                 prefix=maybe_prefix(prefix, "gpt2"))
    self.score = nn.Linear(config.n_embd, config.num_labels, bias=False)
    pooler_config = vllm_config.model_config.pooler_config
    self._pooler = Pooler.from_config_with_defaults(
        pooler_config,
        pooling_type=PoolingType.LAST,
        normalize=False,
        softmax=True)

forward

forward(
    input_ids: Tensor,
    positions: Tensor,
    intermediate_tensors: Optional[
        IntermediateTensors
    ] = None,
    inputs_embeds: Optional[Tensor] = None,
) -> Tensor
Source code in vllm/model_executor/models/gpt2.py
def forward(
    self,
    input_ids: torch.Tensor,
    positions: torch.Tensor,
    intermediate_tensors: Optional[IntermediateTensors] = None,
    inputs_embeds: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    hidden_states = self.transformer(
        input_ids=input_ids,
        position_ids=positions,
        inputs_embeds=inputs_embeds,
        intermediate_tensors=intermediate_tensors)
    logits = self.score(hidden_states)
    return logits

load_weights

load_weights(weights: Iterable[tuple[str, Tensor]])
Source code in vllm/model_executor/models/gpt2.py
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
    loader = AutoWeightsLoader(self)
    return loader.load_weights(weights)

pooler

pooler(
    hidden_states: Tensor, pooling_metadata: PoolingMetadata
) -> Optional[PoolerOutput]
Source code in vllm/model_executor/models/gpt2.py
def pooler(
    self,
    hidden_states: torch.Tensor,
    pooling_metadata: PoolingMetadata,
) -> Optional[PoolerOutput]:
    return self._pooler(hidden_states, pooling_metadata)

GPT2LMHeadModel

Bases: Module, SupportsPP

Source code in vllm/model_executor/models/gpt2.py
class GPT2LMHeadModel(nn.Module, SupportsPP):

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
        self.config = config
        self.quant_config = quant_config
        self.transformer = GPT2Model(vllm_config=vllm_config,
                                     prefix=maybe_prefix(
                                         prefix, "transformer"))
        self.lm_head = ParallelLMHead(self.config.vocab_size,
                                      self.config.hidden_size,
                                      quant_config=quant_config,
                                      prefix=f"{prefix}.lm_head")
        if self.config.tie_word_embeddings:
            self.lm_head = self.lm_head.tie_weights(self.transformer.wte)

        self.logits_processor = LogitsProcessor(config.vocab_size)
        self.make_empty_intermediate_tensors = (
            self.transformer.make_empty_intermediate_tensors)

    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.transformer.get_input_embeddings(input_ids)

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors] = None,
        inputs_embeds: Optional[torch.Tensor] = None,
    ) -> Union[torch.Tensor, IntermediateTensors]:
        hidden_states = self.transformer(input_ids, positions,
                                         intermediate_tensors, inputs_embeds)
        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[torch.Tensor]:
        logits = self.logits_processor(self.lm_head, hidden_states,
                                       sampling_metadata)
        return logits

    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(self)
        weights = _add_transformer_prefix(weights)
        return loader.load_weights(weights)

config instance-attribute

config = config

lm_head instance-attribute

lm_head = ParallelLMHead(
    vocab_size,
    hidden_size,
    quant_config=quant_config,
    prefix=f"{prefix}.lm_head",
)

logits_processor instance-attribute

logits_processor = LogitsProcessor(vocab_size)

make_empty_intermediate_tensors instance-attribute

make_empty_intermediate_tensors = (
    make_empty_intermediate_tensors
)

quant_config instance-attribute

quant_config = quant_config

transformer instance-attribute

transformer = GPT2Model(
    vllm_config=vllm_config,
    prefix=maybe_prefix(prefix, "transformer"),
)

__init__

__init__(*, vllm_config: VllmConfig, prefix: str = '')
Source code in vllm/model_executor/models/gpt2.py
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
    super().__init__()
    config = vllm_config.model_config.hf_config
    quant_config = vllm_config.quant_config
    self.config = config
    self.quant_config = quant_config
    self.transformer = GPT2Model(vllm_config=vllm_config,
                                 prefix=maybe_prefix(
                                     prefix, "transformer"))
    self.lm_head = ParallelLMHead(self.config.vocab_size,
                                  self.config.hidden_size,
                                  quant_config=quant_config,
                                  prefix=f"{prefix}.lm_head")
    if self.config.tie_word_embeddings:
        self.lm_head = self.lm_head.tie_weights(self.transformer.wte)

    self.logits_processor = LogitsProcessor(config.vocab_size)
    self.make_empty_intermediate_tensors = (
        self.transformer.make_empty_intermediate_tensors)

compute_logits

compute_logits(
    hidden_states: Tensor,
    sampling_metadata: SamplingMetadata,
) -> Optional[Tensor]
Source code in vllm/model_executor/models/gpt2.py
def compute_logits(
    self,
    hidden_states: torch.Tensor,
    sampling_metadata: SamplingMetadata,
) -> Optional[torch.Tensor]:
    logits = self.logits_processor(self.lm_head, hidden_states,
                                   sampling_metadata)
    return logits

forward

forward(
    input_ids: Tensor,
    positions: Tensor,
    intermediate_tensors: Optional[
        IntermediateTensors
    ] = None,
    inputs_embeds: Optional[Tensor] = None,
) -> Union[Tensor, IntermediateTensors]
Source code in vllm/model_executor/models/gpt2.py
def forward(
    self,
    input_ids: torch.Tensor,
    positions: torch.Tensor,
    intermediate_tensors: Optional[IntermediateTensors] = None,
    inputs_embeds: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, IntermediateTensors]:
    hidden_states = self.transformer(input_ids, positions,
                                     intermediate_tensors, inputs_embeds)
    return hidden_states

get_input_embeddings

get_input_embeddings(input_ids: Tensor) -> Tensor
Source code in vllm/model_executor/models/gpt2.py
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
    return self.transformer.get_input_embeddings(input_ids)

load_weights

load_weights(
    weights: Iterable[tuple[str, Tensor]],
) -> set[str]
Source code in vllm/model_executor/models/gpt2.py
def load_weights(self, weights: Iterable[tuple[str,
                                               torch.Tensor]]) -> set[str]:
    loader = AutoWeightsLoader(self)
    weights = _add_transformer_prefix(weights)
    return loader.load_weights(weights)

GPT2MLP

Bases: Module

Source code in vllm/model_executor/models/gpt2.py
class GPT2MLP(nn.Module):

    def __init__(
        self,
        intermediate_size: int,
        config: GPT2Config,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ):
        super().__init__()
        hidden_size = config.hidden_size
        self.c_fc = ColumnParallelLinear(
            hidden_size,
            intermediate_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.c_fc",
        )
        self.c_proj = RowParallelLinear(
            intermediate_size,
            hidden_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.c_proj",
        )
        self.act = get_act_fn(config.activation_function)

    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

act instance-attribute

act = get_act_fn(activation_function)

c_fc instance-attribute

c_fc = ColumnParallelLinear(
    hidden_size,
    intermediate_size,
    bias=True,
    quant_config=quant_config,
    prefix=f"{prefix}.c_fc",
)

c_proj instance-attribute

c_proj = RowParallelLinear(
    intermediate_size,
    hidden_size,
    bias=True,
    quant_config=quant_config,
    prefix=f"{prefix}.c_proj",
)

__init__

__init__(
    intermediate_size: int,
    config: GPT2Config,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
)
Source code in vllm/model_executor/models/gpt2.py
def __init__(
    self,
    intermediate_size: int,
    config: GPT2Config,
    quant_config: Optional[QuantizationConfig] = None,
    prefix: str = "",
):
    super().__init__()
    hidden_size = config.hidden_size
    self.c_fc = ColumnParallelLinear(
        hidden_size,
        intermediate_size,
        bias=True,
        quant_config=quant_config,
        prefix=f"{prefix}.c_fc",
    )
    self.c_proj = RowParallelLinear(
        intermediate_size,
        hidden_size,
        bias=True,
        quant_config=quant_config,
        prefix=f"{prefix}.c_proj",
    )
    self.act = get_act_fn(config.activation_function)

forward

forward(hidden_states: Tensor) -> Tensor
Source code in vllm/model_executor/models/gpt2.py
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

GPT2Model

Bases: Module

Source code in vllm/model_executor/models/gpt2.py
@support_torch_compile
class GPT2Model(nn.Module):

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()

        config = vllm_config.model_config.hf_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config

        self.config = config
        assert not config.add_cross_attention
        assert not config.scale_attn_by_inverse_layer_idx
        assert not config.reorder_and_upcast_attn
        self.embed_dim = config.hidden_size
        self.wte = VocabParallelEmbedding(config.vocab_size,
                                          self.embed_dim,
                                          quant_config=quant_config,
                                          prefix=f"{prefix}.wte")
        self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
        self.start_layer, self.end_layer, self.h = make_layers(
            config.num_hidden_layers,
            lambda prefix: GPT2Block(
                config, cache_config, quant_config, prefix=prefix),
            prefix=f"{prefix}.h")
        self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
        self.make_empty_intermediate_tensors = (
            make_empty_intermediate_tensors_factory(["hidden_states"],
                                                    config.n_embd))

    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.wte(input_ids)

    def forward(
        self,
        input_ids: torch.Tensor,
        position_ids: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors],
        inputs_embeds: Optional[torch.Tensor],
    ) -> Union[torch.Tensor, IntermediateTensors]:
        if get_pp_group().is_first_rank:
            if inputs_embeds is None:
                inputs_embeds = self.get_input_embeddings(input_ids)
            position_embeds = self.wpe(position_ids)
            hidden_states = inputs_embeds + position_embeds
        else:
            assert intermediate_tensors is not None
            hidden_states = intermediate_tensors["hidden_states"]

        for layer in self.h[self.start_layer:self.end_layer]:
            hidden_states = layer(hidden_states)

        if not get_pp_group().is_last_rank:
            return IntermediateTensors({"hidden_states": hidden_states})

        hidden_states = self.ln_f(hidden_states)
        return hidden_states

    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
        params_dict = dict(self.named_parameters(remove_duplicate=False))
        loaded_params: set[str] = set()
        for name, loaded_weight in weights:
            if ".attn.bias" in name or ".attn.masked_bias" in name:
                # Skip attention mask.
                # NOTE: "c_attn.bias" should not be skipped.
                continue

            if is_pp_missing_parameter(name, self):
                continue

            param = params_dict[name]
            # The HF's GPT-2 implementation uses Conv1D instead of Linear.
            # Because of this, we need to transpose the weights.
            # Note(zhuohan): the logic below might break quantized models.
            for conv1d_weight_name in ["c_attn", "c_proj", "c_fc"]:
                if conv1d_weight_name not in name:
                    continue
                if not name.endswith(".weight"):
                    continue
                loaded_weight = loaded_weight.t()
            weight_loader = getattr(param, "weight_loader",
                                    default_weight_loader)
            weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params

config instance-attribute

config = config

embed_dim instance-attribute

embed_dim = hidden_size

ln_f instance-attribute

ln_f = LayerNorm(embed_dim, eps=layer_norm_epsilon)

make_empty_intermediate_tensors instance-attribute

make_empty_intermediate_tensors = (
    make_empty_intermediate_tensors_factory(
        ["hidden_states"], n_embd
    )
)

wpe instance-attribute

wpe = Embedding(max_position_embeddings, embed_dim)

wte instance-attribute

wte = VocabParallelEmbedding(
    vocab_size,
    embed_dim,
    quant_config=quant_config,
    prefix=f"{prefix}.wte",
)

__init__

__init__(*, vllm_config: VllmConfig, prefix: str = '')
Source code in vllm/model_executor/models/gpt2.py
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
    super().__init__()

    config = vllm_config.model_config.hf_config
    cache_config = vllm_config.cache_config
    quant_config = vllm_config.quant_config

    self.config = config
    assert not config.add_cross_attention
    assert not config.scale_attn_by_inverse_layer_idx
    assert not config.reorder_and_upcast_attn
    self.embed_dim = config.hidden_size
    self.wte = VocabParallelEmbedding(config.vocab_size,
                                      self.embed_dim,
                                      quant_config=quant_config,
                                      prefix=f"{prefix}.wte")
    self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
    self.start_layer, self.end_layer, self.h = make_layers(
        config.num_hidden_layers,
        lambda prefix: GPT2Block(
            config, cache_config, quant_config, prefix=prefix),
        prefix=f"{prefix}.h")
    self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
    self.make_empty_intermediate_tensors = (
        make_empty_intermediate_tensors_factory(["hidden_states"],
                                                config.n_embd))

forward

forward(
    input_ids: Tensor,
    position_ids: Tensor,
    intermediate_tensors: Optional[IntermediateTensors],
    inputs_embeds: Optional[Tensor],
) -> Union[Tensor, IntermediateTensors]
Source code in vllm/model_executor/models/gpt2.py
def forward(
    self,
    input_ids: torch.Tensor,
    position_ids: torch.Tensor,
    intermediate_tensors: Optional[IntermediateTensors],
    inputs_embeds: Optional[torch.Tensor],
) -> Union[torch.Tensor, IntermediateTensors]:
    if get_pp_group().is_first_rank:
        if inputs_embeds is None:
            inputs_embeds = self.get_input_embeddings(input_ids)
        position_embeds = self.wpe(position_ids)
        hidden_states = inputs_embeds + position_embeds
    else:
        assert intermediate_tensors is not None
        hidden_states = intermediate_tensors["hidden_states"]

    for layer in self.h[self.start_layer:self.end_layer]:
        hidden_states = layer(hidden_states)

    if not get_pp_group().is_last_rank:
        return IntermediateTensors({"hidden_states": hidden_states})

    hidden_states = self.ln_f(hidden_states)
    return hidden_states

get_input_embeddings

get_input_embeddings(input_ids: Tensor) -> Tensor
Source code in vllm/model_executor/models/gpt2.py
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
    return self.wte(input_ids)

load_weights

load_weights(
    weights: Iterable[tuple[str, Tensor]],
) -> set[str]
Source code in vllm/model_executor/models/gpt2.py
def load_weights(self, weights: Iterable[tuple[str,
                                               torch.Tensor]]) -> set[str]:
    params_dict = dict(self.named_parameters(remove_duplicate=False))
    loaded_params: set[str] = set()
    for name, loaded_weight in weights:
        if ".attn.bias" in name or ".attn.masked_bias" in name:
            # Skip attention mask.
            # NOTE: "c_attn.bias" should not be skipped.
            continue

        if is_pp_missing_parameter(name, self):
            continue

        param = params_dict[name]
        # The HF's GPT-2 implementation uses Conv1D instead of Linear.
        # Because of this, we need to transpose the weights.
        # Note(zhuohan): the logic below might break quantized models.
        for conv1d_weight_name in ["c_attn", "c_proj", "c_fc"]:
            if conv1d_weight_name not in name:
                continue
            if not name.endswith(".weight"):
                continue
            loaded_weight = loaded_weight.t()
        weight_loader = getattr(param, "weight_loader",
                                default_weight_loader)
        weight_loader(param, loaded_weight)
        loaded_params.add(name)
    return loaded_params

_add_transformer_prefix

_add_transformer_prefix(
    weights: Iterable[tuple[str, Tensor]],
) -> Iterable[tuple[str, Tensor]]
Source code in vllm/model_executor/models/gpt2.py
def _add_transformer_prefix(
    weights: Iterable[tuple[str, torch.Tensor]]
) -> Iterable[tuple[str, torch.Tensor]]:
    for name, tensor in weights:
        if not name.startswith('transformer.') and not name.startswith(
                "lm_head"):
            name = 'transformer.' + name
        yield name, tensor