CoolFace
Modelpublic

FreedomIntelligence/openPangu-Embedded-1B

sourceHugging Faceotherupdated 1y agoView on Hugging Face
6likes74downloads
modeling_openpangu_dense.py586 linesDownload Raw Back to root
1#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ2#                       This file was automatically generated from modular_openpangu_dense.py.3#               Do NOT edit this file manually as any edits will be overwritten by the generation of4#             the file from the modular. If any change should be done, please apply the change to the5#                          modular_openpangu_dense.py file directly. One of our CI enforces this.6#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ7 8# coding=utf-89# Copyright (c) 2025 Huawei Technologies Co., Ltd. All rights reserved.10# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.11#12# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX13# and OPT implementations in this library. It has been modified from its14# original forms to accommodate minor architectural differences compared15# to GPT-NeoX and OPT used by the Meta AI team that trained the model.16#17# Licensed under the Apache License, Version 2.0 (the "License");18# you may not use this file except in compliance with the License.19# You may obtain a copy of the License at20#21#     http://www.apache.org/licenses/LICENSE-2.022#23# Unless required by applicable law or agreed to in writing, software24# distributed under the License is distributed on an "AS IS" BASIS,25# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26# See the License for the specific language governing permissions and27# limitations under the License.28 29from typing import Callable, Optional, Union30 31import torch32from torch import nn33 34try:35    import torch_npu36    from torch_npu.contrib import transfer_to_npu37    if "910" in torch.npu.get_device_name():38        NPU_ATTN_INFR = True39        print("[INFO] torch_npu detected. Using NPU fused infer attention.")40except ImportError:41    NPU_ATTN_INFR = False42 43from transformers.activations import ACT2FN44from transformers.cache_utils import Cache, DynamicCache45from transformers.generation import GenerationMixin46from transformers.masking_utils import create_causal_mask47from transformers.modeling_flash_attention_utils import FlashAttentionKwargs48from transformers.modeling_layers import GradientCheckpointingLayer49from transformers.modeling_outputs import (50    BaseModelOutputWithPast,51    CausalLMOutputWithPast,52    SequenceClassifierOutputWithPast,53)54from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update55from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel56from transformers.processing_utils import Unpack57from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, logging58from .configuration_openpangu_dense import PanguEmbeddedConfig59 60 61logger = logging.get_logger(__name__)62 63 64class PanguEmbeddedRMSNorm(nn.Module):65    def __init__(self, hidden_size, eps=1e-6):66        """67        PanguEmbeddedRMSNorm is equivalent to T5LayerNorm68        """69        super().__init__()70        self.weight = nn.Parameter(torch.ones(hidden_size))71        self.variance_epsilon = eps72 73    def forward(self, hidden_states):74        input_dtype = hidden_states.dtype75        hidden_states = hidden_states.to(torch.float32)76        variance = hidden_states.pow(2).mean(-1, keepdim=True)77        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)78        return self.weight * hidden_states.to(input_dtype)79 80    def extra_repr(self):81        return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"82 83 84class PanguEmbeddedRotaryEmbedding(nn.Module):85    def __init__(self, config: PanguEmbeddedConfig, device=None):86        super().__init__()87        # BC: "rope_type" was originally "type"88        if hasattr(config, "rope_scaling") and config.rope_scaling is not None:89            self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))90        else:91            self.rope_type = "default"92        self.max_seq_len_cached = config.max_position_embeddings93        self.original_max_seq_len = config.max_position_embeddings94 95        self.config = config96        self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]97 98        inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)99        self.register_buffer("inv_freq", inv_freq, persistent=False)100        self.original_inv_freq = self.inv_freq101 102    @torch.no_grad()103    @dynamic_rope_update  # power user: used with advanced RoPE types (e.g. dynamic rope)104    def forward(self, x, position_ids):105        inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)106        position_ids_expanded = position_ids[:, None, :].float()107 108        device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"109        with torch.autocast(device_type=device_type, enabled=False):  # Force float32110            freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)111            emb = torch.cat((freqs, freqs), dim=-1)112            cos = emb.cos() * self.attention_scaling113            sin = emb.sin() * self.attention_scaling114 115        return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)116 117 118def rotate_half(x):119    """Rotates half the hidden dims of the input."""120    x1 = x[..., : x.shape[-1] // 2]121    x2 = x[..., x.shape[-1] // 2 :]122    return torch.cat((-x2, x1), dim=-1)123 124 125def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):126    """Applies Rotary Position Embedding to the query and key tensors.127 128    Args:129        q (`torch.Tensor`): The query tensor.130        k (`torch.Tensor`): The key tensor.131        cos (`torch.Tensor`): The cosine part of the rotary embedding.132        sin (`torch.Tensor`): The sine part of the rotary embedding.133        position_ids (`torch.Tensor`, *optional*):134            Deprecated and unused.135        unsqueeze_dim (`int`, *optional*, defaults to 1):136            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and137            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note138            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and139            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes140            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have141            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.142    Returns:143        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.144    """145    cos = cos.unsqueeze(unsqueeze_dim)146    sin = sin.unsqueeze(unsqueeze_dim)147    q_embed = (q * cos) + (rotate_half(q) * sin)148    k_embed = (k * cos) + (rotate_half(k) * sin)149    return q_embed, k_embed150 151 152class PanguEmbeddedMLP(nn.Module):153    def __init__(self, config):154        super().__init__()155        self.config = config156        self.hidden_size = config.hidden_size157        self.intermediate_size = config.intermediate_size158        self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)159        self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)160        self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)161        self.act_fn = ACT2FN[config.hidden_act]162 163    def forward(self, x):164        down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))165        return down_proj166 167 168def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:169    """170    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,171    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)172    """173    batch, num_key_value_heads, slen, head_dim = hidden_states.shape174    if n_rep == 1:175        return hidden_states176    hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)177    return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)178 179 180def eager_attention_forward(181    module: nn.Module,182    query: torch.Tensor,183    key: torch.Tensor,184    value: torch.Tensor,185    attention_mask: Optional[torch.Tensor],186    scaling: float,187    dropout: float = 0.0,188    **kwargs,189):190    key_states = repeat_kv(key, module.num_key_value_groups)191    value_states = repeat_kv(value, module.num_key_value_groups)192 193    attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling194    if attention_mask is not None:195        causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]196        attn_weights = attn_weights + causal_mask197 198    attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)199    attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)200    attn_output = torch.matmul(attn_weights, value_states)201    attn_output = attn_output.transpose(1, 2).contiguous()202 203    return attn_output, attn_weights204 205 206class PanguEmbeddedAttention(nn.Module):207    """Multi-headed attention from 'Attention Is All You Need' paper"""208 209    def __init__(self, config: PanguEmbeddedConfig, layer_idx: int):210        super().__init__()211        self.config = config212        self.layer_idx = layer_idx213        self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)214        self.num_heads = config.num_attention_heads215        self.num_key_value_heads = config.num_key_value_heads216        self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads217        self.scaling = self.head_dim**-0.5218        self.attention_dropout = config.attention_dropout219        self.is_causal = True220 221        self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.bias)222        self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.bias)223        self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.bias)224        self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.bias)225 226    def forward(227        self,228        hidden_states: torch.Tensor,229        position_embeddings: tuple[torch.Tensor, torch.Tensor],230        attention_mask: Optional[torch.Tensor],231        past_key_value: Optional[Cache] = None,232        cache_position: Optional[torch.LongTensor] = None,233        **kwargs: Unpack[FlashAttentionKwargs],234    ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:235        input_shape = hidden_states.shape[:-1]236        hidden_shape = (*input_shape, -1, self.head_dim)237 238        query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)239        key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)240        value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)241 242        cos, sin = position_embeddings243        query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)244 245        if past_key_value is not None:246            # sin and cos are specific to RoPE models; cache_position needed for the static cache247            cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}248            key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)249 250        attention_interface: Callable = eager_attention_forward251        if self.config._attn_implementation != "eager":252            attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]253        254        if not self.training and NPU_ATTN_INFR:255            q_len = input_shape[1]256            if attention_mask is not None:257                attention_mask = ~attention_mask.bool()258            elif q_len > 1:259                attention_mask = torch.triu(torch.ones([q_len, q_len]), diagonal=1).bool().unsqueeze(0).unsqueeze(0).to(query_states.device)260 261            attn_output, _ = torch_npu.npu_fused_infer_attention_score(262                query_states, key_states, value_states,263                num_heads=self.num_heads, num_key_value_heads=self.num_key_value_heads,264                input_layout="BNSD", atten_mask=attention_mask, scale=self.scaling)265            attn_output = attn_output.transpose(1, 2)266            attn_weights = None267        else:268            attn_output, attn_weights = attention_interface(269                self,270                query_states,271                key_states,272                value_states,273                attention_mask,274                dropout=0.0 if not self.training else self.attention_dropout,275                scaling=self.scaling,276                **kwargs,277            )278 279        attn_output = attn_output.reshape(*input_shape, -1).contiguous()280        attn_output = self.o_proj(attn_output)281        return attn_output, attn_weights282 283 284class PanguEmbeddedDecoderLayer(GradientCheckpointingLayer):285    def __init__(self, config: PanguEmbeddedConfig, layer_idx: int):286        super().__init__()287        self.hidden_size = config.hidden_size288        self.self_attn = PanguEmbeddedAttention(config=config, layer_idx=layer_idx)289        self.mlp = PanguEmbeddedMLP(config)290        self.input_layernorm = PanguEmbeddedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)291        self.post_attention_layernorm = PanguEmbeddedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)292 293    def forward(294        self,295        hidden_states: torch.Tensor,296        attention_mask: Optional[torch.Tensor] = None,297        position_ids: Optional[torch.LongTensor] = None,298        past_key_value: Optional[Cache] = None,299        output_attentions: Optional[bool] = False,300        use_cache: Optional[bool] = False,301        cache_position: Optional[torch.LongTensor] = None,302        position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,  # necessary, but kept here for BC303        **kwargs: Unpack[FlashAttentionKwargs],304    ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:305        residual = hidden_states306        hidden_states = self.input_layernorm(hidden_states)307 308        # Self Attention309        hidden_states, self_attn_weights = self.self_attn(310            hidden_states=hidden_states,311            attention_mask=attention_mask,312            position_ids=position_ids,313            past_key_value=past_key_value,314            output_attentions=output_attentions,315            use_cache=use_cache,316            cache_position=cache_position,317            position_embeddings=position_embeddings,318            **kwargs,319        )320        hidden_states = residual + hidden_states321 322        # Fully Connected323        residual = hidden_states324        hidden_states = self.post_attention_layernorm(hidden_states)325        hidden_states = self.mlp(hidden_states)326        hidden_states = residual + hidden_states327 328        outputs = (hidden_states,)329        if output_attentions:330            outputs += (self_attn_weights,)331 332        return outputs333 334 335@auto_docstring336class PanguEmbeddedPreTrainedModel(PreTrainedModel):337    config_class = PanguEmbeddedConfig338    base_model_prefix = "model"339    supports_gradient_checkpointing = True340    _no_split_modules = ["PanguEmbeddedDecoderLayer"]341    _skip_keys_device_placement = ["past_key_values"]342    _supports_flash_attn_3 = True343    _supports_flash_attn_2 = True344    _supports_sdpa = True345    _supports_flex_attn = True346    _supports_cache_class = True347    _supports_quantized_cache = True348    _supports_static_cache = True349    _supports_attention_backend = True350 351    def _init_weights(self, module):352        std = self.config.initializer_range353        if isinstance(module, nn.Linear):354            module.weight.data.normal_(mean=0.0, std=std)355            if module.bias is not None:356                module.bias.data.zero_()357        elif isinstance(module, nn.Embedding):358            module.weight.data.normal_(mean=0.0, std=std)359            if module.padding_idx is not None:360                module.weight.data[module.padding_idx].zero_()361        elif isinstance(module, PanguEmbeddedRMSNorm):362            module.weight.data.fill_(1.0)363 364 365@auto_docstring366class PanguEmbeddedModel(PanguEmbeddedPreTrainedModel):367    def __init__(self, config: PanguEmbeddedConfig):368        super().__init__(config)369        self.padding_idx = config.pad_token_id370        self.vocab_size = config.vocab_size371 372        self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)373        self.layers = nn.ModuleList(374            [PanguEmbeddedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]375        )376        self.norm = PanguEmbeddedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)377        self.rotary_emb = PanguEmbeddedRotaryEmbedding(config=config)378        self.gradient_checkpointing = False379 380        # Initialize weights and apply final processing381        self.post_init()382 383    def get_input_embeddings(self):384        return self.embed_tokens385 386    def set_input_embeddings(self, value):387        self.embed_tokens = value388 389    @can_return_tuple390    @auto_docstring391    def forward(392        self,393        input_ids: Optional[torch.LongTensor] = None,394        attention_mask: Optional[torch.Tensor] = None,395        position_ids: Optional[torch.LongTensor] = None,396        past_key_values: Optional[Cache] = None,397        inputs_embeds: Optional[torch.FloatTensor] = None,398        use_cache: Optional[bool] = None,399        output_attentions: Optional[bool] = None,400        output_hidden_states: Optional[bool] = None,401        cache_position: Optional[torch.LongTensor] = None,402        **flash_attn_kwargs: Unpack[FlashAttentionKwargs],403    ) -> BaseModelOutputWithPast:404        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions405        output_hidden_states = (406            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states407        )408        use_cache = use_cache if use_cache is not None else self.config.use_cache409 410        if (input_ids is None) ^ (inputs_embeds is not None):411            raise ValueError("You must specify exactly one of input_ids or inputs_embeds")412 413        if self.gradient_checkpointing and self.training and use_cache:414            logger.warning_once(415                "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."416            )417            use_cache = False418 419        # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache420        if not isinstance(past_key_values, (type(None), Cache)):421            raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")422 423        if inputs_embeds is None:424            inputs_embeds = self.embed_tokens(input_ids)425 426        if use_cache and past_key_values is None:427            past_key_values = DynamicCache()428 429        if cache_position is None:430            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0431            cache_position = torch.arange(432                past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device433            )434 435        if position_ids is None:436            position_ids = cache_position.unsqueeze(0)437 438        causal_mask = create_causal_mask(439            config=self.config,440            input_embeds=inputs_embeds,441            attention_mask=attention_mask,442            cache_position=cache_position,443            past_key_values=past_key_values,444            position_ids=position_ids,445        )446 447        hidden_states = inputs_embeds448 449        # create position embeddings to be shared across the decoder layers450        position_embeddings = self.rotary_emb(hidden_states, position_ids)451 452        # decoder layers453        all_hidden_states = () if output_hidden_states else None454        all_self_attns = () if output_attentions else None455 456        for decoder_layer in self.layers[: self.config.num_hidden_layers]:457            if output_hidden_states:458                all_hidden_states += (hidden_states,)459 460            layer_outputs = decoder_layer(461                hidden_states,462                attention_mask=causal_mask,463                position_ids=position_ids,464                past_key_value=past_key_values,465                output_attentions=output_attentions,466                use_cache=use_cache,467                cache_position=cache_position,468                position_embeddings=position_embeddings,469                **flash_attn_kwargs,470            )471 472            hidden_states = layer_outputs[0]473 474            if output_attentions:475                all_self_attns += (layer_outputs[1],)476 477        hidden_states = self.norm(hidden_states)478 479        # add hidden states from the last decoder layer480        if output_hidden_states:481            all_hidden_states += (hidden_states,)482 483        return BaseModelOutputWithPast(484            last_hidden_state=hidden_states,485            past_key_values=past_key_values if use_cache else None,486            hidden_states=all_hidden_states,487            attentions=all_self_attns,488        )489 490 491class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...492 493 494@auto_docstring495class PanguEmbeddedForCausalLM(PanguEmbeddedPreTrainedModel, GenerationMixin):496    _tied_weights_keys = ["lm_head.weight"]497    _tp_plan = {"lm_head": "colwise_rep"}498    _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}499 500    def __init__(self, config):501        super().__init__(config)502        self.model = PanguEmbeddedModel(config)503        self.vocab_size = config.vocab_size504        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)505 506        # Initialize weights and apply final processing507        self.post_init()508 509    def get_input_embeddings(self):510        return self.model.embed_tokens511 512    def set_input_embeddings(self, value):513        self.model.embed_tokens = value514 515    def get_output_embeddings(self):516        return self.lm_head517 518    def set_output_embeddings(self, new_embeddings):519        self.lm_head = new_embeddings520 521    def set_decoder(self, decoder):522        self.model = decoder523 524    def get_decoder(self):525        return self.model526 527    @can_return_tuple528    @auto_docstring529    def forward(530        self,531        input_ids: Optional[torch.LongTensor] = None,532        attention_mask: Optional[torch.Tensor] = None,533        position_ids: Optional[torch.LongTensor] = None,534        past_key_values: Optional[Cache] = None,535        inputs_embeds: Optional[torch.FloatTensor] = None,536        labels: Optional[torch.LongTensor] = None,537        use_cache: Optional[bool] = None,538        output_attentions: Optional[bool] = None,539        output_hidden_states: Optional[bool] = None,540        cache_position: Optional[torch.LongTensor] = None,541        logits_to_keep: Union[int, torch.Tensor] = 0,542        **kwargs: Unpack[KwargsForCausalLM],543    ) -> CausalLMOutputWithPast:544 545        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions546        output_hidden_states = (547            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states548        )549 550        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)551        outputs: BaseModelOutputWithPast = self.model(552            input_ids=input_ids,553            attention_mask=attention_mask,554            position_ids=position_ids,555            past_key_values=past_key_values,556            inputs_embeds=inputs_embeds,557            use_cache=use_cache,558            output_attentions=output_attentions,559            output_hidden_states=output_hidden_states,560            cache_position=cache_position,561            **kwargs,562        )563 564        hidden_states = outputs.last_hidden_state565        # Only compute necessary logits, and do not upcast them to float if we are not computing the loss566        slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep567        logits = self.lm_head(hidden_states[:, slice_indices, :])568 569        loss = None570        if labels is not None:571            loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)572 573        return CausalLMOutputWithPast(574            loss=loss,575            logits=logits,576            past_key_values=outputs.past_key_values,577            hidden_states=outputs.hidden_states,578            attentions=outputs.attentions,579        )580 581 582__all__ = [583    "PanguEmbeddedForCausalLM",584    "PanguEmbeddedModel",585    "PanguEmbeddedPreTrainedModel",586]