primeqa.mrc.models.task_model.ModelForDownstreamTasks#

class primeqa.mrc.models.task_model.ModelForDownstreamTasks(config: transformers.configuration_utils.PretrainedConfig, task_heads: Dict[str, Type[primeqa.mrc.models.heads.abstract.AbstractTaskHead]])#

Bases: transformers.modeling_utils.PreTrainedModel

Language model for downstream tasks. Tasks are implemented via task heads which subclass AbstractTaskHead.

Methods

add_memory_hooks

Add a memory hook before and after each sub-module forward pass to record increase in memory consumption.

add_module

Adds a child module to the current module.

adjust_logits_during_generation

Implement in subclasses of [PreTrainedModel] for custom behavior to adjust the logits in the generate method.

apply

Applies fn recursively to every submodule (as returned by .children()) as well as self.

beam_sample

Generates sequences for models with a language modeling head using beam search with multinomial sampling.

beam_search

Generates sequences for models with a language modeling head using beam search decoding.

bfloat16

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers

Returns an iterator over module buffers.

children

Returns an iterator over immediate children modules.

compute_transition_beam_scores

compute the transition probabilities of sequences given generation scores and beam indices

constrained_beam_search

Generates sequences for models with a language modeling head using beam search decoding.

cpu

Moves all model parameters and buffers to the CPU.

create_extended_attention_mask_for_decoder

cuda

Moves all model parameters and buffers to the GPU.

double

Casts all floating point parameters and buffers to double datatype.

estimate_tokens

Helper function to estimate the total number of tokens from the model inputs.

eval

Sets the module in evaluation mode.

extra_repr

Set the extra representation of the module

float

Casts all floating point parameters and buffers to float datatype.

floating_point_ops

Get number of (optionally, non-embeddings) floating-point operations for the forward and backward passes of a batch with this transformer model.

forward

Returns task head applied to language model outputs and any additional arguments supplied via kwargs.

from_config

Dynamically creates a model class from a PreTrainedConfig and then uses the config with args or kwargs to instantiate and return a model.

from_pretrained

Instantiate a pretrained pytorch model from a pre-trained model configuration.

generate

Generates sequences for models with a language modeling head.

get_buffer

Returns the buffer given by target if it exists, otherwise throws an error.

get_extended_attention_mask

Makes broadcastable attention and causal masks so that future and masked tokens are ignored.

get_extra_state

Returns any extra state to include in the module's state_dict.

get_head_mask

Prepare the head mask if needed.

get_input_embeddings

Returns the model's input embeddings.

get_output_embeddings

Returns the model's output embeddings.

get_parameter

Returns the parameter given by target if it exists, otherwise throws an error.

get_position_embeddings

get_submodule

Returns the submodule given by target if it exists, otherwise throws an error.

gradient_checkpointing_disable

Deactivates gradient checkpointing for the current model.

gradient_checkpointing_enable

Activates gradient checkpointing for the current model.

greedy_search

Generates sequences for models with a language modeling head using greedy decoding.

group_beam_search

Generates sequences for models with a language modeling head using beam search decoding.

half

Casts all floating point parameters and buffers to half datatype.

init_weights

If needed prunes and maybe initializes weights.

invert_attention_mask

Invert an attention mask (e.g., switches 0.

load_state_dict

Copies parameters and buffers from state_dict into this module and its descendants.

model_class_from_config

Dynamically creates and returns a model class from a PreTrainedConfig.

modules

Returns an iterator over all modules in the network.

named_buffers

Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children

Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules

Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters

Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

num_parameters

Get number of (optionally, trainable or non-embeddings) parameters in the module.

parameters

Returns an iterator over module parameters.

post_init

A method executed at the end of each Transformer model initialization, to execute code that needs the model's modules properly initialized (such as weight initialization).

prepare_inputs_for_generation

Implement in subclasses of [PreTrainedModel] for custom behavior to prepare inputs in the generate method.

prune_heads

Prunes heads of the base model.

push_to_hub

Upload the model checkpoint to the 🤗 Model Hub while synchronizing a local clone of the repo in repo_path_or_name.

register_backward_hook

Registers a backward hook on the module.

register_buffer

Adds a buffer to the module.

register_for_auto_class

Register this class with a given auto class.

register_forward_hook

Registers a forward hook on the module.

register_forward_pre_hook

Registers a forward pre-hook on the module.

register_full_backward_hook

Registers a backward hook on the module.

register_module

Alias for add_module().

register_parameter

Adds a parameter to the module.

requires_grad_

Change if autograd should record operations on parameters in this module.

reset_memory_hooks_state

Reset the mem_rss_diff attribute of each module (see [~modeling_utils.ModuleUtilsMixin.add_memory_hooks]).

resize_position_embeddings

resize_token_embeddings

Resizes input token embeddings matrix of the model if new_num_tokens != config.vocab_size.

retrieve_modules_from_names

sample

Generates sequences for models with a language modeling head using multinomial sampling.

save_pretrained

Save a model and its configuration file to a directory, so that it can be re-loaded using the [`~PreTrainedModel.from_pretrained]` class method.

set_extra_state

This function is called from load_state_dict() to handle any extra state found within the state_dict.

set_input_embeddings

Set model's input embeddings.

set_task_head

param task_head

name of the task head to activate.

share_memory

See torch.Tensor.share_memory_()

state_dict

Returns a dictionary containing a whole state of the module.

tie_weights

Tie the weights between the input embeddings and the output embeddings.

to

Moves and/or casts the parameters and buffers.

to_empty

Moves the parameters and buffers to the specified device without copying storage.

train

Sets the module in training mode.

type

Casts all parameters and buffers to dst_type.

xpu

Moves all model parameters and buffers to the XPU.

zero_grad

Sets gradients of all model parameters to zero.

Attributes

T_destination

alias of TypeVar('T_destination', bound=Mapping[str, torch.Tensor])

base_model

The main body of the model.

base_model_prefix

config_class

device

The device on which the module is (assuming that all the module parameters are on the same device).

dtype

The dtype of the module (assuming that all the module parameters have the same dtype).

dummy_inputs

Dummy inputs to do a forward pass in the network.

dump_patches

This allows better BC support for load_state_dict().

framework

Identifies that this is a PyTorch model.

is_gradient_checkpointing

Whether gradient checkpointing is activated for this model or not.

is_parallelizable

main_input_name

model_

Returns the underlying language model.

supports_gradient_checkpointing

task_head

Return the current task head or raises a ValueError if it has not yet been set.

__call__(*input, **kwargs)#

Call self as a function.

add_memory_hooks()#

Add a memory hook before and after each sub-module forward pass to record increase in memory consumption.

Increase in memory consumption is stored in a mem_rss_diff attribute for each module and can be reset to zero with model.reset_memory_hooks_state().

add_module(name: str, module: Optional[torch.nn.modules.module.Module]) None#

Adds a child module to the current module.

The module can be accessed as an attribute using the given name.

Parameters
  • name (string) – name of the child module. The child module can be accessed from this module using the given name

  • module (Module) – child module to be added to the module.

adjust_logits_during_generation(logits: torch.FloatTensor, **kwargs) torch.FloatTensor#

Implement in subclasses of [PreTrainedModel] for custom behavior to adjust the logits in the generate method.

apply(fn: Callable[[torch.nn.modules.module.Module], None]) torch.nn.modules.module.T#

Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also nn-init-doc).

Parameters

fn (Module -> None) – function to be applied to each submodule

Returns

self

Return type

Module

Example:

>>> @torch.no_grad()
>>> def init_weights(m):
>>>     print(m)
>>>     if type(m) == nn.Linear:
>>>         m.weight.fill_(1.0)
>>>         print(m.weight)
>>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
>>> net.apply(init_weights)
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1.,  1.],
        [ 1.,  1.]])
Linear(in_features=2, out_features=2, bias=True)
Parameter containing:
tensor([[ 1.,  1.],
        [ 1.,  1.]])
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
property base_model: torch.nn.modules.module.Module#

The main body of the model.

Type

torch.nn.Module

