o
    ߥi.                     @   sT   d dl Z d dlZd dlmZ d dlmZ e ZG dd deZG dd deZ	dS )    N)PretrainedConfig)loggerc                       s   e Zd ZdZ												
														d# fdd	Zedd Zedd Zdd Zdd Z	dd  Z
d!d" Z  ZS )$PlugNLUConfigplugNLU T  R               gelu皙?      hn|?linear{Gz?      ?镲?TFh㈵>   c                    s   t  jdd|i| || _|| _|| _|| _|| _|| _|| _|| _	|	| _
|
| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _d S Nlayer_norm_eps )super__init__
vocab_sizeoriginal_vocab_sizehidden_sizenum_hidden_layersnum_attention_heads
hidden_actintermediate_sizehidden_dropout_probattention_probs_dropout_probmax_position_embeddingstype_vocab_sizeinitializer_rangelr_decay_styleweight_decay	clip_gradwarmuppre_lnfp16fp32_layernormfp32_embeddinglayernorm_epsilonfp32_tokentypesdec_hidden_layersattn_separate)selfr   r   r   r   r    r"   r!   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r1   r0   r2   r3   kwargs	__class__r   \/home/ubuntu/.local/lib/python3.10/site-packages/modelscope/models/nlp/plug/configuration.pyr      s2   
zPlugNLUConfig.__init__c                 C   s&   t  }| D ]	\}}||j|< q|S )zAConstructs a `BertConfig` from a Python dictionary of parameters.)r   items__dict__)clsjson_objectconfigkeyvaluer   r   r8   	from_dictS   s   zPlugNLUConfig.from_dictc                 C   sF   t |ddd}| }W d   n1 sw   Y  | t|S )z9Constructs a `BertConfig` from a json file of parameters.rzutf-8)encodingN)openreadr@   jsonloads)r;   	json_filereadertextr   r   r8   from_json_file[   s   
zPlugNLUConfig.from_json_filec                 C   s6   | j  }|j  D ]\}}||v rq
|| j |< q
| S )z;merge values a `BertConfig` from a json file of parameters.)r:   keysr9   )r4   args
local_keysr>   r?   r   r   r8   
merge_argsb   s   
zPlugNLUConfig.merge_argsc                 C   s   t |  S )N)strto_json_stringr4   r   r   r8   __repr__k   s   zPlugNLUConfig.__repr__c                 C   s   t | j}|S )z0Serializes this instance to a Python dictionary.)copydeepcopyr:   )r4   outputr   r   r8   to_dictn   s   zPlugNLUConfig.to_dictc                 C   s   t j|  dddd S )z*Serializes this instance to a JSON string.   T)indent	sort_keys
)rE   dumpsrV   rQ   r   r   r8   rP   s   s   zPlugNLUConfig.to_json_string)r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   TTTFFr   r   F)__name__
__module____qualname__
model_typer   classmethodr@   rJ   rN   rR   rV   rP   __classcell__r   r   r6   r8   r      sF    5

	r   c                       sV   e Zd ZdZdZ									
																d fdd	Z  ZS )PlugNLGConfiga  
    This is the configuration class to store the configuration of a [`PlugModel`]. It is used to instantiate a
    PLUG understanding model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the PLUG
    [PLUG](https://modelscope.cn/models/damo/nlp_plug_text-generation_27B/summary) architecture.

    Configuration objects inherit from [`PlugNLUConfig`] and can be used to control the model outputs. Read the
    documentation from [`PlugNLUConfig`] for more information.

    Args:
        vocab_size (`int`, *optional*, defaults to 21504):
            Padded vocabulary size of the PLUG model for vocab tensor parallel. Defines the number of different tokens
            that can be represented by the `inputs_ids` passed when calling [`PlugModel`].
        original_vocab_size (`int`, *optional*, defaults to 21128):
            True vocabulary size of the PLUG model. Defines the number of different tokens that can be represented.
        hidden_size (`int`, *optional*, defaults to 8192):
            Dimensionality of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 24):
            Number of hidden layers in the Transformer encoder.
        dec_hidden_layers (`int`, *optional*, defaults to 6):
            Number of hidden layers in the Transformer decoder.
        num_attention_heads (`int`, *optional*, defaults to 128):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (`int`, *optional*, defaults to 32768):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        hidden_act (`str`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` are supported.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout ratio for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the Transformer Attention.
        max_position_embeddings (`int`, *optional*, defaults to 2048):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        type_vocab_size (`int`, *optional*, defaults to 3):
            The vocabulary size of the `token_type_ids` passed when calling [`PlugModel`].
        initializer_range (`float`, *optional*, defaults to 0.00707):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        lr_decay_style (`str`, *optional*, defaults to 'linear'):
            The decay style of learning rate during fine-tunining. If string, `"linear"`, `"cosine"`, `"exponential"`,
            `"constant"`, `"None"` are supported.
        weight_decay (`float`, *optional*, defaults to 1e-2):
            Decoupled weight decay to apply.
        clip_grad (`float`, *optional*, defaults to 1.0):
            Maximum gradient norm for gradient clipping.
        warmup (`float`, *optional*, defaults to 0.01):
            Ratio of total training steps used for a linear warmup from 0 to `learning_rate`.
        pre_ln (`boolean`, *optional*, defaults to `True`):
            Whether or not to apply LayerNorm to the input instead of the output in the blocks.
        fp16 (`boolean`, *optional*, defaults to `True`):
            Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
        fp32_layernorm (`boolean`, *optional*, defaults to `True`):
            Whether to use fp32 32-bit precision LayerNorm training while the argument `fp16` set to `True`.
        fp32_embedding (`boolean`, *optional*, defaults to `False`):
            Whether to use fp32 32-bit precision Embedding training while the argument `fp16` set to `True`.
        fp32_tokentypes (`boolean`, *optional*, defaults to `False`):
            Whether to use fp32 32-bit precision token types training while the argument `fp16` set to `True`.
        layernorm_epsilon (`float`, *optional*, defaults to 1e-5):
            The epsilon to use in the layer normalization layers.
        attn_separate (`boolean`, *optional*, defaults to `False`):
            Whether or not to separate query-key-value to query, key, value in the Attention.

    Example:

    >>> # The PLUG model has 27B parameters and usually need to run on multiple GPUs. The example given
    >>> # here only initializes a slice of the model on a single GPU.
    >>> # Check out the [`~DistributedPipeline.__init__`] method to initialize entire PLUG model.
    >>> from modelscope.models.nlp.plug import PlugNLGConfig, PlugModel

    >>> # Initializing a Plug configuration
    >>> configuration = PlugNLGConfig()

    >>> # Initializing a model from the configuration
    >>> model = PlugModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    plugNLGr   r   r   r	   r   r
   r   r   r   r   r   r   r   r   r   TF-q=c                    s   t  jdd|i| || _|| _|| _|| _|| _|| _|	| _|
| _	|| _
|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _d S r   )r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   )r4   r   r   r   r   r2   r    r"   r!   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r1   r0   r3   r5   r6   r   r8   r      s0   
zPlugNLGConfig.__init__)r   r   r   r	   r   r
   r   r   r   r   r   r   r   r   r   r   r   TTTFFrd   F)r\   r]   r^   __doc__r_   r   ra   r   r   r6   r8   rb   x   s8    Prb   )
rS   rE   transformersr   modelscope.utilsr   logging
get_loggerr   rb   r   r   r   r8   <module>   s   ]