commit files to HF hub
Browse filesFiles changed (3)
- config.json+3-3
- configuration_phi3.py → configuration.pyRenamed+8-8
- modeling_phi3.py → modeling.pyRenamed+69-69
123456789101112{"_name_or_path": "Phi-3-mini-4k-instruct","architectures": ["Phi3ForCausalLM"],"attention_dropout": 0.0,"auto_map": {"AutoConfig": "configuration_phi3.Phi3Config","AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"},"bos_token_id": 1,"embd_pdrop": 0.0,123456789101112{"_name_or_path": "PersianStories-4k","architectures": ["Phi3ForCausalLM"],"attention_dropout": 0.0,"auto_map": {"AutoConfig": "configuration.Phi3Config","AutoModelForCausalLM": "modeling.Phi3ForCausalLM"},"bos_token_id": 1,"embd_pdrop": 0.0,
21 unmodified lines2223242526272829303132333435364 unmodified lines4142434445464751 unmodified lines9910010110210310410510610710810911011111211311411511611721 unmodified lineslogger = logging.get_logger(__name__)PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {"microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json","microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",}class Phi3Config(PretrainedConfig):r"""This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3model according to the specified arguments, defining the model architecture. Instantiating a configuration with thedefaults will yield a similar configuration to that of the[microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).4 unmodified linesArgs:vocab_size (`int`, *optional*, defaults to 32064):Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the`inputs_ids` passed when calling [`Phi3Model`].hidden_size (`int`, *optional*, defaults to 3072):Dimension of the hidden representations.intermediate_size (`int`, *optional*, defaults to 8192):51 unmodified linesExample:```python>>> from transformers import Phi3Model, Phi3Config>>> # Initializing a Phi-3 style configuration>>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")>>> # Initializing a model from the configuration>>> model = Phi3Model(configuration)>>> # Accessing the model configuration>>> configuration = model.config```"""model_type = "phi3"keys_to_ignore_at_inference = ["past_key_values"]def __init__(21 unmodified lines2223242526272829303132333435364 unmodified lines4142434445464751 unmodified lines9910010110210310410510610710810911011111211311411511611721 unmodified lineslogger = logging.get_logger(__name__)PersianStories_PRETRAINED_CONFIG_ARCHIVE_MAP = {"microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json","microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",}class PersianStoriesConfig(PretrainedConfig):r"""This is the configuration class to store the configuration of a [`PersianStoriesModel`]. It is used to instantiate a Phi-3model according to the specified arguments, defining the model architecture. Instantiating a configuration with thedefaults will yield a similar configuration to that of the[microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).4 unmodified linesArgs:vocab_size (`int`, *optional*, defaults to 32064):Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the`inputs_ids` passed when calling [`PersianStoriesModel`].hidden_size (`int`, *optional*, defaults to 3072):Dimension of the hidden representations.intermediate_size (`int`, *optional*, defaults to 8192):51 unmodified linesExample:```python>>> from transformers import PersianStoriesModel, PersianStoriesConfig>>> # Initializing a Phi-3 style configuration>>> configuration = PersianStoriesConfig.from_pretrained("microsoft/Phi-3-mini-4k-instruct")>>> # Initializing a model from the configuration>>> model = PersianStoriesModel(configuration)>>> # Accessing the model configuration>>> configuration = model.config```"""model_type = "PersianStories"keys_to_ignore_at_inference = ["past_key_values"]def __init__(
44 unmodified lines4546474849505116 unmodified lines686970717273747576777879808182838485868720 unmodified lines10810911011111211311411523 unmodified lines13914014114214314414570 unmodified lines21621721821922022122225 unmodified lines24824925025125225325425525625729 unmodified lines2872882892902912922931 unmodified line29529629729829930030179 unmodified lines38138238338438538638738838917 unmodified lines407408409410411412413276 unmodified lines6906916926936946956966976986997007017027037047056 unmodified lines71271371471571671771862 unmodified lines78178278378478578678778878979079179279379479579679779879980080180280380480580659 unmodified lines8668678688698708718723 unmodified lines8768778788798808818822 unmodified lines88588688788888989089189289389489589689713 unmodified lines91191291391491591691765 unmodified lines9839849859869879889899909919929939949959969979989991 unmodified line10011002100310041005100610071008100910105 unmodified lines101610171018101910201021102256 unmodified lines107910801081108210831084108568 unmodified lines115411551156115711581159116011611162116311641165116625 unmodified lines119211931194119511961197119820 unmodified lines121912201221122212231224122512261227123 unmodified lines1351135213531354135513561357135813592 unmodified lines136213631364136513661367136813691370137113721373137413755 unmodified lines138113821383138413851386138787 unmodified lines1475147614771478147914801481148214831484148514861487148814891490149114926 unmodified lines149915001501150215031504150544 unmodified lineslogging,replace_return_docstrings,)from .configuration_phi3 import Phi3Configlogger = logging.get_logger(__name__)16 unmodified lines)_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"_CONFIG_FOR_DOC = "Phi3Config"PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = ["microsoft/Phi-3-mini-4k-instruct","microsoft/Phi-3-mini-128k-instruct",# See all Phi-3 models at https://huggingface.co/models?filter=Phi-3]# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3class Phi3RMSNorm(nn.Module):def __init__(self, hidden_size, eps=1e-6):"""Phi3RMSNorm is equivalent to T5LayerNorm"""super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))20 unmodified lines)# Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3class Phi3RotaryEmbedding(nn.Module):def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):super().__init__()23 unmodified linesreturn cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)class Phi3LongRoPEScaledRotaryEmbedding(Phi3RotaryEmbedding):def __init__(self, dim, config, device=None):super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)70 unmodified linesreturn q_embed, k_embedclass Phi3MLP(nn.Module):def __init__(self, config):super().__init__()25 unmodified linesreturn hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)class Phi3Attention(nn.Module):"""Multi-headed attention from 'Attention Is All You Need' paper"""def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):super().__init__()self.config = configself.layer_idx = layer_idx29 unmodified linesdef _init_rope(self):if self.rope_scaling is None:self.rotary_emb = Phi3RotaryEmbedding(self.head_dim,max_position_embeddings=self.max_position_embeddings,base=self.rope_theta,1 unmodified lineelse:scaling_type = self.config.rope_scaling["type"]if scaling_type == "longrope":self.rotary_emb = Phi3LongRoPEScaledRotaryEmbedding(self.head_dim, self.config)else:raise ValueError(f"Unknown RoPE scaling type {scaling_type}")79 unmodified linesreturn attn_output, attn_weights, past_key_valueclass Phi3FlashAttention2(Phi3Attention):"""Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module staysuntouched. The only required change would be on the forward pass where it needs to correctly call the public API offlash attention and deal with padding tokens in case the input contains any of them."""17 unmodified linesuse_cache: bool = False,**kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:# Phi3FlashAttention2 attention does not support output_attentionsif not _flash_supports_window_size:logger.warning_once(276 unmodified lines)# copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3# TODO @Arthur no longer copied from LLama after static cacheclass Phi3SdpaAttention(Phi3Attention):"""Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from`Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt toSDPA API."""# Adapted from Phi3Attention.forwarddef forward(self,hidden_states: torch.Tensor,6 unmodified linesif output_attentions:# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.logger.warning_once("Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.')return super().forward(62 unmodified linesreturn attn_output, None, past_key_valuePHI3_ATTENTION_CLASSES = {"eager": Phi3Attention,"flash_attention_2": Phi3FlashAttention2,"sdpa": Phi3SdpaAttention,}class Phi3DecoderLayer(nn.Module):def __init__(self, config: Phi3Config, layer_idx: int):super().__init__()self.config = configself.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)self.mlp = Phi3MLP(config)self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)def forward(self,59 unmodified linesreturn outputsPHI3_START_DOCSTRING = r"""This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)3 unmodified linesand behavior.Parameters:config ([`Phi3Config`]):Model configuration class with all the parameters of the model. Initializing with a config file does notload the weights associated with the model, only the configuration. Check out the[`~PreTrainedModel.from_pretrained`] method to load the model weights.2 unmodified lines@add_start_docstrings("The bare Phi-3 model outputting raw hidden-states without any specific head on top.",PHI3_START_DOCSTRING,)class Phi3PreTrainedModel(PreTrainedModel):config_class = Phi3Configbase_model_prefix = "model"supports_gradient_checkpointing = True_no_split_modules = ["Phi3DecoderLayer"]_skip_keys_device_placement = "past_key_values"_supports_flash_attn_2 = True_supports_sdpa = False13 unmodified linesmodule.weight.data[module.padding_idx].zero_()PHI3_INPUTS_DOCSTRING = r"""Args:input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide65 unmodified lines@add_start_docstrings("The bare Phi-3 model outputting raw hidden-states without any specific head on top.",PHI3_START_DOCSTRING,)class Phi3Model(Phi3PreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]Args:config: Phi3Config"""def __init__(self, config: Phi3Config):super().__init__(config)self.padding_idx = config.pad_token_idself.vocab_size = config.vocab_size1 unmodified lineself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)self.embed_dropout = nn.Dropout(config.embd_pdrop)self.layers = nn.ModuleList([Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])self._attn_implementation = config._attn_implementationself.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.gradient_checkpointing = False# Initialize weights and apply final processing5 unmodified linesdef set_input_embeddings(self, value):self.embed_tokens = value@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)def forward(self,input_ids: torch.LongTensor = None,56 unmodified linesif is_padding_right:raise ValueError("You are attempting to perform batched generation with padding_side='right'"" this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "" call `tokenizer.padding_side = 'left'` before tokenizing the input. ")68 unmodified lines)class Phi3ForCausalLM(Phi3PreTrainedModel):_tied_weights_keys = ["lm_head.weight"]# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3def __init__(self, config):super().__init__(config)self.model = Phi3Model(config)self.vocab_size = config.vocab_sizeself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)25 unmodified linesreturn self.model# Ignore copy@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)def forward(self,20 unmodified linesExample:```python>>> from transformers import AutoTokenizer, Phi3ForCausalLM>>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")>>> prompt = "This is an example script ."123 unmodified lines@add_start_docstrings("""The [`Phi3Model`] with a sequence classification head on top (linear layer).[`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models(e.g. GPT-2) do.Since it does classification on the last token, it requires to know the position of the last token. If a2 unmodified linespadding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value ineach row of the batch).""",PHI3_START_DOCSTRING,)# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputsclass Phi3ForSequenceClassification(Phi3PreTrainedModel):def __init__(self, config):super().__init__(config)self.num_labels = config.num_labelsself.model = Phi3Model(config)self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)# Initialize weights and apply final processing5 unmodified linesdef set_input_embeddings(self, value):self.model.embed_tokens = value@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)def forward(self,input_ids: torch.LongTensor = None,87 unmodified lines@add_start_docstrings("""[`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. forNamed-Entity-Recognition (NER) tasks.""",PHI3_START_DOCSTRING,)# Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputsclass Phi3ForTokenClassification(Phi3PreTrainedModel):def __init__(self, config: Phi3Config):super().__init__(config)self.num_labels = config.num_labelsself.model = Phi3Model(config)if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:classifier_dropout = config.classifier_dropoutelif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:6 unmodified lines# Initialize weights and apply final processingself.post_init()@add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)@add_code_sample_docstrings(checkpoint=_CHECKPOINT_FOR_DOC,output_type=TokenClassifierOutput,44 unmodified lines4546474849505116 unmodified lines686970717273747576777879808182838485868720 unmodified lines10810911011111211311411523 unmodified lines13914014114214314414570 unmodified lines21621721821922022122225 unmodified lines24824925025125225325425525625729 unmodified lines2872882892902912922931 unmodified line29529629729829930030179 unmodified lines38138238338438538638738838917 unmodified lines407408409410411412413276 unmodified lines6906916926936946956966976986997007017027037047056 unmodified lines71271371471571671771862 unmodified lines78178278378478578678778878979079179279379479579679779879980080180280380480580659 unmodified lines8668678688698708718723 unmodified lines8768778788798808818822 unmodified lines88588688788888989089189289389489589689713 unmodified lines91191291391491591691765 unmodified lines9839849859869879889899909919929939949959969979989991 unmodified line10011002100310041005100610071008100910105 unmodified lines101610171018101910201021102256 unmodified lines107910801081108210831084108568 unmodified lines115411551156115711581159116011611162116311641165116625 unmodified lines119211931194119511961197119820 unmodified lines121912201221122212231224122512261227123 unmodified lines1351135213531354135513561357135813592 unmodified lines136213631364136513661367136813691370137113721373137413755 unmodified lines138113821383138413851386138787 unmodified lines1475147614771478147914801481148214831484148514861487148814891490149114926 unmodified lines149915001501150215031504150544 unmodified lineslogging,replace_return_docstrings,)from .configuration import PersianStoriesConfiglogger = logging.get_logger(__name__)16 unmodified lines)_CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"_CONFIG_FOR_DOC = "PersianStoriesConfig"PersianStories_PRETRAINED_MODEL_ARCHIVE_LIST = ["microsoft/Phi-3-mini-4k-instruct","microsoft/Phi-3-mini-128k-instruct",# See all Phi-3 models at https://huggingface.co/models?filter=Phi-3]# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->PersianStoriesclass PersianStoriesRMSNorm(nn.Module):def __init__(self, hidden_size, eps=1e-6):"""PersianStoriesRMSNorm is equivalent to T5LayerNorm"""super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))20 unmodified lines)# Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->PersianStories, Gemma->PersianStoriesclass PersianStoriesRotaryEmbedding(nn.Module):def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):super().__init__()23 unmodified linesreturn cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)class PersianStoriesLongRoPEScaledRotaryEmbedding(PersianStoriesRotaryEmbedding):def __init__(self, dim, config, device=None):super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)70 unmodified linesreturn q_embed, k_embedclass PersianStoriesMLP(nn.Module):def __init__(self, config):super().__init__()25 unmodified linesreturn hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)class PersianStoriesAttention(nn.Module):"""Multi-headed attention from 'Attention Is All You Need' paper"""def __init__(self, config: PersianStoriesConfig, layer_idx: Optional[int] = None):super().__init__()self.config = configself.layer_idx = layer_idx29 unmodified linesdef _init_rope(self):if self.rope_scaling is None:self.rotary_emb = PersianStoriesRotaryEmbedding(self.head_dim,max_position_embeddings=self.max_position_embeddings,base=self.rope_theta,1 unmodified lineelse:scaling_type = self.config.rope_scaling["type"]if scaling_type == "longrope":self.rotary_emb = PersianStoriesLongRoPEScaledRotaryEmbedding(self.head_dim, self.config)else:raise ValueError(f"Unknown RoPE scaling type {scaling_type}")79 unmodified linesreturn attn_output, attn_weights, past_key_valueclass PersianStoriesFlashAttention2(PersianStoriesAttention):"""Phi-3 flash attention module. This module inherits from `PersianStoriesAttention` as the weights of the module staysuntouched. The only required change would be on the forward pass where it needs to correctly call the public API offlash attention and deal with padding tokens in case the input contains any of them."""17 unmodified linesuse_cache: bool = False,**kwargs,) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:# PersianStoriesFlashAttention2 attention does not support output_attentionsif not _flash_supports_window_size:logger.warning_once(276 unmodified lines)# copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->PersianStories# TODO @Arthur no longer copied from LLama after static cacheclass PersianStoriesSdpaAttention(PersianStoriesAttention):"""PersianStories attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from`PersianStoriesAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt toSDPA API."""# Adapted from PersianStoriesAttention.forwarddef forward(self,hidden_states: torch.Tensor,6 unmodified linesif output_attentions:# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.logger.warning_once("PersianStoriesModel is using PersianStoriesSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.')return super().forward(62 unmodified linesreturn attn_output, None, past_key_valuePersianStories_ATTENTION_CLASSES = {"eager": PersianStoriesAttention,"flash_attention_2": PersianStoriesFlashAttention2,"sdpa": PersianStoriesSdpaAttention,}class PersianStoriesDecoderLayer(nn.Module):def __init__(self, config: PersianStoriesConfig, layer_idx: int):super().__init__()self.config = configself.self_attn = PersianStories_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)self.mlp = PersianStoriesMLP(config)self.input_layernorm = PersianStoriesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)self.post_attention_layernorm = PersianStoriesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)def forward(self,59 unmodified linesreturn outputsPersianStories_START_DOCSTRING = r"""This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)3 unmodified linesand behavior.Parameters:config ([`PersianStoriesConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does notload the weights associated with the model, only the configuration. Check out the[`~PreTrainedModel.from_pretrained`] method to load the model weights.2 unmodified lines@add_start_docstrings("The bare Phi-3 model outputting raw hidden-states without any specific head on top.",PersianStories_START_DOCSTRING,)class PersianStoriesPreTrainedModel(PreTrainedModel):config_class = PersianStoriesConfigbase_model_prefix = "model"supports_gradient_checkpointing = True_no_split_modules = ["PersianStoriesDecoderLayer"]_skip_keys_device_placement = "past_key_values"_supports_flash_attn_2 = True_supports_sdpa = False13 unmodified linesmodule.weight.data[module.padding_idx].zero_()PersianStories_INPUTS_DOCSTRING = r"""Args:input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide65 unmodified lines@add_start_docstrings("The bare Phi-3 model outputting raw hidden-states without any specific head on top.",PersianStories_START_DOCSTRING,)class PersianStoriesModel(PersianStoriesPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PersianStoriesDecoderLayer`]Args:config: PersianStoriesConfig"""def __init__(self, config: PersianStoriesConfig):super().__init__(config)self.padding_idx = config.pad_token_idself.vocab_size = config.vocab_size1 unmodified lineself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)self.embed_dropout = nn.Dropout(config.embd_pdrop)self.layers = nn.ModuleList([PersianStoriesDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])self._attn_implementation = config._attn_implementationself.norm = PersianStoriesRMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.gradient_checkpointing = False# Initialize weights and apply final processing5 unmodified linesdef set_input_embeddings(self, value):self.embed_tokens = value@add_start_docstrings_to_model_forward(PersianStories_INPUTS_DOCSTRING)def forward(self,input_ids: torch.LongTensor = None,56 unmodified linesif is_padding_right:raise ValueError("You are attempting to perform batched generation with padding_side='right'"" this may lead to unexpected behaviour for Flash Attention version of PersianStories. Make sure to "" call `tokenizer.padding_side = 'left'` before tokenizing the input. ")68 unmodified lines)class PersianStoriesForCausalLM(PersianStoriesPreTrainedModel):_tied_weights_keys = ["lm_head.weight"]# Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->PersianStoriesdef __init__(self, config):super().__init__(config)self.model = PersianStoriesModel(config)self.vocab_size = config.vocab_sizeself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)25 unmodified linesreturn self.model# Ignore copy@add_start_docstrings_to_model_forward(PersianStories_INPUTS_DOCSTRING)@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)def forward(self,20 unmodified linesExample:```python>>> from transformers import AutoTokenizer, PersianStoriesForCausalLM>>> model = PersianStoriesForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")>>> prompt = "This is an example script ."123 unmodified lines@add_start_docstrings("""The [`PersianStoriesModel`] with a sequence classification head on top (linear layer).[`PersianStoriesForSequenceClassification`] uses the last token in order to do the classification, as other causal models(e.g. GPT-2) do.Since it does classification on the last token, it requires to know the position of the last token. If a2 unmodified linespadding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value ineach row of the batch).""",PersianStories_START_DOCSTRING,)# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->PersianStories, LLAMA->PersianStories, self.transformer->self.model, transformer_outputs->model_outputsclass PersianStoriesForSequenceClassification(PersianStoriesPreTrainedModel):def __init__(self, config):super().__init__(config)self.num_labels = config.num_labelsself.model = PersianStoriesModel(config)self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)# Initialize weights and apply final processing5 unmodified linesdef set_input_embeddings(self, value):self.model.embed_tokens = value@add_start_docstrings_to_model_forward(PersianStories_INPUTS_DOCSTRING)def forward(self,input_ids: torch.LongTensor = None,87 unmodified lines@add_start_docstrings("""[`PersianStoriesModel`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. forNamed-Entity-Recognition (NER) tasks.""",PersianStories_START_DOCSTRING,)# Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->PersianStories,MPT->PersianStories,self.transformer->self.model,transformer_outputs->model_outputsclass PersianStoriesForTokenClassification(PersianStoriesPreTrainedModel):def __init__(self, config: PersianStoriesConfig):super().__init__(config)self.num_labels = config.num_labelsself.model = PersianStoriesModel(config)if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:classifier_dropout = config.classifier_dropoutelif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:6 unmodified lines# Initialize weights and apply final processingself.post_init()@add_start_docstrings_to_model_forward(PersianStories_INPUTS_DOCSTRING)@add_code_sample_docstrings(checkpoint=_CHECKPOINT_FOR_DOC,output_type=TokenClassifierOutput,
config.json+3-3
configuration_phi3.py → configuration.pyRenamed+8-8
modeling_phi3.py → modeling.pyRenamed+69-69