beam_sample(input_ids: torch.LongTensor, beam_scorer: transformers.generation_beam_search.BeamScorer, logits_processor: Optional[transformers.generation_logits_process.LogitsProcessorList] = None, stopping_criteria: Optional[transformers.generation_stopping_criteria.StoppingCriteriaList] = None, logits_warper: Optional[transformers.generation_logits_process.LogitsProcessorList] = None, max_length: Optional[int] = None, pad_token_id: Optional[int] = None, eos_token_id: Optional[int] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_scores: Optional[bool] = None, return_dict_in_generate: Optional[bool] = None, synced_gpus: Optional[bool] = False, **model_kwargs) Union[transformers.generation_utils.BeamSampleEncoderDecoderOutput, transformers.generation_utils.BeamSampleDecoderOnlyOutput, torch.LongTensor]#

Generates sequences for models with a language modeling head using beam search with multinomial sampling.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) – The sequence used as a prompt for the generation.

  • beam_scorer (BeamScorer) – A derived instance of [BeamScorer] that defines how beam hypotheses are constructed, stored and sorted during generation. For more information, the documentation of [BeamScorer] should be read.

  • logits_processor (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsProcessor] used to modify the prediction scores of the language modeling head applied at each generation step.

  • stopping_criteria (StoppingCriteriaList, optional) – An instance of [StoppingCriteriaList]. List of instances of class derived from [StoppingCriteria] used to tell if the generation loop should stop.

  • logits_warper (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsWarper] used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.

  • max_length (int, optional, defaults to 20) – DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated tokens. The maximum length of the sequence to be generated.

  • pad_token_id (int, optional) – The id of the padding token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific kwargs will be forwarded to the forward function of the model. If model is an encoder-decoder model the kwargs should include encoder_outputs.

Returns

[~generation_utils.BeamSampleDecoderOnlyOutput], [~generation_utils.BeamSampleEncoderDecoderOutput] or torch.LongTensor: A torch.LongTensor containing the generated tokens (default behaviour) or a [~generation_utils.BeamSampleDecoderOnlyOutput] if model.config.is_encoder_decoder=False and return_dict_in_generate=True or a [~generation_utils.BeamSampleEncoderDecoderOutput] if model.config.is_encoder_decoder=True.

Examples:

```python >>> from transformers import ( … AutoTokenizer, … AutoModelForSeq2SeqLM, … LogitsProcessorList, … MinLengthLogitsProcessor, … TopKLogitsWarper, … TemperatureLogitsWarper, … BeamSearchScorer, … ) >>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id
>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }
>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     max_length=model.config.max_length,
...     num_beams=num_beams,
...     device=model.device,
... )
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id)]
... )
>>> # instantiate logits processors
>>> logits_warper = LogitsProcessorList(
...     [
...         TopKLogitsWarper(50),
...         TemperatureLogitsWarper(0.7),
...     ]
... )
>>> outputs = model.beam_sample(
...     input_ids, beam_scorer, logits_processor=logits_processor, logits_warper=logits_warper, **model_kwargs
... )
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
```

Generates sequences for models with a language modeling head using beam search decoding.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) – The sequence used as a prompt for the generation.

  • beam_scorer (BeamScorer) – An derived instance of [BeamScorer] that defines how beam hypotheses are constructed, stored and sorted during generation. For more information, the documentation of [BeamScorer] should be read.

  • logits_processor (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsProcessor] used to modify the prediction scores of the language modeling head applied at each generation step.

  • stopping_criteria (StoppingCriteriaList, optional) – An instance of [StoppingCriteriaList]. List of instances of class derived from [StoppingCriteria] used to tell if the generation loop should stop.

  • max_length (int, optional, defaults to 20) – DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated tokens. The maximum length of the sequence to be generated.

  • pad_token_id (int, optional) – The id of the padding token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific kwargs will be forwarded to the forward function of the model. If model is an encoder-decoder model the kwargs should include encoder_outputs.

Returns

[generation_utilsBeamSearchDecoderOnlyOutput], [~generation_utils.BeamSearchEncoderDecoderOutput] or torch.LongTensor: A torch.LongTensor containing the generated tokens (default behaviour) or a [~generation_utils.BeamSearchDecoderOnlyOutput] if model.config.is_encoder_decoder=False and return_dict_in_generate=True or a [~generation_utils.BeamSearchEncoderDecoderOutput] if model.config.is_encoder_decoder=True.

Examples:

```python >>> from transformers import ( … AutoTokenizer, … AutoModelForSeq2SeqLM, … LogitsProcessorList, … MinLengthLogitsProcessor, … BeamSearchScorer, … ) >>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id
>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }
>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     num_beams=num_beams,
...     device=model.device,
... )
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )
>>> outputs = model.beam_search(input_ids, beam_scorer, logits_processor=logits_processor, **model_kwargs)
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
```
bfloat16() torch.nn.modules.module.T#

Casts all floating point parameters and buffers to bfloat16 datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

buffers(recurse: bool = True) Iterator[torch.Tensor]#

Returns an iterator over module buffers.

Parameters

recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields

torch.Tensor – module buffer

Example:

>>> for buf in model.buffers():
>>>     print(type(buf), buf.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
children() Iterator[torch.nn.modules.module.Module]#

Returns an iterator over immediate children modules.

Yields

Module – a child module

compute_transition_beam_scores(sequences: torch.Tensor, scores: Tuple[torch.Tensor], beam_indices: torch.Tensor, eos_token_id: Optional[int] = None)#

compute the transition probabilities of sequences given generation scores and beam indices

Generates sequences for models with a language modeling head using beam search decoding.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) – The sequence used as a prompt for the generation.

  • constrained_beam_scorer (ConstrainedBeamSearchScorer) – A derived instance of [BeamScorer] that defines how beam hypotheses are constructed, stored and sorted during generation, while satisfying a list of positive constraints. For more information, the documentation of [ConstrainedBeamSearchScorer] should be read.

  • logits_processor (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsProcessor] used to modify the prediction scores of the language modeling head applied at each generation step.

  • stopping_criteria (StoppingCriteriaList, optional) – An instance of [StoppingCriteriaList]. List of instances of class derived from [StoppingCriteria] used to tell if the generation loop should stop.

  • logits_warper (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsWarper] used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.

  • max_length (int, optional, defaults to 20) – DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated tokens. The maximum length of the sequence to be generated.

  • pad_token_id (int, optional) – The id of the padding token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific kwargs will be forwarded to the forward function of the model. If model is an encoder-decoder model the kwargs should include encoder_outputs.

Returns

[generation_utilsBeamSearchDecoderOnlyOutput], [~generation_utils.BeamSearchEncoderDecoderOutput] or torch.LongTensor: A torch.LongTensor containing the generated tokens (default behaviour) or a [~generation_utils.BeamSearchDecoderOnlyOutput] if model.config.is_encoder_decoder=False and return_dict_in_generate=True or a [~generation_utils.BeamSearchEncoderDecoderOutput] if model.config.is_encoder_decoder=True.

Examples:

```python >>> from transformers import ( … AutoTokenizer, … AutoModelForSeq2SeqLM, … LogitsProcessorList, … MinLengthLogitsProcessor, … ConstrainedBeamSearchScorer, … PhrasalConstraint, … ) >>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id
>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }
>>> constraint_str = "sind"
>>> constraint_token_ids = tokenizer.encode(constraint_str)[:-1]  # slice to remove eos token
>>> constraints = [PhrasalConstraint(token_ids=constraint_token_ids)]
>>> # instantiate beam scorer
>>> beam_scorer = ConstrainedBeamSearchScorer(
...     batch_size=1, num_beams=num_beams, device=model.device, constraints=constraints
... )
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )
>>> outputs = model.constrained_beam_search(
...     input_ids, beam_scorer, constraints=constraints, logits_processor=logits_processor, **model_kwargs
... )
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
# => ['Wie alter sind Sie?']
```
cpu() torch.nn.modules.module.T#

Moves all model parameters and buffers to the CPU.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

cuda(device: Optional[Union[int, torch.device]] = None) torch.nn.modules.module.T#

Moves all model parameters and buffers to the GPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.

