Movatterモバイル変換


[0]ホーム

URL:


Hugging Face's logoHugging Face

Transformers documentation

Phi

Transformers

You are viewingmain version, which requiresinstallation from source. If you'd likeregular pip install, checkout the latest stable version (v4.57.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

Collaborate on models, datasets and Spaces
Faster examples with accelerated inference
Switch between documentation themes

to get started

This model was released on 2023-06-20 and added to Hugging Face Transformers on 2023-11-10.

PyTorchFlashAttentionSDPATensor parallelism

Phi

Phi is a 1.3B parameter transformer model optimized for Python code generation. It focuses on “textbook-quality” training data of code examples, exercises and synthetic Python problems rather than scaling the model size or compute.

You can find all the original Phi checkpoints under thePhi-1 collection.

Click on the Phi models in the right sidebar for more examples of how to apply Phi to different language tasks.

The example below demonstrates how to generate text withPipeline,AutoModel and from the command line.

Pipeline
AutoModel
transformers CLI
import torchfrom transformersimport pipelinepipeline = pipeline(task="text-generation", model="microsoft/phi-1.5", device=0, dtype=torch.bfloat16)pipeline("pipeline('''def print_prime(n): """ Printall primes between1and n"""''')")

Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to theQuantization overview for more available quantization backends.

The example below usesbitsandbytes to only quantize the weights to 4-bits.

import torchfrom transformersimport BitsAndBytesConfig, AutoTokenizer, AutoModelForCausalLMbnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True)tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")model = AutoModelForCausalLM.from_pretrained("microsoft/phi-1", dtype=torch.float16, device_map="auto", attn_implementation="sdpa", quantization_config=bnb_config)input_ids = tokenizer('''def print_prime(n):   """   Print all primes between 1 and n   """''', return_tensors="pt").to(model.device)output = model.generate(**input_ids, cache_implementation="static")print(tokenizer.decode(output[0], skip_special_tokens=True))

Notes

  • If you’re using Transformers < 4.37.0.dev, settrust_remote_code=True infrom_pretrained(). Otherwise, make sure you update Transformers to the latest stable version.

    import torchfrom transformersimport AutoTokenizer, AutoModelForCausalLMtokenizer = AutoTokenizer.from_pretrained("microsoft/phi-1")model = AutoModelForCausalLM.from_pretrained("microsoft/phi-1",    dtype=torch.float16,    device_map="auto",    trust_remote_code=True,    attn_implementation="sdpa")input_ids = tokenizer('''def print_prime(n):   """   Print all primes between 1 and n   """''', return_tensors="pt").to(model.device)output = model.generate(**input_ids, cache_implementation="static")print(tokenizer.decode(output[0], skip_special_tokens=True))

PhiConfig

classtransformers.PhiConfig

<source>

(vocab_size: typing.Optional[int] = 51200hidden_size: typing.Optional[int] = 2048intermediate_size: typing.Optional[int] = 8192num_hidden_layers: typing.Optional[int] = 24num_attention_heads: typing.Optional[int] = 32num_key_value_heads: typing.Optional[int] = Noneresid_pdrop: typing.Optional[float] = 0.0embd_pdrop: typing.Optional[float] = 0.0attention_dropout: typing.Optional[float] = 0.0hidden_act: typing.Optional[str] = 'gelu_new'max_position_embeddings: typing.Optional[int] = 2048initializer_range: typing.Optional[float] = 0.02layer_norm_eps: typing.Optional[int] = 1e-05use_cache: typing.Optional[bool] = Truetie_word_embeddings: typing.Optional[bool] = Falserope_parameters: typing.Union[transformers.modeling_rope_utils.RopeParameters, dict[str, transformers.modeling_rope_utils.RopeParameters], NoneType] = Nonepartial_rotary_factor: typing.Optional[float] = 0.5qk_layernorm: typing.Optional[bool] = Falsebos_token_id: typing.Optional[int] = 1eos_token_id: typing.Optional[int] = 2**kwargs)

Parameters

  • vocab_size (int,optional, defaults to 51200) —Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by theinputs_ids passed when callingPhiModel.
  • hidden_size (int,optional, defaults to 2048) —Dimension of the hidden representations.
  • intermediate_size (int,optional, defaults to 8192) —Dimension of the MLP representations.
  • num_hidden_layers (int,optional, defaults to 24) —Number of hidden layers in the Transformer decoder.
  • num_attention_heads (int,optional, defaults to 32) —Number of attention heads for each attention layer in the Transformer decoder.
  • num_key_value_heads (int,optional) —This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. Whenconverting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructedby meanpooling all the original heads within that group. For more details, check outthispaper. If it is not specified, will default tonum_attention_heads.
  • resid_pdrop (float,optional, defaults to 0.0) —Dropout probability for mlp outputs.
  • embd_pdrop (int,optional, defaults to 0.0) —The dropout ratio for the embeddings.
  • attention_dropout (float,optional, defaults to 0.0) —The dropout ratio after computing the attention scores.
  • hidden_act (str orfunction,optional, defaults to"gelu_new") —The non-linear activation function (function or string) in the decoder.
  • max_position_embeddings (int,optional, defaults to 2048) —The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048tokens.
  • initializer_range (float,optional, defaults to 0.02) —The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  • layer_norm_eps (float,optional, defaults to 1e-05) —The epsilon used by the rms normalization layers.
  • use_cache (bool,optional, defaults toTrue) —Whether or not the model should return the last key/values attentions (not used by all models). Onlyrelevant ifconfig.is_decoder=True. Whether to tie weight embeddings or not.
  • tie_word_embeddings (bool,optional, defaults toFalse) —Whether to tie weight embeddings
  • rope_parameters (RopeParameters,optional) —Dictionary containing the configuration parameters for the RoPE embeddings. The dictionaty should containa value forrope_theta and optionally parameters used for scaling in case you want to use RoPEwith longermax_position_embeddings.
  • partial_rotary_factor (float,optional, defaults to 0.5) —Percentage of the query and keys which will have rotary embedding.
  • qk_layernorm (bool,optional, defaults toFalse) —Whether or not to normalize the Queries and Keys after projecting the hidden states.
  • bos_token_id (int,optional, defaults to 1) —Denotes beginning of sequences token id.
  • eos_token_id (int,optional, defaults to 2) —Denotes end of sequences token id.

This is the configuration class to store the configuration of aPhiModel. It is used to instantiate an Phimodel according to the specified arguments, defining the model architecture. Instantiating a configuration with thedefaults will yield a similar configuration to that of the Phimicrosoft/phi-1.

Configuration objects inherit fromPreTrainedConfig and can be used to control the model outputs. Read thedocumentation fromPreTrainedConfig for more information.

Example:

>>>from transformersimport PhiModel, PhiConfig>>># Initializing a Phi-1 style configuration>>>configuration = PhiConfig.from_pretrained("microsoft/phi-1")>>># Initializing a model from the configuration>>>model = PhiModel(configuration)>>># Accessing the model configuration>>>configuration = model.config

PhiModel

classtransformers.PhiModel

<source>

(config: PhiConfig)

Parameters

  • config (PhiConfig) —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 thefrom_pretrained() method to load the model weights.

The bare Phi Model outputting raw hidden-states without any specific head on top.

This model inherits fromPreTrainedModel. 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.)

This model is also a PyTorchtorch.nn.Module subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.

forward

<source>

(input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[transformers.cache_utils.Cache] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = None**kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs])transformers.modeling_outputs.BaseModelOutputWithPast ortuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained usingAutoTokenizer. SeePreTrainedTokenizer.encode() andPreTrainedTokenizer.call() for details.

    What are input IDs?

  • attention_mask (torch.Tensor of shape(batch_size, sequence_length),optional) —Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:

    • 1 for tokens that arenot masked,
    • 0 for tokens that aremasked.

    What are attention masks?

  • position_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].

    What are position IDs?

  • past_key_values (~cache_utils.Cache,optional) —Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=True orconfig.use_cache=True.

    OnlyCache instance is allowed as input, see ourkv cache guide.If nopast_key_values are passed,DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    Ifpast_key_values are used, the user is expected to input only unprocessedinput_ids (those that don’thave their past key value states given to this model) of shape(batch_size, unprocessed_length) instead of allinput_idsof shape(batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape(batch_size, sequence_length, hidden_size),optional) —Optionally, instead of passinginput_ids you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convertinput_ids indices into associated vectors than themodel’s internal embedding lookup matrix.
  • use_cache (bool,optional) —If set toTrue,past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).
  • output_attentions (bool,optional) —Whether or not to return the attentions tensors of all attention layers. Seeattentions under returnedtensors for more detail.
  • output_hidden_states (bool,optional) —Whether or not to return the hidden states of all layers. Seehidden_states under returned tensors formore detail.
  • cache_position (torch.LongTensor of shape(sequence_length),optional) —Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids,this tensor is not affected by padding. It is used to update the cache in the correct position and to inferthe complete sequence length.

Atransformers.modeling_outputs.BaseModelOutputWithPast or a tuple oftorch.FloatTensor (ifreturn_dict=False is passed or whenconfig.return_dict=False) comprising variouselements depending on the configuration (PhiConfig) and inputs.

  • last_hidden_state (torch.FloatTensor of shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.

    Ifpast_key_values is used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size) is output.

  • past_key_values (Cache,optional, returned whenuse_cache=True is passed or whenconfig.use_cache=True) — It is aCache instance. For more details, see ourkv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=True in the cross-attention blocks) that can be used (seepast_key_valuesinput) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor),optional, returned whenoutput_hidden_states=True is passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

  • attentions (tuple(torch.FloatTensor),optional, returned whenoutput_attentions=True is passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor (one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights after the attention softmax, used to compute the weighted average in the self-attentionheads.

ThePhiModel forward method, overrides the__call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call theModuleinstance afterwards instead of this since the former takes care of running the pre and post processing steps whilethe latter silently ignores them.

PhiForCausalLM

classtransformers.PhiForCausalLM

<source>

(config)

Parameters

  • config (PhiForCausalLM) —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 thefrom_pretrained() method to load the model weights.

The Phi Model for causal language modeling.

This model inherits fromPreTrainedModel. 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.)

This model is also a PyTorchtorch.nn.Module subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.

forward

<source>

(input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[transformers.cache_utils.Cache] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs])transformers.modeling_outputs.CausalLMOutputWithPast ortuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained usingAutoTokenizer. SeePreTrainedTokenizer.encode() andPreTrainedTokenizer.call() for details.

    What are input IDs?

  • attention_mask (torch.Tensor of shape(batch_size, sequence_length),optional) —Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:

    • 1 for tokens that arenot masked,
    • 0 for tokens that aremasked.

    What are attention masks?

  • position_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].

    What are position IDs?

  • past_key_values (~cache_utils.Cache,optional) —Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=True orconfig.use_cache=True.

    OnlyCache instance is allowed as input, see ourkv cache guide.If nopast_key_values are passed,DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    Ifpast_key_values are used, the user is expected to input only unprocessedinput_ids (those that don’thave their past key value states given to this model) of shape(batch_size, unprocessed_length) instead of allinput_idsof shape(batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape(batch_size, sequence_length, hidden_size),optional) —Optionally, instead of passinginput_ids you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convertinput_ids indices into associated vectors than themodel’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape(batch_size, sequence_length),optional) —Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size] or -100 (seeinput_ids docstring). Tokens with indices set to-100 are ignored(masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].
  • use_cache (bool,optional) —If set toTrue,past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).
  • cache_position (torch.LongTensor of shape(sequence_length),optional) —Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids,this tensor is not affected by padding. It is used to update the cache in the correct position and to inferthe complete sequence length.
  • logits_to_keep (Union[int, torch.Tensor], defaults to0) —If anint, compute logits for the lastlogits_to_keep tokens. If0, calculate logits for allinput_ids (special case). Only last token logits are needed for generation, and calculating them only for thattoken can save memory, which becomes pretty significant for long sequences or large vocabulary size.If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension.This is useful when using packed tensor format (single dimension for batch and sequence length).

Atransformers.modeling_outputs.CausalLMOutputWithPast or a tuple oftorch.FloatTensor (ifreturn_dict=False is passed or whenconfig.return_dict=False) comprising variouselements depending on the configuration (PhiConfig) and inputs.

  • loss (torch.FloatTensor of shape(1,),optional, returned whenlabels is provided) — Language modeling loss (for next-token prediction).

  • logits (torch.FloatTensor of shape(batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

  • past_key_values (Cache,optional, returned whenuse_cache=True is passed or whenconfig.use_cache=True) — It is aCache instance. For more details, see ourkv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (seepast_key_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor),optional, returned whenoutput_hidden_states=True is passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

  • attentions (tuple(torch.FloatTensor),optional, returned whenoutput_attentions=True is passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor (one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights after the attention softmax, used to compute the weighted average in the self-attentionheads.

ThePhiForCausalLM forward method, overrides the__call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call theModuleinstance afterwards instead of this since the former takes care of running the pre and post processing steps whilethe latter silently ignores them.

Example:

>>>from transformersimport AutoTokenizer, PhiForCausalLM>>>model = PhiForCausalLM.from_pretrained("meta-phi/Phi-2-7b-hf")>>>tokenizer = AutoTokenizer.from_pretrained("meta-phi/Phi-2-7b-hf")>>>prompt ="Hey, are you conscious? Can you talk to me?">>>inputs = tokenizer(prompt, return_tensors="pt")>>># Generate>>>generate_ids = model.generate(inputs.input_ids, max_length=30)>>>tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."

generate

<source>

(inputs: typing.Optional[torch.Tensor] = Nonegeneration_config: typing.Optional[transformers.generation.configuration_utils.GenerationConfig] = Nonelogits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = Nonestopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = Noneprefix_allowed_tokens_fn: typing.Optional[collections.abc.Callable[[int, torch.Tensor], list[int]]] = Nonesynced_gpus: typing.Optional[bool] = Noneassistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = Nonestreamer: typing.Optional[ForwardRef('BaseStreamer')] = Nonenegative_prompt_ids: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneuse_model_defaults: typing.Optional[bool] = Nonecustom_generate: typing.Union[str, collections.abc.Callable, NoneType] = None**kwargs)ModelOutput ortorch.LongTensor

Parameters

  • inputs (torch.Tensor of varying shape depending on the modality,optional) —The sequence used as a prompt for the generation or as model inputs to the encoder. IfNone themethod initializes it withbos_token_id and a batch size of 1. For decoder-only modelsinputsshould be in the format ofinput_ids. For encoder-decoder modelsinputs can represent any ofinput_ids,input_values,input_features, orpixel_values.
  • generation_config (GenerationConfig,optional) —The generation configuration to be used as base parametrization for the generation call.**kwargspassed to generate matching the attributes ofgeneration_config will override them. Ifgeneration_config is not provided, the default will be used, which has the following loadingpriority: 1) from thegeneration_config.json model file, if it exists; 2) from the modelconfiguration. Please note that unspecified parameters will inheritGenerationConfig’sdefault values, whose documentation should be checked to parameterize generation.
  • logits_processor (LogitsProcessorList,optional) —Custom logits processors that complement the default logits processors built from arguments andgeneration config. If a logit processor is passed that is already created with the arguments or ageneration config an error is thrown. This feature is intended for advanced users.
  • stopping_criteria (StoppingCriteriaList,optional) —Custom stopping criteria that complements the default stopping criteria built from arguments and ageneration config. If a stopping criteria is passed that is already created with the arguments or ageneration config an error is thrown. If your stopping criteria depends on thescores input, makesure you passreturn_dict_in_generate=True, output_scores=True togenerate. This feature isintended for advanced users.
  • prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], list[int]],optional) —If provided, this function constraints the beam search to allowed tokens only at each step. If notprovided no constraint is applied. This function takes 2 arguments: the batch IDbatch_id andinput_ids. It has to return a list with the allowed tokens for the next generation step conditionedon the batch IDbatch_id and the previously generated tokensinputs_ids. This argument is usefulfor constrained generation conditioned on the prefix, as described inAutoregressive EntityRetrieval.
  • synced_gpus (bool,optional) —Whether to continue running the while loop until max_length. Unless overridden, this flag will be settoTrue if usingFullyShardedDataParallel or DeepSpeed ZeRO Stage 3 with multiple GPUs to avoiddeadlocking if one GPU finishes generating before other GPUs. Otherwise, defaults toFalse.
  • assistant_model (PreTrainedModel,optional) —An assistant model that can be used to accelerate generation. The assistant model must have the exactsame tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistant modelis much faster than running generation with the model you’re calling generate from. As such, theassistant model should be much smaller.
  • streamer (BaseStreamer,optional) —Streamer object that will be used to stream the generated sequences. Generated tokens are passedthroughstreamer.put(token_ids) and the streamer is responsible for any further processing.
  • negative_prompt_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —The negative prompt needed for some processors such as CFG. The batch size must match the input batchsize. This is an experimental feature, subject to breaking API changes in future versions.
  • negative_prompt_attention_mask (torch.LongTensor of shape(batch_size, sequence_length),optional) —Attention_mask fornegative_prompt_ids.
  • use_model_defaults (bool,optional) —When it isTrue, unset parameters ingeneration_config will be set to the model-specific defaultgeneration configuration (model.generation_config), as opposed to the global defaults(GenerationConfig()). If unset, models saved starting fromv4.50 will consider this flag to beTrue.
  • custom_generate (str orCallable,optional) —One of the following:
    • str (Hugging Face Hub repository name): runs the customgenerate function defined atcustom_generate/generate.py in that repository instead of the standardgenerate method. Therepository fully replaces the generation logic, and the return type may differ.
    • str (local repository path): same as above but from a local path,trust_remote_code not required.
    • Callable:generate will perform the usual input preparation steps, then call the provided callable torun the decoding loop.For more information, seethe docs.
  • kwargs (dict[str, Any],optional) —Ad hoc parametrization ofgeneration_config and/or additional model-specific kwargs that will beforwarded to theforward function of the model. If the model is an encoder-decoder model, encoderspecific kwargs should not be prefixed and decoder specific kwargs should be prefixed withdecoder_.

Returns

ModelOutput ortorch.LongTensor

AModelOutput (ifreturn_dict_in_generate=Trueor whenconfig.return_dict_in_generate=True) or atorch.LongTensor.

If the model isnot an encoder-decoder model (model.config.is_encoder_decoder=False), the possibleModelOutput types are:

If the model is an encoder-decoder model (model.config.is_encoder_decoder=True), the possibleModelOutput types are:

Generates sequences of token ids for models with a language modeling head.

Most generation-controlling parameters are set ingeneration_config which, if not passed, will be set to themodel’s default generation configuration. You can override anygeneration_config by passing the correspondingparameters to generate(), e.g..generate(inputs, num_beams=4, do_sample=True).

For an overview of generation strategies and code examples, check out thefollowingguide.

PhiForSequenceClassification

classtransformers.PhiForSequenceClassification

<source>

(config)

forward

<source>

(input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[transformers.cache_utils.Cache] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = None**kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs])transformers.modeling_outputs.SequenceClassifierOutputWithPast ortuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained usingAutoTokenizer. SeePreTrainedTokenizer.encode() andPreTrainedTokenizer.call() for details.

    What are input IDs?

  • attention_mask (torch.Tensor of shape(batch_size, sequence_length),optional) —Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:

    • 1 for tokens that arenot masked,
    • 0 for tokens that aremasked.

    What are attention masks?

  • position_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].

    What are position IDs?

  • past_key_values (~cache_utils.Cache,optional) —Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=True orconfig.use_cache=True.

    OnlyCache instance is allowed as input, see ourkv cache guide.If nopast_key_values are passed,DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    Ifpast_key_values are used, the user is expected to input only unprocessedinput_ids (those that don’thave their past key value states given to this model) of shape(batch_size, unprocessed_length) instead of allinput_idsof shape(batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape(batch_size, sequence_length, hidden_size),optional) —Optionally, instead of passinginput_ids you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convertinput_ids indices into associated vectors than themodel’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape(batch_size, sequence_length),optional) —Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size] or -100 (seeinput_ids docstring). Tokens with indices set to-100 are ignored(masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].
  • use_cache (bool,optional) —If set toTrue,past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).

Returns

transformers.modeling_outputs.SequenceClassifierOutputWithPast ortuple(torch.FloatTensor)

Atransformers.modeling_outputs.SequenceClassifierOutputWithPast or a tuple oftorch.FloatTensor (ifreturn_dict=False is passed or whenconfig.return_dict=False) comprising variouselements depending on the configuration (None) and inputs.

  • loss (torch.FloatTensor of shape(1,),optional, returned whenlabels is provided) — Classification (or regression if config.num_labels==1) loss.

  • logits (torch.FloatTensor of shape(batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).

  • past_key_values (Cache,optional, returned whenuse_cache=True is passed or whenconfig.use_cache=True) — It is aCache instance. For more details, see ourkv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (seepast_key_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor),optional, returned whenoutput_hidden_states=True is passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

  • attentions (tuple(torch.FloatTensor),optional, returned whenoutput_attentions=True is passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor (one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights after the attention softmax, used to compute the weighted average in the self-attentionheads.

TheGenericForSequenceClassification forward method, overrides the__call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call theModuleinstance afterwards instead of this since the former takes care of running the pre and post processing steps whilethe latter silently ignores them.

PhiForTokenClassification

classtransformers.PhiForTokenClassification

<source>

(config)

forward

<source>

(input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[transformers.cache_utils.Cache] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = None**kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs])transformers.modeling_outputs.TokenClassifierOutput ortuple(torch.FloatTensor)

Parameters

  • input_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

    Indices can be obtained usingAutoTokenizer. SeePreTrainedTokenizer.encode() andPreTrainedTokenizer.call() for details.

    What are input IDs?

  • attention_mask (torch.Tensor of shape(batch_size, sequence_length),optional) —Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:

    • 1 for tokens that arenot masked,
    • 0 for tokens that aremasked.

    What are attention masks?

  • position_ids (torch.LongTensor of shape(batch_size, sequence_length),optional) —Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1].

    What are position IDs?

  • past_key_values (~cache_utils.Cache,optional) —Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=True orconfig.use_cache=True.

    OnlyCache instance is allowed as input, see ourkv cache guide.If nopast_key_values are passed,DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    Ifpast_key_values are used, the user is expected to input only unprocessedinput_ids (those that don’thave their past key value states given to this model) of shape(batch_size, unprocessed_length) instead of allinput_idsof shape(batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape(batch_size, sequence_length, hidden_size),optional) —Optionally, instead of passinginput_ids you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convertinput_ids indices into associated vectors than themodel’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape(batch_size, sequence_length),optional) —Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size] or -100 (seeinput_ids docstring). Tokens with indices set to-100 are ignored(masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].
  • use_cache (bool,optional) —If set toTrue,past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).

Returns

transformers.modeling_outputs.TokenClassifierOutput ortuple(torch.FloatTensor)

Atransformers.modeling_outputs.TokenClassifierOutput or a tuple oftorch.FloatTensor (ifreturn_dict=False is passed or whenconfig.return_dict=False) comprising variouselements depending on the configuration (None) and inputs.

  • loss (torch.FloatTensor of shape(1,),optional, returned whenlabels is provided) — Classification loss.

  • logits (torch.FloatTensor of shape(batch_size, sequence_length, config.num_labels)) — Classification scores (before SoftMax).

  • hidden_states (tuple(torch.FloatTensor),optional, returned whenoutput_hidden_states=True is passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).

    Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

  • attentions (tuple(torch.FloatTensor),optional, returned whenoutput_attentions=True is passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor (one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights after the attention softmax, used to compute the weighted average in the self-attentionheads.

TheGenericForTokenClassification forward method, overrides the__call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call theModuleinstance afterwards instead of this since the former takes care of running the pre and post processing steps whilethe latter silently ignores them.

Update on GitHub


[8]ページ先頭

©2009-2025 Movatter.jp