Note

This method modifies the module in-place.

Parameters

device (int, optional) – if specified, all parameters will be copied to that device

Returns

self

Return type

Module

property device: torch.device#

The device on which the module is (assuming that all the module parameters are on the same device).

Type

torch.device

double() torch.nn.modules.module.T#

Casts all floating point parameters and buffers to double datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

property dtype: torch.dtype#

The dtype of the module (assuming that all the module parameters have the same dtype).

Type

torch.dtype

property dummy_inputs: Dict[str, torch.Tensor]#

Dummy inputs to do a forward pass in the network.

Type

Dict[str, torch.Tensor]

estimate_tokens(input_dict: Dict[str, Union[torch.Tensor, Any]]) int#

Helper function to estimate the total number of tokens from the model inputs.

Parameters

inputs (dict) – The model inputs.

Returns

The total number of tokens.

Return type

int

eval() torch.nn.modules.module.T#

Sets the module in evaluation mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

This is equivalent with self.train(False).

See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.

Returns

self

Return type

Module

extra_repr() str#

Set the extra representation of the module

To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.

float() torch.nn.modules.module.T#

Casts all floating point parameters and buffers to float datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

floating_point_ops(input_dict: Dict[str, Union[torch.Tensor, Any]], exclude_embeddings: bool = True) int#

Get number of (optionally, non-embeddings) floating-point operations for the forward and backward passes of a batch with this transformer model. Default approximation neglects the quadratic dependency on the number of tokens (valid if 12 * d_model << sequence_length) as laid out in [this paper](https://arxiv.org/pdf/2001.08361.pdf) section 2.1. Should be overridden for transformers with parameter re-use e.g. Albert or Universal Transformers, or if doing long-range modeling with very high sequence lengths.

Parameters
  • batch_size (int) – The batch size for the forward pass.

  • sequence_length (int) – The number of tokens in each line of the batch.

  • exclude_embeddings (bool, optional, defaults to True) – Whether or not to count embedding and softmax operations.

Returns

The number of floating-point operations.

Return type

int

forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)#

Returns task head applied to language model outputs and any additional arguments supplied via kwargs. See HF transformers documentation for more details on other parameters.

property framework: str#

Identifies that this is a PyTorch model.

Type

str

classmethod from_config(config: transformers.configuration_utils.PretrainedConfig, *args, **kwargs) primeqa.mrc.models.task_model.ModelForDownstreamTasks#

Dynamically creates a model class from a PreTrainedConfig and then uses the config with args or kwargs to instantiate and return a model.

classmethod from_pretrained(pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs)#

Instantiate a pretrained pytorch model from a pre-trained model configuration.

The model is set in evaluation mode by default using model.eval() (Dropout modules are deactivated). To train the model, you should first set it back in training mode with model.train().

The warning Weights from XXX not initialized from pretrained model means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task.

The warning Weights from XXX not used in YYY means that the layer XXX is not used by YYY, therefore those weights are discarded.

Parameters
  • pretrained_model_name_or_path (str or os.PathLike, optional) –

    Can be either:

    • A string, the model id of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like bert-base-uncased, or namespaced under a user or organization name, like dbmdz/bert-base-german-cased.

    • A path to a directory containing model weights saved using [~PreTrainedModel.save_pretrained], e.g., ./my_model_directory/.

    • A path or url to a tensorflow index checkpoint file (e.g, ./tf_model/model.ckpt.index). In this case, from_tf should be set to True and a configuration object should be provided as config argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.

    • A path or url to a model folder containing a flax checkpoint file in .msgpack format (e.g, ./flax_model/ containing flax_model.msgpack). In this case, from_flax should be set to True.

    • None if you are both providing the configuration and state dictionary (resp. with keyword arguments config and state_dict).

  • model_args (sequence of positional arguments, optional) – All remaining positional arguments will be passed to the underlying model’s __init__ method.

  • config (Union[PretrainedConfig, str, os.PathLike], optional) –

    Can be either:

    • an instance of a class derived from [PretrainedConfig],

    • a string or path valid as input to [~PretrainedConfig.from_pretrained].

    Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:

    • The model is a model provided by the library (loaded with the model id string of a pretrained model).

    • The model was saved using [~PreTrainedModel.save_pretrained] and is reloaded by supplying the save directory.

    • The model is loaded by supplying a local directory as pretrained_model_name_or_path and a configuration JSON file named config.json is found in the directory.

  • state_dict (Dict[str, torch.Tensor], optional) –

    A state dictionary to use instead of a state dictionary loaded from saved weights file.

    This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using [~PreTrainedModel.save_pretrained] and [~PreTrainedModel.from_pretrained] is not a simpler option.

  • cache_dir (Union[str, os.PathLike], optional) – Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.

  • from_tf (bool, optional, defaults to False) – Load the model weights from a TensorFlow checkpoint save file (see docstring of pretrained_model_name_or_path argument).

  • from_flax (bool, optional, defaults to False) – Load the model weights from a Flax checkpoint save file (see docstring of pretrained_model_name_or_path argument).

  • ignore_mismatched_sizes (bool, optional, defaults to False) – Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a checkpoint with 3 labels).

  • force_download (bool, optional, defaults to False) – Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.

  • resume_download (bool, optional, defaults to False) – Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists.

  • proxies (Dict[str, str], optional) – A dictionary of proxy servers to use by protocol or endpoint, e.g., {‘http’: ‘foo.bar:3128’, ‘http://hostname’: ‘foo.bar:4012’}. The proxies are used on each request.

  • output_loading_info (bool, optional, defaults to False) – Whether ot not to also return a dictionary containing missing keys, unexpected keys and error messages.

  • local_files_only (bool, optional, defaults to False) – Whether or not to only look at local files (i.e., do not try to download the model).

  • use_auth_token (str or bool, optional) – The token to use as HTTP bearer authorization for remote files. If True, will use the token generated when running transformers-cli login (stored in ~/.huggingface).

  • revision (str, optional, defaults to “main”) – The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so revision can be any identifier allowed by git.

  • mirror (str, optional) – Mirror source to accelerate downloads in China. If you are from China and have an accessibility problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety. Please refer to the mirror site for more information.

  • _fast_init (bool, optional, defaults to ``True) – Whether or not to disable fast initialization.

  • low_cpu_mem_usage (bool`, optional, defaults to ``False) – Tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model. This is an experimental feature and a subject to change at any moment.

  • torch_dtype (str or torch.dtype, optional) –

    Override the default torch.dtype and load the model under this dtype. If “auto” is passed the dtype will be automatically derived from the model’s weights.

    <Tip warning={true}>

    One should only disable _fast_init to ensure backwards compatibility with transformers.__version__ < 4.6.0 for seeded model initialization. This argument will be removed at the next major version. See [pull request 11471](https://github.com/huggingface/transformers/pull/11471) for more information.

    </Tip>

  • kwargs (remaining dictionary of keyword arguments, optional) –

    Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., output_attentions=True). Behaves differently depending on whether a config is provided or automatically loaded:

    • If a configuration is provided with config, **kwargs will be directly passed to the underlying model’s __init__ method (we assume all relevant updates to the configuration have already been done)

    • If a configuration is not provided, kwargs will be first passed to the configuration class initialization function ([~PretrainedConfig.from_pretrained]). Each key of kwargs that corresponds to a configuration attribute will be used to override said attribute with the supplied kwargs value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model’s __init__ function.

<Tip>

Passing use_auth_token=True` is required when you want to use a private model.

</Tip>

<Tip>

Activate the special [“offline-mode”](https://huggingface.co/transformers/installation.html#offline-mode) to use this method in a firewalled environment.

</Tip>

Examples:

```python >>> from transformers import BertConfig, BertModel

>>> # Download model and configuration from huggingface.co and cache.
>>> model = BertModel.from_pretrained("bert-base-uncased")
>>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
>>> model = BertModel.from_pretrained("./test/saved_model/")
>>> # Update configuration during loading.
>>> model = BertModel.from_pretrained("bert-base-uncased", output_attentions=True)
>>> assert model.config.output_attentions == True
>>> # Loading from a TF checkpoint file instead of a PyTorch model (slower, for example purposes, not runnable).
>>> config = BertConfig.from_json_file("./tf_model/my_tf_model_config.json")
>>> model = BertModel.from_pretrained("./tf_model/my_tf_checkpoint.ckpt.index", from_tf=True, config=config)
>>> # Loading from a Flax checkpoint file instead of a PyTorch model (slower)
>>> model = BertModel.from_pretrained("bert-base-uncased", from_flax=True)
```
generate(inputs: Optional[torch.Tensor] = None, max_length: Optional[int] = None, min_length: Optional[int] = None, do_sample: Optional[bool] = None, early_stopping: Optional[bool] = None, num_beams: Optional[int] = None, temperature: Optional[float] = None, top_k: Optional[int] = None, top_p: Optional[float] = None, typical_p: Optional[float] = None, repetition_penalty: Optional[float] = None, bad_words_ids: Optional[Iterable[int]] = None, bos_token_id: Optional[int] = None, pad_token_id: Optional[int] = None, eos_token_id: Optional[int] = None, length_penalty: Optional[float] = None, no_repeat_ngram_size: Optional[int] = None, encoder_no_repeat_ngram_size: Optional[int] = None, num_return_sequences: Optional[int] = None, max_time: Optional[float] = None, max_new_tokens: Optional[int] = None, decoder_start_token_id: Optional[int] = None, use_cache: Optional[bool] = None, num_beam_groups: Optional[int] = None, diversity_penalty: Optional[float] = None, prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None, logits_processor: Optional[transformers.generation_logits_process.LogitsProcessorList] = [], stopping_criteria: Optional[transformers.generation_stopping_criteria.StoppingCriteriaList] = [], constraints: Optional[List[transformers.generation_beam_constraints.Constraint]] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_scores: Optional[bool] = None, return_dict_in_generate: Optional[bool] = None, forced_bos_token_id: Optional[int] = None, forced_eos_token_id: Optional[int] = None, remove_invalid_values: Optional[bool] = None, synced_gpus: Optional[bool] = False, **model_kwargs) Union[transformers.generation_utils.GreedySearchEncoderDecoderOutput, transformers.generation_utils.GreedySearchDecoderOnlyOutput, transformers.generation_utils.SampleEncoderDecoderOutput, transformers.generation_utils.SampleDecoderOnlyOutput, transformers.generation_utils.BeamSearchEncoderDecoderOutput, transformers.generation_utils.BeamSearchDecoderOnlyOutput, transformers.generation_utils.BeamSampleEncoderDecoderOutput, transformers.generation_utils.BeamSampleDecoderOnlyOutput, torch.LongTensor]#

Generates sequences for models with a language modeling head. The method currently supports greedy decoding, multinomial sampling, beam-search decoding, and beam-search multinomial sampling.

Apart from inputs, all the arguments below will default to the value of the attribute of the same name inside the [PretrainedConfig] of the model. The default values indicated are the default values of those config.

Most of these parameters are explained in more detail in [this blog post](https://huggingface.co/blog/how-to-generate).

Parameters
  • inputs (torch.Tensor of shape `(batch_size, sequence_length) –

  • ` (feature_dim)` or) – The sequence used as a prompt for the generation or as model inputs to the encoder. If None the method initializes it with bos_token_id and a batch size of 1. For decoder-only models inputs should of in the format of input_ids. For encoder-decoder models inputs can represent any of input_ids, input_values, input_features, or pixel_values.

  • max_length (int, optional, defaults to model.config.max_length) – The maximum length of the sequence to be generated.

  • max_new_tokens (int, optional, defaults to None) – The maximum numbers of tokens to generate, ignore the current number of tokens. Use either max_new_tokens or max_length but not both, they serve the same purpose.

  • min_length (int, optional, defaults to 10) – The minimum length of the sequence to be generated.

  • do_sample (bool, optional, defaults to False) – Whether or not to use sampling ; use greedy decoding otherwise.

  • early_stopping (bool, optional, defaults to False) – Whether to stop the beam search when at least num_beams sentences are finished per batch or not.

  • num_beams (int, optional, defaults to 1) – Number of beams for beam search. 1 means no beam search.

  • temperature (float, optional, defaults to 1.0) – The value used to module the next token probabilities.

  • top_k (int, optional, defaults to 50) – The number of highest probability vocabulary tokens to keep for top-k-filtering.

  • top_p (float, optional, defaults to 1.0) – If set to float < 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation.

  • repetition_penalty (float, optional, defaults to 1.0) – The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.

  • pad_token_id (int, optional) – The id of the padding token.

  • bos_token_id (int, optional) – The id of the beginning-of-sequence token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • length_penalty (float, optional, defaults to 1.0) – Exponential penalty to the length. 1.0 means no penalty. Set to values < 1.0 in order to encourage the model to generate shorter sequences, to a value > 1.0 in order to encourage the model to produce longer sequences.

  • no_repeat_ngram_size (int, optional, defaults to 0) – If set to int > 0, all ngrams of that size can only occur once.

  • encoder_no_repeat_ngram_size (int, optional, defaults to 0) – If set to int > 0, all ngrams of that size that occur in the encoder_input_ids cannot occur in the decoder_input_ids.

  • bad_words_ids (List[List[int]], optional) – List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use tokenizer(bad_words, add_prefix_space=True, add_special_tokens=False).input_ids.

  • num_return_sequences (int, optional, defaults to 1) – The number of independently computed returned sequences for each element in the batch.

  • max_time (float, optional, defaults to None) – The maximum amount of time you allow the computation to run for in seconds. generation will still finish the current pass after allocated time has been passed.

  • attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) – Mask to avoid performing attention on padding token indices. Mask values are in [0, 1], 1 for tokens that are not masked, and 0 for masked tokens. If not provided, will default to a tensor the same shape as input_ids that masks the pad token. [What are attention masks?](../glossary#attention-mask)

  • decoder_start_token_id (int, optional) – If an encoder-decoder model starts decoding with a different token than bos, the id of that token.

  • use_cache – (bool, optional, defaults to True): Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.

  • num_beam_groups (int, optional, defaults to 1) – Number of groups to divide num_beams into in order to ensure diversity among different groups of beams. [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.

  • diversity_penalty (float, optional, defaults to 0.0) – This value is subtracted from a beam’s score if it generates a token same as any beam from other group at a particular time. Note that diversity_penalty is only effective if group beam search is enabled.

  • 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 not provided no constraint is applied. This function takes 2 arguments: the batch ID batch_id and input_ids. It has to return a list with the allowed tokens for the next generation step conditioned on the batch ID batch_id and the previously generated tokens inputs_ids. This argument is useful for constrained generation conditioned on the prefix, as described in [Autoregressive Entity Retrieval](https://arxiv.org/abs/2010.00904).

  • logits_processor (LogitsProcessorList, optional) – Custom logits processors that complement the default logits processors built from arguments and a model’s config. If a logit processor is passed that is already created with the arguments or a model’s config an error is thrown. This feature is intended for advanced users.

  • stopping_criteria (StoppingCriteriaList, optional) – Custom stopping criteria that complement the default stopping criteria built from arguments and a model’s config. If a stopping criteria is passed that is already created with the arguments or a model’s config an error is thrown. This feature is intended for advanced users.

  • constraints (List[Constraint], optional) – Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by Constraint objects, in the most sensible way possible.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • forced_bos_token_id (int, optional) – The id of the token to force as the first generated token after the decoder_start_token_id. Useful for multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be the target language token.

  • forced_eos_token_id (int, optional) – The id of the token to force as the last generated token when max_length is reached.

  • remove_invalid_values (bool, optional) – Whether to remove possible nan and inf outputs of the model to prevent the generation method to crash. Note that using remove_invalid_values can slow down generation.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific kwargs will be forwarded to the forward function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with decoder_.

Returns

A [~file_utils.ModelOutput] (if return_dict_in_generate=True or when config.return_dict_in_generate=True) or a torch.FloatTensor.

If the model is not an encoder-decoder model (model.config.is_encoder_decoder=False), the possible [~file_utils.ModelOutput] types are:

  • [~generation_utils.GreedySearchDecoderOnlyOutput],

  • [~generation_utils.SampleDecoderOnlyOutput],

  • [~generation_utils.BeamSearchDecoderOnlyOutput],

  • [~generation_utils.BeamSampleDecoderOnlyOutput]

If the model is an encoder-decoder model (model.config.is_encoder_decoder=True), the possible [~file_utils.ModelOutput] types are:

  • [~generation_utils.GreedySearchEncoderDecoderOutput],

  • [~generation_utils.SampleEncoderDecoderOutput],

  • [~generation_utils.BeamSearchEncoderDecoderOutput],

  • [~generation_utils.BeamSampleEncoderDecoderOutput]

Return type

[~file_utils.ModelOutput] or torch.LongTensor

Examples:

```python >>> from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForSeq2SeqLM

>>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
>>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
>>> # do greedy decoding without providing a prompt
>>> outputs = model.generate(max_length=40)
>>> print("Generated:", tokenizer.decode(outputs[0], skip_special_tokens=True))
>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
>>> document = (
...     "at least two people were killed in a suspected bomb attack on a passenger bus "
...     "in the strife-torn southern philippines on monday , the military said."
... )
>>> # encode input context
>>> input_ids = tokenizer(document, return_tensors="pt").input_ids
>>> # generate 3 independent sequences using beam search decoding (5 beams)
>>> # with T5 encoder-decoder model conditioned on short news article.
>>> outputs = model.generate(input_ids=input_ids, num_beams=5, num_return_sequences=3)
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
>>> tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
>>> model = AutoModelForCausalLM.from_pretrained("distilgpt2")
>>> input_context = "The dog"
>>> # encode input context
>>> input_ids = tokenizer(input_context, return_tensors="pt").input_ids
>>> # generate 3 candidates using sampling
>>> outputs = model.generate(input_ids=input_ids, max_length=20, num_return_sequences=3, do_sample=True)
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
>>> tokenizer = AutoTokenizer.from_pretrained("ctrl")
>>> model = AutoModelForCausalLM.from_pretrained("ctrl")
>>> # "Legal" is one of the control codes for ctrl
>>> input_context = "Legal My neighbor is"
>>> # encode input context
>>> input_ids = tokenizer(input_context, return_tensors="pt").input_ids
>>> outputs = model.generate(input_ids=input_ids, max_length=20, repetition_penalty=1.2)
>>> print("Generated:", tokenizer.decode(outputs[0], skip_special_tokens=True))
>>> tokenizer = AutoTokenizer.from_pretrained("gpt2", use_fast=False)
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> input_context = "My cute dog"
>>> # get tokens of words that should not be generated
>>> bad_words_ids = tokenizer(
...     ["idiot", "stupid", "shut up"], add_prefix_space=True, add_special_tokens=False
>>> ).input_ids
>>> # encode input context
>>> input_ids = tokenizer(input_context, return_tensors="pt").input_ids
>>> # generate sequences without allowing bad_words to be generated
>>> outputs = model.generate(input_ids=input_ids, max_length=20, do_sample=True, bad_words_ids=bad_words_ids)
>>> print("Generated:", tokenizer.decode(outputs[0], skip_special_tokens=True))
```
get_buffer(target: str) torch.Tensor#

Returns the buffer given by target if it exists, otherwise throws an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Parameters

target – The fully-qualified string name of the buffer to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns

The buffer referenced by target

Return type

torch.Tensor

Raises

AttributeError – If the target string references an invalid path or resolves to something that is not a buffer

get_extended_attention_mask(attention_mask: torch.Tensor, input_shape: typing.Tuple[int], device: <property object at 0x7f074f1029f0>) torch.Tensor#

Makes broadcastable attention and causal masks so that future and masked tokens are ignored.

Parameters
  • attention_mask (torch.Tensor) – Mask with ones indicating tokens to attend to, zeros for tokens to ignore.

  • input_shape (Tuple[int]) – The shape of the input to the model.

  • device – (torch.device): The device of the input to the model.

Returns

torch.Tensor The extended attention mask, with a the same dtype as attention_mask.dtype.

get_extra_state() Any#

Returns any extra state to include in the module’s state_dict. Implement this and a corresponding set_extra_state() for your module if you need to store extra state. This function is called when building the module’s state_dict().

Note that extra state should be pickleable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.

Returns

Any extra state to store in the module’s state_dict

Return type

object

get_head_mask(head_mask: Optional[torch.Tensor], num_hidden_layers: int, is_attention_chunked: bool = False) torch.Tensor#

Prepare the head mask if needed.

Parameters
  • head_mask (torch.Tensor with shape [num_heads] or [num_hidden_layers x num_heads], optional) – The mask indicating if we should keep the heads or not (1.0 for keep, 0.0 for discard).

  • num_hidden_layers (int) – The number of hidden layers in the model.

  • is_attention_chunked – (bool, optional, defaults to False): Whether or not the attentions scores are computed by chunks or not.

Returns

torch.Tensor with shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] or list with [None] for each layer.

get_input_embeddings() torch.nn.modules.module.Module#

Returns the model’s input embeddings.

Returns

A torch module mapping vocabulary to hidden states.

Return type

nn.Module

get_output_embeddings() torch.nn.modules.module.Module#

Returns the model’s output embeddings.

Returns

A torch module mapping hidden states to vocabulary.

Return type

nn.Module

get_parameter(target: str) torch.nn.parameter.Parameter#

Returns the parameter given by target if it exists, otherwise throws an error.

See the docstring for get_submodule for a more detailed explanation of this method’s functionality as well as how to correctly specify target.

Parameters

target – The fully-qualified string name of the Parameter to look for. (See get_submodule for how to specify a fully-qualified string.)

Returns

The Parameter referenced by target

Return type

torch.nn.Parameter

Raises

AttributeError – If the target string references an invalid path or resolves to something that is not an nn.Parameter

get_submodule(target: str) torch.nn.modules.module.Module#

Returns the submodule given by target if it exists, otherwise throws an error.

For example, let’s say you have an nn.Module A that looks like this:

(The diagram shows an nn.Module A. A has a nested submodule net_b, which itself has two submodules net_c and linear. net_c then has a submodule conv.)

To check whether or not we have the linear submodule, we would call get_submodule("net_b.linear"). To check whether we have the conv submodule, we would call get_submodule("net_b.net_c.conv").

The runtime of get_submodule is bounded by the degree of module nesting in target. A query against named_modules achieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists, get_submodule should always be used.

Parameters

target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)

Returns

The submodule referenced by target

Return type

torch.nn.Module

Raises

AttributeError – If the target string references an invalid path or resolves to something that is not an nn.Module

gradient_checkpointing_disable()#

Deactivates gradient checkpointing for the current model.

Note that in other frameworks this feature can be referred to as “activation checkpointing” or “checkpoint activations”.

gradient_checkpointing_enable()#

Activates gradient checkpointing for the current model.

Note that in other frameworks this feature can be referred to as “activation checkpointing” or “checkpoint activations”.

Generates sequences for models with a language modeling head using greedy decoding.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) – The sequence used as a prompt for the generation.

  • logits_processor (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsProcessor] used to modify the prediction scores of the language modeling head applied at each generation step.

  • stopping_criteria (StoppingCriteriaList, optional) – An instance of [StoppingCriteriaList]. List of instances of class derived from [StoppingCriteria] used to tell if the generation loop should stop.

  • max_length (int, optional, defaults to 20) – DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated tokens. The maximum length of the sequence to be generated.

  • pad_token_id (int, optional) – The id of the padding token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific keyword arguments will be forwarded to the forward function of the model. If model is an encoder-decoder model the kwargs should include encoder_outputs.

Returns

[~generation_utils.GreedySearchDecoderOnlyOutput], [~generation_utils.GreedySearchEncoderDecoderOutput] or torch.LongTensor: A torch.LongTensor containing the generated tokens (default behaviour) or a [~generation_utils.GreedySearchDecoderOnlyOutput] if model.config.is_encoder_decoder=False and return_dict_in_generate=True or a [~generation_utils.GreedySearchEncoderDecoderOutput] if model.config.is_encoder_decoder=True.

Examples:

```python >>> from transformers import ( … AutoTokenizer, … AutoModelForCausalLM, … LogitsProcessorList, … MinLengthLogitsProcessor, … )

>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
>>> model.config.pad_token_id = model.config.eos_token_id
>>> input_prompt = "Today is a beautiful day, and"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(15, eos_token_id=model.config.eos_token_id),
...     ]
... )
>>> outputs = model.greedy_search(input_ids, logits_processor=logits_processor)
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
```

Generates sequences for models with a language modeling head using beam search decoding.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) – The sequence used as a prompt for the generation.

  • beam_scorer (BeamScorer) – An derived instance of [BeamScorer] that defines how beam hypotheses are constructed, stored and sorted during generation. For more information, the documentation of [BeamScorer] should be read.

  • logits_processor (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsProcessor] used to modify the prediction scores of the language modeling head applied at each generation step.

  • stopping_criteria (StoppingCriteriaList, optional) – An instance of [StoppingCriteriaList]. List of instances of class derived from [StoppingCriteria] used to tell if the generation loop should stop.

  • max_length (int, optional, defaults to 20) – DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated tokens. The maximum length of the sequence to be generated.

  • pad_token_id (int, optional) – The id of the padding token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific kwargs that will be forwarded to the forward function of the model. If model is an encoder-decoder model the kwargs should include encoder_outputs.

Returns

[~generation_utils.BeamSearchDecoderOnlyOutput], [~generation_utils.BeamSearchEncoderDecoderOutput] or torch.LongTensor: A torch.LongTensor containing the generated tokens (default behaviour) or a [~generation_utils.BeamSearchDecoderOnlyOutput] if [~generation_utils.BeamSearchDecoderOnlyOutput] if model.config.is_encoder_decoder=False and return_dict_in_generate=True or a [~generation_utils.BeamSearchEncoderDecoderOutput] if model.config.is_encoder_decoder=True.

Examples:

```python >>> from transformers import ( … AutoTokenizer, … AutoModelForSeq2SeqLM, … LogitsProcessorList, … MinLengthLogitsProcessor, … HammingDiversityLogitsProcessor, … BeamSearchScorer, … ) >>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
>>> # lets run diverse beam search using 6 beams
>>> num_beams = 6
>>> # define decoder start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id
>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }
>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     max_length=model.config.max_length,
...     num_beams=num_beams,
...     device=model.device,
...     num_beam_groups=3,
... )
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         HammingDiversityLogitsProcessor(5.5, num_beams=6, num_beam_groups=3),
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )
>>> outputs = model.group_beam_search(
...     input_ids, beam_scorer, logits_processor=logits_processor, **model_kwargs
... )
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
```
half() torch.nn.modules.module.T#

Casts all floating point parameters and buffers to half datatype.

Note

This method modifies the module in-place.

Returns

self

Return type

Module

init_weights()#

If needed prunes and maybe initializes weights.

invert_attention_mask(encoder_attention_mask: torch.Tensor) torch.Tensor#

Invert an attention mask (e.g., switches 0. and 1.).

Parameters

encoder_attention_mask (torch.Tensor) – An attention mask.

Returns

The inverted attention mask.

Return type

torch.Tensor

property is_gradient_checkpointing: bool#

Whether gradient checkpointing is activated for this model or not.

Note that in other frameworks this feature can be referred to as “activation checkpointing” or “checkpoint activations”.

load_state_dict(state_dict: collections.OrderedDict[str, torch.Tensor], strict: bool = True)#

Copies parameters and buffers from state_dict into this module and its descendants. If strict is True, then the keys of state_dict must exactly match the keys returned by this module’s state_dict() function.

Parameters
  • state_dict (dict) – a dict containing parameters and persistent buffers.

  • strict (bool, optional) – whether to strictly enforce that the keys in state_dict match the keys returned by this module’s state_dict() function. Default: True

Returns

  • missing_keys is a list of str containing the missing keys

  • unexpected_keys is a list of str containing the unexpected keys

Return type

NamedTuple with missing_keys and unexpected_keys fields

Note

If a parameter or buffer is registered as None and its corresponding key exists in state_dict, load_state_dict() will raise a RuntimeError.

property model_: transformers.modeling_utils.PreTrainedModel#

Returns the underlying language model. This is an alias to simplify access.

classmethod model_class_from_config(config: transformers.configuration_utils.PretrainedConfig) Type[primeqa.mrc.models.task_model.ModelForDownstreamTasks]#

Dynamically creates and returns a model class from a PreTrainedConfig.

modules() Iterator[torch.nn.modules.module.Module]#

Returns an iterator over all modules in the network.

Yields

Module – a module in the network

Note

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.modules()):
        print(idx, '->', m)

0 -> Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
)
1 -> Linear(in_features=2, out_features=2, bias=True)
named_buffers(prefix: str = '', recurse: bool = True) Iterator[Tuple[str, torch.Tensor]]#

Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

Parameters
  • prefix (str) – prefix to prepend to all buffer names.

  • recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.

Yields

(string, torch.Tensor) – Tuple containing the name and buffer

Example:

>>> for name, buf in self.named_buffers():
>>>    if name in ['running_var']:
>>>        print(buf.size())
named_children() Iterator[Tuple[str, torch.nn.modules.module.Module]]#

Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

Yields

(string, Module) – Tuple containing a name and child module

Example:

>>> for name, module in model.named_children():
>>>     if name in ['conv4', 'conv5']:
>>>         print(module)
named_modules(memo: Optional[Set[torch.nn.modules.module.Module]] = None, prefix: str = '', remove_duplicate: bool = True)#

Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

Parameters
  • memo – a memo to store the set of modules already added to the result

  • prefix – a prefix that will be added to the name of the module

  • remove_duplicate – whether to remove the duplicated module instances in the result or not

Yields

(string, Module) – Tuple of name and module

Note

Duplicate modules are returned only once. In the following example, l will be returned only once.

Example:

>>> l = nn.Linear(2, 2)
>>> net = nn.Sequential(l, l)
>>> for idx, m in enumerate(net.named_modules()):
        print(idx, '->', m)

0 -> ('', Sequential(
  (0): Linear(in_features=2, out_features=2, bias=True)
  (1): Linear(in_features=2, out_features=2, bias=True)
))
1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
named_parameters(prefix: str = '', recurse: bool = True) Iterator[Tuple[str, torch.nn.parameter.Parameter]]#

Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

Parameters
  • prefix (str) – prefix to prepend to all parameter names.

  • recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields

(string, Parameter) – Tuple containing the name and parameter

Example:

>>> for name, param in self.named_parameters():
>>>    if name in ['bias']:
>>>        print(param.size())
num_parameters(only_trainable: bool = False, exclude_embeddings: bool = False) int#

Get number of (optionally, trainable or non-embeddings) parameters in the module.

Parameters
  • only_trainable (bool, optional, defaults to False) – Whether or not to return only the number of trainable parameters

  • exclude_embeddings (bool, optional, defaults to False) – Whether or not to return only the number of non-embeddings parameters

Returns

The number of parameters.

Return type

int

parameters(recurse: bool = True) Iterator[torch.nn.parameter.Parameter]#

Returns an iterator over module parameters.

This is typically passed to an optimizer.

Parameters

recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.

Yields

Parameter – module parameter

Example:

>>> for param in model.parameters():
>>>     print(type(param), param.size())
<class 'torch.Tensor'> (20L,)
<class 'torch.Tensor'> (20L, 1L, 5L, 5L)
post_init()#

A method executed at the end of each Transformer model initialization, to execute code that needs the model’s modules properly initialized (such as weight initialization).

prepare_inputs_for_generation(input_ids: torch.LongTensor, **kwargs) Dict[str, Any]#

Implement in subclasses of [PreTrainedModel] for custom behavior to prepare inputs in the generate method.

prune_heads(heads_to_prune: Dict[int, List[int]])#

Prunes heads of the base model.

Parameters

heads_to_prune (Dict[int, List[int]]) – Dictionary with keys being selected layer indices (int) and associated values being the list of heads to prune in said layer (list of int). For instance {1: [0, 2], 2: [2, 3]} will prune heads 0 and 2 on layer 1 and heads 2 and 3 on layer 2.

push_to_hub(repo_path_or_name: Optional[str] = None, repo_url: Optional[str] = None, use_temp_dir: bool = False, commit_message: Optional[str] = None, organization: Optional[str] = None, private: Optional[bool] = None, use_auth_token: Optional[Union[str, bool]] = None, **model_card_kwargs) str#

Upload the model checkpoint to the 🤗 Model Hub while synchronizing a local clone of the repo in repo_path_or_name.

Parameters
  • repo_path_or_name (str, optional) – Can either be a repository name for your model in the Hub or a path to a local folder (in which case the repository will have the name of that local folder). If not specified, will default to the name given by repo_url and a local directory with that name will be created.

  • repo_url (str, optional) – Specify this in case you want to push to an existing repository in the hub. If unspecified, a new repository will be created in your namespace (unless you specify an organization) with repo_name.

  • use_temp_dir (bool, optional, defaults to False) – Whether or not to clone the distant repo in a temporary directory or in repo_path_or_name inside the current working directory. This will slow things down if you are making changes in an existing repo since you will need to clone the repo before every push.

  • commit_message (str, optional) – Message to commit while pushing. Will default to “add model”.

  • organization (str, optional) – Organization in which you want to push your model (you must be a member of this organization).

  • private (bool, optional) – Whether or not the repository created should be private (requires a paying subscription).

  • use_auth_token (bool or str, optional) – The token to use as HTTP bearer authorization for remote files. If True, will use the token generated when running transformers-cli login (stored in ~/.huggingface). Will default to True if repo_url is not specified.

Returns

The url of the commit of your model in the given repository.

Return type

str

Examples:

```python from transformers import AutoModel

model = AutoModel.from_pretrained(“bert-base-cased”)

# Push the model to your namespace with the name “my-finetuned-bert” and have a local clone in the # my-finetuned-bert folder. model.push_to_hub(“my-finetuned-bert”)

# Push the model to your namespace with the name “my-finetuned-bert” with no local clone. model.push_to_hub(“my-finetuned-bert”, use_temp_dir=True)

# Push the model to an organization with the name “my-finetuned-bert” and have a local clone in the # my-finetuned-bert folder. model.push_to_hub(“my-finetuned-bert”, organization=”huggingface”)

# Make a change to an existing repo that has been cloned locally in my-finetuned-bert. model.push_to_hub(“my-finetuned-bert”, repo_url=”https://huggingface.co/sgugger/my-finetuned-bert”) ```

register_backward_hook(hook: Callable[[torch.nn.modules.module.Module, Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[None, torch.Tensor]]) torch.utils.hooks.RemovableHandle#

Registers a backward hook on the module.

This function is deprecated in favor of register_full_backward_hook() and the behavior of this function will change in future versions.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

register_buffer(name: str, tensor: Optional[torch.Tensor], persistent: bool = True) None#

Adds a buffer to the module.

This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s running_mean is not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting persistent to False. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’s state_dict.

Buffers can be accessed as attributes using given names.

Parameters
  • name (string) – name of the buffer. The buffer can be accessed from this module using the given name

  • tensor (Tensor or None) – buffer to be registered. If None, then operations that run on buffers, such as cuda, are ignored. If None, the buffer is not included in the module’s state_dict.

  • persistent (bool) – whether the buffer is part of this module’s state_dict.

Example:

>>> self.register_buffer('running_mean', torch.zeros(num_features))
classmethod register_for_auto_class(auto_class='AutoModel')#

Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class.

<Tip warning={true}>

This API is experimental and may have some slight breaking changes in the next releases.

</Tip>

Parameters

auto_class (str or type, optional, defaults to “AutoModel”) – The auto class to register this new model with.

register_forward_hook(hook: Callable[[...], None]) torch.utils.hooks.RemovableHandle#

Registers a forward hook on the module.

The hook will be called every time after forward() has computed an output. It should have the following signature:

hook(module, input, output) -> None or modified output

The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called after forward() is called.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

register_forward_pre_hook(hook: Callable[[...], None]) torch.utils.hooks.RemovableHandle#

Registers a forward pre-hook on the module.

The hook will be called every time before forward() is invoked. It should have the following signature:

hook(module, input) -> None or modified input

The input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to the forward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned(unless that value is already a tuple).

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

register_full_backward_hook(hook: Callable[[torch.nn.modules.module.Module, Union[Tuple[torch.Tensor, ...], torch.Tensor], Union[Tuple[torch.Tensor, ...], torch.Tensor]], Union[None, torch.Tensor]]) torch.utils.hooks.RemovableHandle#

Registers a backward hook on the module.

The hook will be called every time the gradients with respect to module inputs are computed. The hook should have the following signature:

hook(module, grad_input, grad_output) -> tuple(Tensor) or None

The grad_input and grad_output are tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place of grad_input in subsequent computations. grad_input will only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries in grad_input and grad_output will be None for all non-Tensor arguments.

For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.

Warning

Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.

Returns

a handle that can be used to remove the added hook by calling handle.remove()

Return type

torch.utils.hooks.RemovableHandle

register_module(name: str, module: Optional[torch.nn.modules.module.Module]) None#

Alias for add_module().

register_parameter(name: str, param: Optional[torch.nn.parameter.Parameter]) None#

Adds a parameter to the module.

The parameter can be accessed as an attribute using given name.

Parameters
  • name (string) – name of the parameter. The parameter can be accessed from this module using the given name

  • param (Parameter or None) – parameter to be added to the module. If None, then operations that run on parameters, such as cuda, are ignored. If None, the parameter is not included in the module’s state_dict.

requires_grad_(requires_grad: bool = True) torch.nn.modules.module.T#

Change if autograd should record operations on parameters in this module.

This method sets the parameters’ requires_grad attributes in-place.

This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).

See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.

Parameters

requires_grad (bool) – whether autograd should record operations on parameters in this module. Default: True.

Returns

self

Return type

Module

reset_memory_hooks_state()#

Reset the mem_rss_diff attribute of each module (see [~modeling_utils.ModuleUtilsMixin.add_memory_hooks]).

resize_token_embeddings(new_num_tokens: Optional[int] = None) torch.nn.modules.sparse.Embedding#

Resizes input token embeddings matrix of the model if new_num_tokens != config.vocab_size.

Takes care of tying weights embeddings afterwards if the model class has a tie_weights() method.

Parameters

new_num_tokens (int, optional) – The number of new tokens in the embedding matrix. Increasing the size will add newly initialized vectors at the end. Reducing the size will remove vectors from the end. If not provided or None, just returns a pointer to the input tokens torch.nn.Embedding module of the model without doing anything.

Returns

Pointer to the input tokens Embeddings Module of the model.

Return type

torch.nn.Embedding

sample(input_ids: torch.LongTensor, logits_processor: Optional[transformers.generation_logits_process.LogitsProcessorList] = None, stopping_criteria: Optional[transformers.generation_stopping_criteria.StoppingCriteriaList] = None, logits_warper: Optional[transformers.generation_logits_process.LogitsProcessorList] = None, max_length: Optional[int] = None, pad_token_id: Optional[int] = None, eos_token_id: Optional[int] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_scores: Optional[bool] = None, return_dict_in_generate: Optional[bool] = None, synced_gpus: Optional[bool] = False, **model_kwargs) Union[transformers.generation_utils.SampleEncoderDecoderOutput, transformers.generation_utils.SampleDecoderOnlyOutput, torch.LongTensor]#

Generates sequences for models with a language modeling head using multinomial sampling.

Parameters
  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) – The sequence used as a prompt for the generation.

  • logits_processor (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsProcessor] used to modify the prediction scores of the language modeling head applied at each generation step.

  • stopping_criteria (StoppingCriteriaList, optional) – An instance of [StoppingCriteriaList]. List of instances of class derived from [StoppingCriteria] used to tell if the generation loop should stop.

  • logits_warper (LogitsProcessorList, optional) – An instance of [LogitsProcessorList]. List of instances of class derived from [LogitsWarper] used to warp the prediction score distribution of the language modeling head applied before multinomial sampling at each generation step.

  • max_length (int, optional, defaults to 20) – DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated tokens. The maximum length of the sequence to be generated.

  • pad_token_id (int, optional) – The id of the padding token.

  • eos_token_id (int, optional) – The id of the end-of-sequence token.

  • output_attentions (bool, optional, defaults to False) – Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more details.

  • output_hidden_states (bool, optional, defaults to False) – Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more details.

  • output_scores (bool, optional, defaults to False) – Whether or not to return the prediction scores. See scores under returned tensors for more details.

  • return_dict_in_generate (bool, optional, defaults to False) – Whether or not to return a [~file_utils.ModelOutput] instead of a plain tuple.

  • synced_gpus (bool, optional, defaults to False) – Whether to continue running the while loop until max_length (needed for ZeRO stage 3)

  • model_kwargs – Additional model specific kwargs will be forwarded to the forward function of the model. If model is an encoder-decoder model the kwargs should include encoder_outputs.

Returns

[~generation_utils.SampleDecoderOnlyOutput], [~generation_utils.SampleEncoderDecoderOutput] or torch.LongTensor: A torch.LongTensor containing the generated tokens (default behaviour) or a [~generation_utils.SampleDecoderOnlyOutput] if model.config.is_encoder_decoder=False and return_dict_in_generate=True or a [~generation_utils.SampleEncoderDecoderOutput] if model.config.is_encoder_decoder=True.

Examples:

```python >>> from transformers import ( … AutoTokenizer, … AutoModelForCausalLM, … LogitsProcessorList, … MinLengthLogitsProcessor, … TopKLogitsWarper, … TemperatureLogitsWarper, … )

>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
>>> model.config.pad_token_id = model.config.eos_token_id
>>> input_prompt = "Today is a beautiful day, and"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(15, eos_token_id=model.config.eos_token_id),
...     ]
... )
>>> # instantiate logits processors
>>> logits_warper = LogitsProcessorList(
...     [
...         TopKLogitsWarper(50),
...         TemperatureLogitsWarper(0.7),
...     ]
... )
>>> outputs = model.sample(input_ids, logits_processor=logits_processor, logits_warper=logits_warper)
>>> print("Generated:", tokenizer.batch_decode(outputs, skip_special_tokens=True))
```
save_pretrained(save_directory: typing.Union[str, os.PathLike], save_config: bool = True, state_dict: typing.Optional[dict] = None, save_function: typing.Callable = <function save>, push_to_hub: bool = False, **kwargs)#

Save a model and its configuration file to a directory, so that it can be re-loaded using the [`~PreTrainedModel.from_pretrained]` class method.

Parameters
  • save_directory (str or os.PathLike) – Directory to which to save. Will be created if it doesn’t exist.

  • save_config (bool, optional, defaults to True) – Whether or not to save the config of the model. Useful when in distributed training like TPUs and need to call this function on all processes. In this case, set save_config=True only on the main process to avoid race conditions.

  • state_dict (nested dictionary of torch.Tensor) – The state dictionary of the model to save. Will default to self.state_dict(), but can be used to only save parts of the model or if special precautions need to be taken when recovering the state dictionary of a model (like when using model parallelism).

  • save_function (Callable) – The function to use to save the state dictionary. Useful on distributed training like TPUs when one need to replace torch.save by another method.

  • push_to_hub (bool, optional, defaults to False) –

    Whether or not to push your model to the Hugging Face model hub after saving it.

    <Tip warning={true}>

    Using push_to_hub=True will synchronize the repository you are pushing to with save_directory, which requires save_directory to be a local clone of the repo you are pushing to if it’s an existing folder. Pass along temp_dir=True to use a temporary directory instead.

    </Tip>

  • kwargs – Additional key word arguments passed along to the [~file_utils.PushToHubMixin.push_to_hub] method.

set_extra_state(state: Any)#

This function is called from load_state_dict() to handle any extra state found within the state_dict. Implement this function and a corresponding get_extra_state() for your module if you need to store extra state within its state_dict.

Parameters

state (dict) – Extra state from the state_dict

set_input_embeddings(value: torch.nn.modules.module.Module)#

Set model’s input embeddings.

Parameters

value (nn.Module) – A module mapping vocabulary to hidden states.

set_task_head(task_head: str) None#
Parameters

task_head – name of the task head to activate.

Raises

KeyError – model does not have task head with name task_head.

share_memory() torch.nn.modules.module.T#

See torch.Tensor.share_memory_()

state_dict(destination=None, prefix='', keep_vars=False)#

Returns a dictionary containing a whole state of the module.

Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to None are not included.

Returns

a dictionary containing a whole state of the module

Return type

dict

Example:

>>> module.state_dict().keys()
['bias', 'weight']
property task_head: primeqa.mrc.models.heads.abstract.AbstractTaskHead#

Return the current task head or raises a ValueError if it has not yet been set.

tie_weights()#

Tie the weights between the input embeddings and the output embeddings.

If the torchscript flag is set in the configuration, can’t handle parameter sharing so we are cloning the weights instead.

to(*args, **kwargs)#

Moves and/or casts the parameters and buffers.

This can be called as

to(device=None, dtype=None, non_blocking=False)
to(dtype, non_blocking=False)
to(tensor, non_blocking=False)
to(memory_format=torch.channels_last)

Its signature is similar to torch.Tensor.to(), but only accepts floating point or complex dtypes. In addition, this method will only cast the floating point or complex parameters and buffers to dtype (if given). The integral parameters and buffers will be moved device, if that is given, but with dtypes unchanged. When non_blocking is set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.

See below for examples.

Note

This method modifies the module in-place.

Parameters
  • device (torch.device) – the desired device of the parameters and buffers in this module

  • dtype (torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this module

  • tensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module

  • memory_format (torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)

Returns

self

Return type

Module

Examples:

>>> linear = nn.Linear(2, 2)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]])
>>> linear.to(torch.double)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1913, -0.3420],
        [-0.5113, -0.2325]], dtype=torch.float64)
>>> gpu1 = torch.device("cuda:1")
>>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
>>> cpu = torch.device("cpu")
>>> linear.to(cpu)
Linear(in_features=2, out_features=2, bias=True)
>>> linear.weight
Parameter containing:
tensor([[ 0.1914, -0.3420],
        [-0.5112, -0.2324]], dtype=torch.float16)

>>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
>>> linear.weight
Parameter containing:
tensor([[ 0.3741+0.j,  0.2382+0.j],
        [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
>>> linear(torch.ones(3, 2, dtype=torch.cdouble))
tensor([[0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j],
        [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
to_empty(*, device: Union[str, torch.device]) torch.nn.modules.module.T#

Moves the parameters and buffers to the specified device without copying storage.

Parameters

device (torch.device) – The desired device of the parameters and buffers in this module.

Returns

self

Return type

Module

train(mode: bool = True) torch.nn.modules.module.T#

Sets the module in training mode.

This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. Dropout, BatchNorm, etc.

Parameters

mode (bool) – whether to set training mode (True) or evaluation mode (False). Default: True.

Returns

self

Return type

Module

type(dst_type: Union[torch.dtype, str]) torch.nn.modules.module.T#

Casts all parameters and buffers to dst_type.

Note

This method modifies the module in-place.

Parameters

dst_type (type or string) – the desired type

Returns

self

Return type

Module

xpu(device: Optional[Union[int, torch.device]] = None) torch.nn.modules.module.T#

Moves all model parameters and buffers to the XPU.

This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.

Note

This method modifies the module in-place.

Parameters

device (int, optional) – if specified, all parameters will be copied to that device

Returns

self

Return type

Module

zero_grad(set_to_none: bool = False) None#

Sets gradients of all model parameters to zero. See similar function under torch.optim.Optimizer for more context.

Parameters

set_to_none (bool) – instead of setting to zero, set the grads to None. See torch.optim.Optimizer.zero_grad() for details.