GPTNeoForTokenClassification

ngTensor of shape (batch_size, input_ids_length), optional) —
Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
0 corresponds to a sentence A token,
1 corresponds to a sentence B token.
What are token type IDs?   position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].
What are position IDs?   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Optionally, instead of passing input_ids you can choose to directly pass an embedded repr


GPTNeoForTokenClassification

esentation. This
is useful if you want more control over how to convert input_ids indices into associated vectors than the
model’s internal embedding lookup matrix.
If past_key_values is used, optionally only the last inputs_embeds have to be input (see
past_key_values).   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   labels (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Labels for computing the sequence cl


GPTNeoForTokenClassification

assification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If
config.num_labels > 1 a classification loss is computed (Cross-Entropy).   Returns
transformers.modeling_outputs.TokenClassifierOutput or tuple(torch.FloatTensor)

A transformers.modeling_outputs.TokenClassifierOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (GPTNeoConfig) and inputs.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided)  — Classification loss.
logits (torch.FloatTensor of shape (batch_size, sequence_length, config.num_labels)) — Classification scores (before SoftMax).
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.F


GPTNeoForTokenClassification

loatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The GPTNeoForTokenClassification forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter


GPTNeoForTokenClassification

 silently ignores them.  Example:   Copied >>> from transformers import AutoTokenizer, GPTNeoForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-125m")
>>> model = GPTNeoForTokenClassification.from_pretrained("EleutherAI/gpt-neo-125m")
>>> inputs = tokenizer(
...     "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )
>>> with torch.no_grad():
...     logits = model(**inputs).logits
>>> predicted_token_class_ids = logits.argmax(-1)
>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)


FlaxGPTNeoModel

class transformers.FlaxGPTNeoModel  < source > ( config: GPTNeoConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs  )   Parameters   config (GPTNeoConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.   dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) —
The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and
jax.numpy.bfloat16 (on TPUs).
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
specified all the computation will be performed with the given dtype.
Note that this only specifies the dtype of the computation and does not influence the dtype


FlaxGPTNeoModel

 of model
parameters.
If you wish to change the dtype of the model parameters, see to_fp16() and
to_bf16().    The bare GPTNeo Model transformer outputting raw hidden-states without any specific head on top. This model inherits from FlaxPreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a Flax Linen
flax.nn.Module subclass. Use it as a
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: Just-In-Time (JIT) compilation Automatic Differentiation Vectorization Parallelization  __call__  < source > ( input_ids attention_mask = None position_ids = None params: dict = None past_key_values: dict = None dropout_rng: PRNGKey = None train: bool = Fal


FlaxGPTNeoModel

se output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_flax_outputs.FlaxBaseModelOutput or tuple(torch.FloatTensor)  Parameters   input_ids (numpy.ndarray of shape (batch_size, input_ids_length)) —
input_ids_length = sequence_length. Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) —
Indices of positions of each input seque


FlaxGPTNeoModel

nce tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].   past_key_values (Dict[str, np.ndarray], optional, returned by init_cache or when passing previous past_key_values) —
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
auto-regressive decoding. Pre-computed key and value hidden-states are of shape [batch_size, max_length].   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_flax_outputs.FlaxBaseModelOutput or tuple(


FlaxGPTNeoModel

torch.FloatTensor)

A transformers.modeling_flax_outputs.FlaxBaseModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (GPTNeoConfig) and inputs.
last_hidden_state (jnp.ndarray of shape (batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.
hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tupl


FlaxGPTNeoModel

e of jnp.ndarray (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The FlaxGPTNeoPreTrainedModel forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:   Copied >>> from transformers import AutoTokenizer, FlaxGPTNeoModel
>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B")
>>> model = FlaxGPTNeoModel.from_pretrained("EleutherAI/gpt-neo-1.3B")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_sta


FlaxGPTNeoForCausalLM

class transformers.FlaxGPTNeoForCausalLM  < source > ( config: GPTNeoConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs  )   Parameters   config (GPTNeoConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.   dtype (jax.numpy.dtype, optional, defaults to jax.numpy.float32) —
The data type of the computation. Can be one of jax.numpy.float32, jax.numpy.float16 (on GPUs) and
jax.numpy.bfloat16 (on TPUs).
This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
specified all the computation will be performed with the given dtype.
Note that this only specifies the dtype of the computation and does not influence the dtype of model


FlaxGPTNeoForCausalLM

parameters.
If you wish to change the dtype of the model parameters, see to_fp16() and
to_bf16().    The GPTNeo Model transformer with a language modeling head on top (linear layer with weights tied to the input
embeddings). This model inherits from FlaxPreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a Flax Linen
flax.nn.Module subclass. Use it as a
regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior. Finally, this model supports inherent JAX features such as: Just-In-Time (JIT) compilation Automatic Differentiation Vectorization Parallelization  __call__  < source > ( input_ids attention_mask = None position_ids = None params: dict = None past_key_values: dict = None dropout_rng: PRNGKey = None train: bool = Fa


FlaxGPTNeoForCausalLM

lse output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_flax_outputs.FlaxMaskedLMOutput or tuple(torch.FloatTensor)  Parameters   input_ids (numpy.ndarray of shape (batch_size, input_ids_length)) —
input_ids_length = sequence_length. Indices of input sequence tokens in the vocabulary.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (numpy.ndarray of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (numpy.ndarray of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in th


FlaxGPTNeoForCausalLM

e position embeddings. Selected in the range [0, config.max_position_embeddings - 1].   past_key_values (Dict[str, np.ndarray], optional, returned by init_cache or when passing previous past_key_values) —
Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
auto-regressive decoding. Pre-computed key and value hidden-states are of shape [batch_size, max_length].   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_flax_outputs.FlaxMaskedLMOutput or tuple(torch.FloatTensor)

A transform


FlaxGPTNeoForCausalLM

ers.modeling_flax_outputs.FlaxMaskedLMOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (GPTNeoConfig) and inputs.
logits (jnp.ndarray of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
hidden_states (tuple(jnp.ndarray), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of jnp.ndarray (one for the output of the embeddings + one for the output of each layer) of shape
(batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (tuple(jnp.ndarray), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of jnp.ndarray (one for ea


FlaxGPTNeoForCausalLM

ch layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The FlaxGPTNeoPreTrainedModel forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:   Copied >>> from transformers import AutoTokenizer, FlaxGPTNeoForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B")
>>> model = FlaxGPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")
>>> outputs = model(**inputs)
>>> # retrieve logts for next token
>>> next_token_logits = outputs.logits[:, -1]


Reformer

DISCLAIMER: This model is still a work in progress, if you see something strange, file a Github Issue.


Overview

The Reformer model was proposed in the paper Reformer: The Efficient Transformer by Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya.
The abstract from the paper is the following:
Large Transformer models routinely achieve state-of-the-art results on a number of tasks but training these models can
be prohibitively costly, especially on long sequences. We introduce two techniques to improve the efficiency of
Transformers. For one, we replace dot-product attention by one that uses locality-sensitive hashing, changing its
complexity from O(L^2) to O(Llog(L)), where L is the length of the sequence. Furthermore, we use reversible residual
layers instead of the standard residuals, which allows storing activations only once in the training process instead of
N times, where N is the number of layers. The resulting model, the Reformer, performs on par with Transformer models
while being much more memory-efficient and much faster on long sequences.
This mod


Overview

el was contributed by patrickvonplaten. The Authors’ code can be
found here.
Tips:
Reformer does not work with torch.nn.DataParallel due to a bug in PyTorch, see issue #36035. Use Axial position encoding (see below for more details). It’s a mechanism to avoid having a huge positional encoding matrix (when the sequence length is very big) by factorizing it into smaller matrices. Replace traditional attention by LSH (local-sensitive hashing) attention (see below for more details). It’s a technique to avoid computing the full product query-key in the attention layers. Avoid storing the intermediate results of each layer by using reversible transformer layers to obtain them during the backward pass (subtracting the residuals from the input of the next layer gives them back) or recomputing them for results inside a given layer (less efficient than storing them but saves memory). Compute the feedforward operations by chunks and not on the whole batch


Axial Positional Encodings

Axial Positional Encodings were first implemented in Google’s trax library
and developed by the authors of this model’s paper. In models that are treating very long input sequences, the
conventional position id encodings store an embedings vector of size ddd being the config.hidden_size for
every position i,…,nsi, \ldots, n_si,…,ns, with nsn_sns being config.max_embedding_size. This means that having
a sequence length of ns=219≈0.5Mn_s = 2^{19} \approx 0.5Mns=219≈0.5M and a config.hidden_size of d=210≈1000d = 2^{10} \approx 1000d=210≈1000
would result in a position encoding matrix:
Xi,j, with i∈[1,…,d] and j∈[1,…,ns]X_{i,j}, \text{ with } i \in \left[1,\ldots, d\right] \text{ and } j \in \left[1,\ldots, n_s\right]Xi,j, with i∈[1,…,d] and j∈[1,…,ns]
which alone has over 500M parameters to store. Axial positional encodings factorize Xi,jX_{i,j}Xi,j into two matrices:
Xi,j1, with i∈[1,…,d1] and j∈[1,…,ns1]X^{1}_{i,j}, \tex


Axial Positional Encodings

t{ with } i \in \left[1,\ldots, d^1\right] \text{ and } j \in \left[1,\ldots, n_s^1\right]Xi,j1, with i∈[1,…,d1] and j∈[1,…,ns1]
and
Xi,j2, with i∈[1,…,d2] and j∈[1,…,ns2]X^{2}_{i,j}, \text{ with } i \in \left[1,\ldots, d^2\right] \text{ and } j \in \left[1,\ldots, n_s^2\right]Xi,j2, with i∈[1,…,d2] and j∈[1,…,ns2]
with:
d=d1+d2 and ns=ns1×ns2.d = d^1 + d^2 \text{ and } n_s = n_s^1 \times n_s^2 .d=d1+d2 and ns=ns1×ns2.
Therefore the following holds:
Xi,j={Xi,k1,if  i<d1 with k=jmod  ns1Xi−d1,l2,if i≥d1 with l=⌊jns1⌋X_{i,j} = \begin{cases}
X^{1}_{i, k}, & \text{if }\ i < d^1 \text{ with } k = j \mod n_s^1 \\
X^{2}_{i - d^1, l}, & \text{if } i \ge d^1 \text{ with } l = \lfloor\frac{j}{n_s^1}\rfloor
\end{cases}Xi,j={Xi,k1,Xi−d1,l2,if  i<d1 with k=jmodns1if i≥d1 with l=⌊ns1j⌋
Intuitively, this means that a position embedding vector xj∈Rdx_j \in \mathbb{R}^{d}xj∈Rd is now the composition of two
factorized embedding


Axial Positional Encodings

 vectors: xk,l1+xl,k2x^1_{k, l} + x^2_{l, k}xk,l1+xl,k2, where as the config.max_embedding_size dimension
jjj is factorized into k and lk \text{ and } lk and l. This design ensures that each position embedding vector
xjx_jxj is unique.
Using the above example again, axial position encoding with d1=29,d2=29,ns1=29,ns2=210d^1 = 2^9, d^2 = 2^9, n_s^1 = 2^9, n_s^2 = 2^{10}d1=29,d2=29,ns1=29,ns2=210
can drastically reduced the number of parameters from 500 000 000 to 218+219≈7800002^{18} + 2^{19} \approx 780 000218+219≈780000 parameters, this means 85% less memory usage.
In practice, the parameter config.axial_pos_embds_dim is set to a tuple (d1,d2)(d^1, d^2)(d1,d2) which sum has to be
equal to config.hidden_size and config.axial_pos_shape is set to a tuple (ns1,ns2)(n_s^1, n_s^2)(ns1,ns2) which
product has to be equal to config.max_embedding_size, which during training has to be equal to the sequence
length of the input_id


LSH Self Attention

In Locality sensitive hashing (LSH) self attention the key and query projection weights are tied. Therefore, the key
query embedding vectors are also tied. LSH self attention uses the locality sensitive hashing mechanism proposed in
Practical and Optimal LSH for Angular Distance to assign each of the tied key
query embedding vectors to one of config.num_buckets possible buckets. The premise is that the more “similar”
key query embedding vectors (in terms of cosine similarity) are to each other, the more likely they are assigned to
the same bucket.
The accuracy of the LSH mechanism can be improved by increasing config.num_hashes or directly the argument
num_hashes of the forward function so that the output of the LSH self attention better approximates the output
of the “normal” full self attention. The buckets are th


LSH Self Attention

en sorted and chunked into query key embedding vector chunks
each of length config.lsh_chunk_length. For each chunk, the query embedding vectors attend to its key vectors
(which are tied to themselves) and to the key embedding vectors of config.lsh_num_chunks_before previous
neighboring chunks and config.lsh_num_chunks_after following neighboring chunks.
For more information, see the original Paper or this great blog post.
Note that config.num_buckets can also be factorized into a list (nbuckets1,nbuckets2)(n_{\text{buckets}}^1,
n_{\text{buckets}}^2)(nbuckets1,nbuckets2). This way instead of assigning the query key embedding vectors to one of (1,…,nbuckets)(1,\ldots,
n_{\text{buckets}})(1,…,nbuckets) they are assigned to one of (1−1,…,nbuckets1−1,…,1−nbuckets2,…,nbuckets1−nbuckets2)(1-1,\ldots, n_{\text{buckets}}


LSH Self Attention

^1-1, \ldots,
1-n_{\text{buckets}}^2, \ldots, n_{\text{buckets}}^1-n_{\text{buckets}}^2)(1−1,…,nbuckets1−1,…,1−nbuckets2,…,nbuckets1−nbuckets2). This is crucial for very long sequences to
save memory.
When training a model from scratch, it is recommended to leave config.num_buckets=None, so that depending on the
sequence length a good value for num_buckets is calculated on the fly. This value will then automatically be
saved in the config and should be reused for inference.
Using LSH self attention, the memory and time complexity of the query-key matmul operation can be reduced from
O(ns×ns)\mathcal{O}(n_s \times n_s)O(ns×ns) to O(ns×log(ns))\mathcal{O}(n_s \times \log(n_s))O(ns×log(ns)), which usually represents the memory
and time bottleneck in a transformer model, with nsn_sns being the sequence length.


Local Self Attention

Local self attention is essentially a “normal” self attention layer with key, query and value projections, but is
chunked so that in each chunk of length config.local_chunk_length the query embedding vectors only attends to
the key embedding vectors in its chunk and to the key embedding vectors of config.local_num_chunks_before
previous neighboring chunks and config.local_num_chunks_after following neighboring chunks.
Using Local self attention, the memory and time complexity of the query-key matmul operation can be reduced from
O(ns×ns)\mathcal{O}(n_s \times n_s)O(ns×ns) to O(ns×log(ns))\mathcal{O}(n_s \times \log(n_s))O(ns×log(ns)), which usually represents the memory
and time bottleneck in a transformer model, with nsn_sns being the sequence length.


Training

During training, we must ensure that the sequence length is set to a value that can be divided by the least common
multiple of config.lsh_chunk_length and config.local_chunk_length and that the parameters of the Axial
Positional Encodings are correctly set as described above. Reformer is very memory efficient so that the model can
easily be trained on sequences as long as 64000 tokens.
For training, the ReformerModelWithLMHead should be used as follows:
  Copied input_ids = tokenizer.encode("This is a sentence from the training data", return_tensors="pt")
loss = model(input_ids, labels=input_ids)[0]


Documentation resources

Text classification task guide Question answering task guide Causal language modeling task guide Masked language modeling task guide


ReformerConfig

class transformers.ReformerConfig  < source > ( attention_head_size = 64 attn_layers = ['local', 'lsh', 'local', 'lsh', 'local', 'lsh'] axial_norm_std = 1.0 axial_pos_embds = True axial_pos_shape = [64, 64] axial_pos_embds_dim = [64, 192] chunk_size_lm_head = 0 eos_token_id = 2 feed_forward_size = 512 hash_seed = None hidden_act = 'relu' hidden_dropout_prob = 0.05 hidden_size = 256 initializer_range = 0.02 is_decoder = False layer_norm_eps = 1e-12 local_num_chunks_before = 1 local_num_chunks_after = 0 local_attention_probs_dropout_prob = 0.05 local_attn_chunk_length = 64 lsh_attn_chunk_length = 64 lsh_attention_probs_dropout_prob = 0.0 lsh_num_chunks_before = 1 lsh_num_chunks_after = 0 max_position_embeddings = 4096 num_attention_heads = 12 num_buckets = None num_hashes = 1 pad_token_id = 0 vocab_size = 320 tie_word_embeddings = False use_cache = True classifier_dropout = None **kwargs  )   Parameters   attention_head_size (int, optiona


ReformerConfig

l, defaults to 64) —
Dimensionality of the projected key, query and value vectors   attn_layers (List[str], optional, defaults to ["local", "lsh", "local", "lsh", "local", "lsh"]) —
List of attention layer types in ascending order. It can be chosen between a LSHSelfAttention layer
("lsh") and a LocalSelfAttention layer ("local").
For more information on LSHSelfAttention layer, see LSH Self Attention. For
more information on LocalSelfAttention layer, see Local Self Attention.   axial_pos_embds (bool, optional, defaults to True) —
Whether or not to use axial position embeddings. For more information on how axial position embeddings
work, see Axial Position Encodings.   axial_norm_std (float, optional, defaults to 1.0) —
The standard deviation of the normal_initializer for initializing the weight matrices of the axial
positional encodings.   axial_pos_shape (List[int], optional, defaults to [64, 64]) —
The position dims of the axial positi


ReformerConfig

on encodings. During training, the product of the position dims has to
be equal to the sequence length.
For more information on how axial position embeddings work, see Axial Position
Encodings.   axial_pos_embds_dim (List[int], optional, defaults to [64, 192]) —
The embedding dims of the axial position encodings. The sum of the embedding dims has to be equal to the
hidden size.
For more information on how axial position embeddings work, see Axial Position
Encodings.   chunk_size_lm_head (int, optional, defaults to 0) —
The chunk size of the final language model feed forward head layer. A chunk size of 0 means that the feed
forward layer is not chunked. A chunk size of n means that the feed forward layer processes n <
sequence_length embeddings at a time.
For more information on feed forward chunking, see How does Feed Forward Chunking
work?.   eos_token_id (int, optional, defaults to 2) —
The token id for the end-of-sentence token.   fe


ReformerConfig

ed_forward_size (int, optional, defaults to 512) —
Dimensionality of the feed_forward layer in the residual attention block.   hash_seed (int, optional) —
Seed that can be used to make local sensitive hashing in LSHSelfAttention deterministic. This should only
be set for testing purposed. For evaluation and training purposes hash_seed should be left as None to
ensure fully random rotations in local sensitive hashing scheme.   hidden_act (str or Callable, optional, defaults to "relu") —
The non-linear activation function (function or string) in the feed forward layer in the residual attention
block. If string, "gelu", "relu", "silu" and "gelu_new" are supported.   hidden_dropout_prob (float, optional, defaults to 0.05) —
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.   hidden_size (int, optional, defaults to 256) —
Dimensionality of the output hidden states of the residual attention blocks.


ReformerConfig

   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   is_decoder (bool, optional, defaults to False) —
Whether or not to use a causal mask in addition to the attention_mask passed to ReformerModel. When
using the Reformer for causal language modeling, this argument should be set to True.   layer_norm_eps (float, optional, defaults to 1e-12) —
The epsilon used by the layer normalization layers.   local_chunk_length (int, optional, defaults to 64) —
Length of chunk which attends to itself in LocalSelfAttention. Chunking reduces memory complexity from
sequence length x sequence length (self attention) to chunk length x chunk length x sequence length / chunk
length (chunked self attention).   local_num_chunks_before (int, optional, defaults to 1) —
Number of previous neighbouring chunks to attend to in LocalSelfAttention layer to itself.


ReformerConfig

  local_num_chunks_after (int, optional, defaults to 0) —
Number of following neighbouring chunks to attend to in LocalSelfAttention layer in addition to itself.   local_attention_probs_dropout_prob (float, optional, defaults to 0.1) —
The dropout ratio for the attention probabilities in LocalSelfAttention.   lsh_attn_chunk_length (int, optional, defaults to 64) —
Length of chunk which attends to itself in LSHSelfAttention. Chunking reduces memory complexity from
sequence length x sequence length (self attention) to chunk length x chunk length x sequence length / chunk
length (chunked self attention).   lsh_num_chunks_before (int, optional, defaults to 1) —
Number of previous neighbouring chunks to attend to in LSHSelfAttention layer to itself.   lsh_num_chunks_after (int, optional, defaults to 0) —
Number of following neighbouring chunks to attend to in LSHSelfAttention layer to itself.   lsh_attention_probs_dropout_prob (float, option


ReformerConfig

al, defaults to 0.1) —
The dropout ratio for the attention probabilities in LSHSelfAttention.   max_position_embeddings (int, optional, defaults to 4096) —
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).   num_attention_heads (int, optional, defaults to 12) —
Number of attention heads for each attention layer in the Transformer encoder.   num_buckets (int or List[int], optional) —
Number of buckets, the key query vectors can be “hashed into” using the locality sensitive hashing scheme.
Each query key vector is hashed into a hash in 1, ..., num_buckets. The number of buckets can also be
factorized into a list for improved memory complexity. In this case, each query key vector is hashed into a
hash in 1-1, 1-2, ..., num_buckets[0]-1, ..., num_buckets[0]-num_buckets[1] if num_buckets is
factorized into two factors. The number of buckets (or


ReformerConfig

 the product the factors) should approximately equal
sequence length / lsh_chunk_length. If num_buckets not set, a good value is calculated on the fly.   num_hashes (int, optional, defaults to 1) —
Number of hashing rounds (e.g., number of random rotations) in Local Sensitive Hashing scheme. The higher
num_hashes, the more accurate the LSHSelfAttention becomes, but also the more memory and time intensive
the hashing becomes.   pad_token_id (int, optional, defaults to 0) —
The token id for the padding token.   vocab_size (int, optional, defaults to 320) —\
Vocabulary size of the Reformer model. Defines the number of different tokens that can be represented by
the inputs_ids passed when calling ReformerModel.   tie_word_embeddings (bool, optional, defaults to False) —
Whether to tie input and output embeddings.   use_cache (bool, optional, defaults to True) —
Whether or not the model should return the last key/values attentions (not used


ReformerConfig

by all models).   classifier_dropout (float, optional) —
The dropout ratio for the classification head.    This is the configuration class to store the configuration of a ReformerModel. It is used to instantiate a
Reformer model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the ReFormer
google/reformer-crime-and-punishment architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Examples:   Copied >>> from transformers import ReformerConfig, ReformerModel
>>> # Initializing a Reformer configuration
>>> configuration = ReformerConfig()
>>> # Initializing a Reformer model (with random weights)
>>> model = ReformerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.co


ReformerTokenizer

class transformers.ReformerTokenizer  < source > ( vocab_file eos_token = '</s>' unk_token = '<unk>' additional_special_tokens = [] sp_model_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = None **kwargs  )   Parameters   vocab_file (str) —
SentencePiece file (generally has a .spm extension) that
contains the vocabulary necessary to instantiate a tokenizer.   eos_token (str, optional, defaults to "</s>") —
The end of sequence token.
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
The token used is the sep_token.
   unk_token (str, optional, defaults to "<unk>") —
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.   additional_special_tokens (List[str], optional, defaults to []) —
Additional special tokens used by the tokenizer.   sp_model_kwargs (dict, optional) —
Will be passed to t


ReformerTokenizer

he SentencePieceProcessor.__init__() method. The Python wrapper for
SentencePiece can be used, among other things,
to set:
enable_sampling: Enable subword regularization.
nbest_size: Sampling parameters for unigram. Invalid for BPE-Dropout.
nbest_size = {0,1}: No sampling is performed.
nbest_size > 1: samples from the nbest_size results.
nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
using forward-filtering-and-backward-sampling algorithm.
alpha: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
BPE-dropout.
    Construct a Reformer tokenizer. Based on SentencePiece . This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.  save_vocabulary  < source > ( save_directory: str filename_prefix: typing.Optional[str] = None  )


ReformerTokenizerFast

class transformers.ReformerTokenizerFast  < source > ( vocab_file = None tokenizer_file = None eos_token = '</s>' unk_token = '<unk>' additional_special_tokens = [] **kwargs  )   Parameters   vocab_file (str) —
SentencePiece file (generally has a .spm extension) that
contains the vocabulary necessary to instantiate a tokenizer.   eos_token (str, optional, defaults to "</s>") —
The end of sequence token.
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
The token used is the sep_token.
   unk_token (str, optional, defaults to "<unk>") —
The unknown token. A t


ReformerTokenizerFast

oken that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.   pad_token (str, optional, defaults to "<pad>") —
The token used for padding, for example when batching sequences of different lengths.   additional_special_tokens (List[str], optional) —
Additional special tokens used by the tokenizer.    Construct a “fast” Reformer tokenizer (backed by HuggingFace’s tokenizers library). Based on
Unigram. This tokenizer inherits from PreTrainedTokenizerFast which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.


ReformerModel

class transformers.ReformerModel  < source > ( config  )   Parameters   config (ReformerConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.    The bare Reformer Model transformer outputting raw hidden-stateswithout any specific head on top.
Reformer was proposed in Reformer: The Efficient Transformer by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all m


ReformerModel

atter related to general usage
and behavior.  forward  < source > ( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None past_buckets_states: typing.Optional[typing.List[typing.Tuple[torch.Tensor]]] = None use_cache: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.models.reformer.modeling_reformer.ReformerModelOutput or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. During training the input_ids sequence_length has


ReformerModel

to be
a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices
are automatically padded to be a multiple of the chunk length.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].
What are position IDs?   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_h


ReformerModel

eads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert input_ids indices into associated vectors than the
model’s internal embedding lookup matrix.   num_hashes (int, optional) —
The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites
the default defined in config.num_hashes.
For more information, see num_hashes in ReformerConfig.   past_buckets_states (List[Tuple(torch.LongTensor, torch.FloatTensor)], optional) —
List of Tuple(torch.LongTensor, torch.FloatTensor of leng


ReformerModel

th config.n_layers, with the first element
being the previous buckets of shape (batch_size, num_heads, num_hashes, sequence_length)) and the
second being the previous hidden_states of shape (batch_size, sequence_length, hidden_size)).
Contains precomputed hidden-states and buckets (only relevant for LSH Self-Attention). Can be used to speed
up sequential decoding.   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOu


ReformerModel

tput instead of a plain tuple.   Returns
transformers.models.reformer.modeling_reformer.ReformerModelOutput or tuple(torch.FloatTensor)

A transformers.models.reformer.modeling_reformer.ReformerModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (ReformerConfig) and inputs.
last_hidden_state (torch.FloatTensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.
num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict
corresponds to sequence_length.
past_buckets_states (List[Tuple(torch.LongTensor, torch.FloatTensor)], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of Tuple(torch.LongTensor, torch.FloatTensor of length config.n_layers, with the firs


ReformerModel

t element
being the previous buckets of shape (batch_size, num_heads, num_hashes, sequence_length)) and the
second being the previous hidden_states of shape (batch_size, sequence_length, hidden_size)).
Contains precomputed buckets and hidden-states that can be used (see past_buckets_states input) to speed
up sequential decoding.
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of
shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of sh


ReformerModel

ape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The ReformerModel forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:   Copied >>> from transformers import AutoTokenizer, ReformerModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerModel.from_pretrained("google/reformer-crime-and-punishment")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden


ReformerModelWithLMHead

class transformers.ReformerModelWithLMHead  < source > ( config  )   Parameters   config (ReformerConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.    Reformer Model with a language modeling head on top.
Reformer was proposed in Reformer: The Efficient Transformer by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related


ReformerModelWithLMHead

 to general usage
and behavior.  forward  < source > ( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None past_buckets_states: typing.Optional[typing.List[typing.Tuple[torch.Tensor]]] = None use_cache: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None  ) → transformers.modeling_outputs.CausalLMOutput or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. During training th


ReformerModelWithLMHead

e input_ids sequence_length has to be
a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices
are automatically padded to be a multiple of the chunk length.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].
What are position IDs?   head_mask (torch.F


ReformerModelWithLMHead

loatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert input_ids indices into associated vectors than the
model’s internal embedding lookup matrix.   num_hashes (int, optional) —
The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites
the default defined in config.num_hashes.
For more information, see num_hashes in ReformerConfig.   past_buckets_states (List[Tuple(torch.LongTensor, torch.FloatTen


ReformerModelWithLMHead

sor)], optional) —
List of Tuple(torch.LongTensor, torch.FloatTensor of length config.n_layers, with the first element
being the previous buckets of shape (batch_size, num_heads, num_hashes, sequence_length)) and the
second being the previous hidden_states of shape (batch_size, sequence_length, hidden_size)).
Contains precomputed hidden-states and buckets (only relevant for LSH Self-Attention). Can be used to speed
up sequential decoding.   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under ret


ReformerModelWithLMHead

urned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   labels (torch.LongTensor of shape (batch_size,), optional) —
Labels for computing the sequence classification/regression loss. Indices should be in [-100, 0, ..., config.vocab_size - 1]. All labels set to -100 are ignored (masked), the loss is only computed for
labels in [0, ..., config.vocab_size]   Returns
transformers.modeling_outputs.CausalLMOutput or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (ReformerConfig) and inputs.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss (for next-token prediction).
lo


ReformerModelWithLMHead

gits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weight


ReformerModelWithLMHead

s after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The ReformerModelWithLMHead forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:   Copied >>> import torch
>>> from transformers import AutoTokenizer, ReformerModelWithLMHead
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs


ReformerForMaskedLM

class transformers.ReformerForMaskedLM  < source > ( config  )   Parameters   config (ReformerConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.    Reformer Model with a language modeling head on top.
Reformer was proposed in Reformer: The Efficient Transformer by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.  forward  < source > ( input_ids: typing.Optional[torch.Tensor] = None pos


ReformerForMaskedLM

ition_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.MaskedLMOutput or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. During training the input_ids sequence_length has to be
a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices
are automatically padded to be a multiple of the chunk length.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What


ReformerForMaskedLM

 are input IDs?   attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].
What are position IDs?   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Optionally, instead of passing input_ids you can choose to directly pass an embedded representation


ReformerForMaskedLM

. This
is useful if you want more control over how to convert input_ids indices into associated vectors than the
model’s internal embedding lookup matrix.   num_hashes (int, optional) —
The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites
the default defined in config.num_hashes.
For more information, see num_hashes in ReformerConfig.   past_buckets_states (List[Tuple(torch.LongTensor, torch.FloatTensor)], optional) —
List of Tuple(torch.LongTensor, torch.FloatTensor of length config.n_layers, with the first element
being the previous buckets of shape (batch_size, num_heads, num_hashes, sequence_length)) and the
second being the previous hidden_states of shape (batch_size, sequence_length, hidden_size)).
Contains precomputed hidden-states and buckets (only relevant for LSH Self-Attention). Can be used to speed
up sequential decoding.   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned a


ReformerForMaskedLM

nd can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   labels (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Labels for computing the masked language modeling loss. Indices should be in [-100, 0, ..., config.vocab_size] (see input_ids docstring) Tokens with indices set to -100 are ignored (masked),
the loss is only computed for the tokens with labels   Returns
transformers.modeling_outputs.MaskedLMOutput or tuple(torch.FloatTensor)

A transformers.modeling_outputs.MaskedLMOutput or a tuple of
torch.FloatTensor (if return_dict=False


ReformerForMaskedLM

 is passed or when config.return_dict=False) comprising various
elements depending on the configuration (ReformerConfig) and inputs.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Masked language modeling (MLM) loss.
logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.outp


ReformerForMaskedLM

ut_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The ReformerForMaskedLM forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them. This example uses a false checkpoint since we don’t have any available pretrained model for the masked language
modeling task with the Reformer architecture.  Example:   Copied >>> import torch
>>> from transformers import AutoTokenizer, ReformerForMaskedLM
>>> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-reformer")
>>> model = ReformerForMaskedLM.from_pretrained("hf-inte


ReformerForMaskedLM

rnal-testing/tiny-random-reformer")
>>> # add mask_token
>>> tokenizer.add_special_tokens({"mask_token": "[MASK]"})
>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt")
>>> # resize model's embedding matrix
>>> model.resize_token_embeddings(new_num_tokens=model.config.vocab_size + 1)
>>> with torch.no_grad():
...     logits = model(**inputs).logits
>>> # retrieve index of [MASK]
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
>>> predicted_token = tokenizer.decode(predicted_token_id)    Copied >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
>>> # mask labels of non-[MASK] tokens
>>> labels = torch.where(
...     inputs.input_ids == tokenizer.mask_token_id, labels[:, : inputs["input_ids"].shape[-1]], -100
... )
>>> outputs = model(**inputs, labels=labels)
>>> loss = round(outputs.loss.item(),


ReformerForSequenceClassification

class transformers.ReformerForSequenceClassification  < source > ( config  )   Parameters   config (ReformerConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.    Reformer Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks. Reformer was proposed in Reformer: The Efficient Transformer by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) This model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTor


ReformerForSequenceClassification

ch documentation for all matter related to general usage
and behavior.  forward  < source > ( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
Indices of input sequence tokens in the vocabulary. During training the input_ids sequence_length has to be
a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indic


ReformerForSequenceClassification

es
are automatically padded to be a multiple of the chunk length.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].
What are position IDs?   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 i


ReformerForSequenceClassification

ndicates the head is masked.
   inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert input_ids indices into associated vectors than the
model’s internal embedding lookup matrix.   num_hashes (int, optional) —
The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites
the default defined in config.num_hashes.
For more information, see num_hashes in ReformerConfig.   past_buckets_states (List[Tuple(torch.LongTensor, torch.FloatTensor)], optional) —
List of Tuple(torch.LongTensor, torch.FloatTensor of length config.n_layers, with the first element
being the previous buckets of shape (batch_size, num_heads, num_hashes, sequence_length)) and the
second being the previous hidden_states of shape (batc


ReformerForSequenceClassification

h_size, sequence_length, hidden_size)).
Contains precomputed hidden-states and buckets (only relevant for LSH Self-Attention). Can be used to speed
up sequential decoding.   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   labels (torch.LongTensor of shape (batch_size,), optional) —
Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels ==


ReformerForSequenceClassification

1 a regression loss is computed (Mean-Square loss), If
config.num_labels > 1 a classification loss is computed (Cross-Entropy).   Returns
transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)

A transformers.modeling_outputs.SequenceClassifierOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (ReformerConfig) and inputs.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Classification (or regression if config.num_labels==1) loss.
logits (torch.FloatTensor of shape (batch_size, config.num_labels)) — Classification (or regression if config.num_labels==1) scores (before SoftMax).
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output


ReformerForSequenceClassification

 of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The ReformerForSequenceClassification forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores


ReformerForSequenceClassification

 them.  Example of single-label classification:   Copied >>> import torch
>>> from transformers import AutoTokenizer, ReformerForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerForSequenceClassification.from_pretrained("google/reformer-crime-and-punishment")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
...     logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> label = model.config.id2label[predicted_class_id]    Copied >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = ReformerForSequenceClassification.from_pretrained(
...     "google/reformer-crime-and-punishment", num_labels=num_labels
... )
>>> labels = torch.tensor(1)
>>> loss = model(**inputs, labels=labels).lo


ReformerForQuestionAnswering

class transformers.ReformerForQuestionAnswering  < source > ( config  )   Parameters   config (ReformerConfig) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.    Reformer Model with a span classification head on top for extractive question-answering tasks like SQuAD / TriviaQA
( a linear layer on top of hidden-states output to compute span start logits and span end logits. Reformer was proposed in Reformer: The Efficient Transformer by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya. This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.) Th


ReformerForQuestionAnswering

is model is also a PyTorch torch.nn.Module subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.  forward  < source > ( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(torch.FloatTensor)  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence


ReformerForQuestionAnswering

_length)) —
Indices of input sequence tokens in the vocabulary. During training the input_ids sequence_length has to be
a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices
are automatically padded to be a multiple of the chunk length.
Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and
PreTrainedTokenizer.call() for details.
What are input IDs?   attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) —
Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
1 for tokens that are not masked,
0 for tokens that are masked.
What are attention masks?   position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_posi


ReformerForQuestionAnswering

tion_embeddings - 1].
What are position IDs?   head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) —
Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:
1 indicates the head is not masked,
0 indicates the head is masked.
   inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) —
Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert input_ids indices into associated vectors than the
model’s internal embedding lookup matrix.   num_hashes (int, optional) —
The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites
the default defined in config.num_hashes.
For more information, see num_hashes in ReformerConfig.   past_buckets_sta


ReformerForQuestionAnswering

tes (List[Tuple(torch.LongTensor, torch.FloatTensor)], optional) —
List of Tuple(torch.LongTensor, torch.FloatTensor of length config.n_layers, with the first element
being the previous buckets of shape (batch_size, num_heads, num_hashes, sequence_length)) and the
second being the previous hidden_states of shape (batch_size, sequence_length, hidden_size)).
Contains precomputed hidden-states and buckets (only relevant for LSH Self-Attention). Can be used to speed
up sequential decoding.   use_cache (bool, optional) —
If set to True, past_key_values key value states are returned and can be used to speed up decoding (see
past_key_values).   output_attentions (bool, optional) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more detail.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all laye


ReformerForQuestionAnswering

rs. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   start_positions (torch.LongTensor of shape (batch_size,), optional) —
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence
are not taken into account for computing the loss.   end_positions (torch.LongTensor of shape (batch_size,), optional) —
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (sequence_length). Position outside of the sequence
are not taken into account for computing the loss.   Returns
transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(torc


ReformerForQuestionAnswering

h.FloatTensor)

A transformers.modeling_outputs.QuestionAnsweringModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (ReformerConfig) and inputs.
loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
start_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — Span-start scores (before SoftMax).
end_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — Span-end scores (before SoftMax).
hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings, if the model has an embedding layer, +
o


ReformerForQuestionAnswering

ne for the output of each layer) of shape (batch_size, sequence_length, hidden_size).
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
  The ReformerForQuestionAnswering forward method, overrides the __call__ special method. Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.  Example:


ReformerForQuestionAnswering

  Copied >>> from transformers import AutoTokenizer, ReformerForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerForQuestionAnswering.from_pretrained("google/reformer-crime-and-punishment")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])
>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.


Overview

The MobileNet model was proposed in MobileNetV2: Inverted Residuals and Linear Bottlenecks by Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen.
The abstract from the paper is the following:
In this paper we describe a new mobile architecture, MobileNetV2, that improves the state of the art performance of mobile models on multiple tasks and benchmarks as well as across a spectrum of different model sizes. We also describe efficient ways of applying these mobile models to object detection in a novel framework we call SSDLite. Additionally, we demonstrate how to build mobile semantic segmentation models through a reduced form of DeepLabv3 which we call Mobile DeepLabv3.
The MobileNetV2 architecture is based on an inverted residual structure where the input and output of the residual bl


Overview

ock are thin bottleneck layers opposite to traditional residual models which use expanded representations in the input an MobileNetV2 uses lightweight depthwise convolutions to filter features in the intermediate expansion layer. Additionally, we find that it is important to remove non-linearities in the narrow layers in order to maintain representational power. We demonstrate that this improves performance and provide an intuition that led to this design. Finally, our approach allows decoupling of the input/output domains from the expressiveness of the transformation, which provides a convenient framework for further analysis. We measure our performance on Imagenet classification, COCO object detection, VOC image segmentation. We evaluate the trade-offs between accuracy, and number of operations measured by mu


Overview

ltiply-adds (MAdd), as well as the number of parameters.
Tips:
The checkpoints are named mobilenet_v2_depth_size, for example mobilenet_v2_1.0_224, where 1.0 is the depth multiplier (sometimes also referred to as “alpha” or the width multiplier) and 224 is the resolution of the input images the model was trained on. Even though the checkpoint is trained on images of specific size, the model will work on images of any size. The smallest supported image size is 32x32. One can use MobileNetV2ImageProcessor to prepare images for the model. The available image classification checkpoints are pre-trained on ImageNet-1k (also referred to as ILSVRC 2012, a collection of 1.3 million images and 1,000 classes). However, the model predicts 1001 classes: the 1000 classes from ImageNet plus an extra “background” class (index


Overview

0). The segmentation model uses a DeepLabV3+ head. The available semantic segmentation checkpoints are pre-trained on PASCAL VOC. The original TensorFlow checkpoints use different padding rules than PyTorch, requiring the model to determine the padding amount at inference time, since this depends on the input image size. To use native PyTorch padding behavior, create a MobileNetV2Config with tf_padding = False.
Unsupported features:
The MobileNetV2Model outputs a globally pooled version of the last hidden state. In the original model it is possible to use an average pooling layer with a fixed 7x7 window and stride 1 instead of global pooling. For inputs that are larger than the recommended image size, this gives a pooled output that is larger than 1x1. The Hugging Face implementation does not support this. The


Overview

original TensorFlow checkpoints include quantized models. We do not support these models as they include additional “FakeQuantization” operations to unquantize the weights. It’s common to extract the output from the expansion layers at indices 10 and 13, as well as the output from the final 1x1 convolution layer, for downstream purposes. Using output_hidden_states=True returns the output from all intermediate layers. There is currently no way to limit this to specific layers. The DeepLabV3+ segmentation head does not use the final convolution layer from the backbone, but this layer gets computed anyway. There is currently no way to tell MobileNetV2Model up to which layer it should run.
This model was contributed by matthijs. The original code and weights can be found here for the main model and here for DeepLab


Resources

A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with MobileNetV2.
 Image Classification
MobileNetV2ForImageClassification is supported by this example script and notebook. See also: Image classification task guide
Semantic segmentation
Semantic segmentation task guide
If you’re interested in submitting a resource to be included here, please feel free to open a Pull Request and we’ll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.


MobileNetV2Config

class transformers.MobileNetV2Config  < source > ( num_channels = 3 image_size = 224 depth_multiplier = 1.0 depth_divisible_by = 8 min_depth = 8 expand_ratio = 6.0 output_stride = 32 first_layer_is_expansion = True finegrained_output = True hidden_act = 'relu6' tf_padding = True classifier_dropout_prob = 0.8 initializer_range = 0.02 layer_norm_eps = 0.001 semantic_loss_ignore_index = 255 **kwargs  )   Parameters   num_channels (int, optional, defaults to 3) —
The number of input channels.   image_size (int, optional, defaults to 224) —
The size (resolution) of each image.   depth_multiplier (float, optional, defaults to 1.0) —
Shrinks or expands the number of channels in each layer. Default is 1.0, which starts the network with 32
channels. This is sometimes also called “alpha” or “width multiplier”.   depth_divisible_by (int, optional, defaults to 8) —
The number of channels in each layer will always b


MobileNetV2Config

e a multiple of this number.   min_depth (int, optional, defaults to 8) —
All layers will have at least this many channels.   expand_ratio (float, optional, defaults to 6.0) —
The number of output channels of the first layer in each block is input channels times expansion ratio.   output_stride (int, optional, defaults to 32) —
The ratio between the spatial resolution of the input and output feature maps. By default the model reduces
the input dimensions by a factor of 32. If output_stride is 8 or 16, the model uses dilated convolutions
on the depthwise layers instead of regular convolutions, so that the feature maps never become more than 8x
or 16x smaller than the input image.   first_layer_is_expansion (bool, optional, defaults to True) —
True if the very first convolution layer is also the expansion layer for the first expansion block.   finegrained_output (bool, optional, defaults to True) —
If tru


MobileNetV2Config

e, the number of output channels in the final convolution layer will stay large (1280) even if
depth_multiplier is less than 1.   hidden_act (str or function, optional, defaults to "relu6") —
The non-linear activation function (function or string) in the Transformer encoder and convolution layers.   tf_padding (bool, optional, defaults to True) —
Whether to use TensorFlow padding rules on the convolution layers.   classifier_dropout_prob (float, optional, defaults to 0.8) —
The dropout ratio for attached classifiers.   initializer_range (float, optional, defaults to 0.02) —
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.   layer_norm_eps (float, optional, defaults to 0.001) —
The epsilon used by the layer normalization layers.   semantic_loss_ignore_index (int, optional, defaults to 255) —
The index that is ignored by the loss function of the semantic seg


MobileNetV2Config

mentation model.    This is the configuration class to store the configuration of a MobileNetV2Model. It is used to instantiate a
MobileNetV2 model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the MobileNetV2
google/mobilenet_v2_1.0_224 architecture. Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the
documentation from PretrainedConfig for more information.  Example:   Copied >>> from transformers import MobileNetV2Config, MobileNetV2Model
>>> # Initializing a "mobilenet_v2_1.0_224" style configuration
>>> configuration = MobileNetV2Config()
>>> # Initializing a model from the "mobilenet_v2_1.0_224" style configuration
>>> model = MobileNetV2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.con


class transformers.MobileNetV2FeatureExtractor  < source > ( *args **kwargs  )     preprocess  < source > ( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channe


ls_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs  )   Parameters   images (ImageInput) —
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set do_rescale=False.   do_resize (bool, optional, defaults to self.do_resize) —
Whether to resize the image.   size (Dict[str, int], optional, defaults to self.size) —
Size of the image after resizing. Shortest edge of the image is resized to size[“shortest_edge”], with
the longest edge resized to keep the input aspect ratio.   resample (PILImageResampling filter, optional, defaults to self.resample) —
PILImageResampling filter to use if resizing the image e.g. PILImageResampling.BILINEAR. Only has
an effect if do_resize is set to True.   do_center_crop (bool, optional, defaults to self.do_center_crop) —
Whether to center crop the i


mage.   crop_size (Dict[str, int], optional, defaults to self.crop_size) —
Size of the center crop. Only has an effect if do_center_crop is set to True.   do_rescale (bool, optional, defaults to self.do_rescale) —
Whether to rescale the image values between [0 - 1].   rescale_factor (float, optional, defaults to self.rescale_factor) —
Rescale factor to rescale the image by if do_rescale is set to True.   do_normalize (bool, optional, defaults to self.do_normalize) —
Whether to normalize the image.   image_mean (float or List[float], optional, defaults to self.image_mean) —
Image mean to use if do_normalize is set to True.   image_std (float or List[float], optional, defaults to self.image_std) —
Image standard deviation to use if do_normalize is set to True.   return_tensors (str or TensorType, optional) —
The type of tensors to return. Can be one of:
Unset: Return a list of np.ndarray.
TensorType.TENSORFLOW or 'tf': Return a batch of typ


e tf.Tensor.
TensorType.PYTORCH or 'pt': Return a batch of type torch.Tensor.
TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
TensorType.JAX or 'jax': Return a batch of type jax.numpy.ndarray.
   data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) —
The channel dimension format for the output image. Can be one of:
"channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
"channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
Unset: Use the channel dimension format of the input image.
   input_data_format (ChannelDimension or str, optional) —
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
"channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
"channels_last" or ChannelDimension.LAST: image in (height, wid


th, num_channels) format.
"none" or ChannelDimension.NONE: image in (height, width) format.
    Preprocess an image or batch of images.  post_process_semantic_segmentation  < source > ( outputs target_sizes: typing.List[typing.Tuple] = None  ) → semantic_segmentation  Parameters   outputs (MobileNetV2ForSemanticSegmentation) —
Raw outputs of the model.   target_sizes (List[Tuple] of length batch_size, optional) —
List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
predictions will not be resized.   Returns
semantic_segmentation

List[torch.Tensor] of length batch_size, where each item is a semantic
segmentation map of shape (height, width) corresponding to the target_sizes entry (if target_sizes is
specified). Each entry of each torch.Tensor correspond to a semantic class id.
  Converts the output of MobileNetV2ForSemanticSegmentation into semantic segmentation maps. Only supports
PyTo


class transformers.MobileNetV2ImageProcessor  < source > ( do_resize: bool = True size: typing.Union[typing.Dict[str, int], NoneType] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs  )   Parameters   do_resize (bool, optional, defaults to True) —
Whether to resize the image’s (height, width) dimensions to the specified size. Can be overridden by
do_resize in the preprocess method.   size (Dict[str, int] optional, defaults to {"shortest_edge" -- 256}):
Size of the image after resizing. The shortest edge of the image is resized to size[“shortest_edge”], with
the longest edge resized to keep the input as


pect ratio. Can be overridden by size in the preprocess
method.   resample (PILImageResampling, optional, defaults to PILImageResampling.BILINEAR) —
Resampling filter to use if resizing the image. Can be overridden by the resample parameter in the
preprocess method.   do_center_crop (bool, optional, defaults to True) —
Whether to center crop the image. If the input size is smaller than crop_size along any edge, the image
is padded with 0’s and then center cropped. Can be overridden by the do_center_crop parameter in the
preprocess method.   crop_size (Dict[str, int], optional, defaults to {"height" -- 224, "width": 224}):
Desired output size when applying center-cropping. Only has an effect if do_center_crop is set to True.
Can be overridden by the crop_size parameter in the preprocess method.   do_rescale (bool, optional, defaults to True) —
Whether to rescale the image by the specified scale rescale_factor. Can be overridden b


y the do_rescale
parameter in the preprocess method.   rescale_factor (int or float, optional, defaults to 1/255) —
Scale factor to use if rescaling the image. Can be overridden by the rescale_factor parameter in the
preprocess method.
do_normalize —
Whether to normalize the image. Can be overridden by the do_normalize parameter in the preprocess
method.   image_mean (float or List[float], optional, defaults to IMAGENET_STANDARD_MEAN) —
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
channels in the image. Can be overridden by the image_mean parameter in the preprocess method.   image_std (float or List[float], optional, defaults to IMAGENET_STANDARD_STD) —
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the image_std parameter in the preprocess method.    Constructs a


MobileNetV2 image processor.  preprocess  < source > ( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: typing.Optional[bool] = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[


str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs  )   Parameters   images (ImageInput) —
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
passing in images with pixel values between 0 and 1, set do_rescale=False.   do_resize (bool, optional, defaults to self.do_resize) —
Whether to resize the image.   size (Dict[str, int], optional, defaults to self.size) —
Size of the image after resizing. Shortest edge of the image is resized to size[“shortest_edge”], with
the longest edge resized to keep the input aspect ratio.   resample (PILImageResampling filter, optional, defaults to self.resample) —
PILImageResampling filter to use if resizing the image e.g. PILImageResampling.BILINEAR. Only has
an effect if do_resize is set to True.   do_center_crop (bool, optional, defaults to self.do_center_crop) —
Whether to center crop the image.   crop_size (Dict[str, int]


, optional, defaults to self.crop_size) —
Size of the center crop. Only has an effect if do_center_crop is set to True.   do_rescale (bool, optional, defaults to self.do_rescale) —
Whether to rescale the image values between [0 - 1].   rescale_factor (float, optional, defaults to self.rescale_factor) —
Rescale factor to rescale the image by if do_rescale is set to True.   do_normalize (bool, optional, defaults to self.do_normalize) —
Whether to normalize the image.   image_mean (float or List[float], optional, defaults to self.image_mean) —
Image mean to use if do_normalize is set to True.   image_std (float or List[float], optional, defaults to self.image_std) —
Image standard deviation to use if do_normalize is set to True.   return_tensors (str or TensorType, optional) —
The type of tensors to return. Can be one of:
Unset: Return a list of np.ndarray.
TensorType.TENSORFLOW or 'tf': Return a batch of type tf.Tensor.
TensorType


.PYTORCH or 'pt': Return a batch of type torch.Tensor.
TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
TensorType.JAX or 'jax': Return a batch of type jax.numpy.ndarray.
   data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) —
The channel dimension format for the output image. Can be one of:
"channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
"channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
Unset: Use the channel dimension format of the input image.
   input_data_format (ChannelDimension or str, optional) —
The channel dimension format for the input image. If unset, the channel dimension format is inferred
from the input image. Can be one of:
"channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
"channels_last" or ChannelDimension.LAST: image in (height, width, num_chann


els) format.
"none" or ChannelDimension.NONE: image in (height, width) format.
    Preprocess an image or batch of images.  post_process_semantic_segmentation  < source > ( outputs target_sizes: typing.List[typing.Tuple] = None  ) → semantic_segmentation  Parameters   outputs (MobileNetV2ForSemanticSegmentation) —
Raw outputs of the model.   target_sizes (List[Tuple] of length batch_size, optional) —
List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
predictions will not be resized.   Returns
semantic_segmentation

List[torch.Tensor] of length batch_size, where each item is a semantic
segmentation map of shape (height, width) corresponding to the target_sizes entry (if target_sizes is
specified). Each entry of each torch.Tensor correspond to a semantic class id.
  Converts the output of MobileNetV2ForSemanticSegmentation into semantic segmentation maps. Only supports
PyTorch


MobileNetV2Model

class transformers.MobileNetV2Model  < source > ( config: MobileNetV2Config add_pooling_layer: bool = True  )   Parameters   config (MobileNetV2Config) — Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the from_pretrained() method to load the model weights.    The bare MobileNetV2 model outputting raw hidden-states without any specific head on top.
This model is a PyTorch torch.nn.Module subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.  forward  < source > ( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None  ) → transformers.modeling_outputs.Base


MobileNetV2Model

ModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)  Parameters   pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) —
Pixel values. Pixel values can be obtained using AutoImageProcessor. See
MobileNetV2ImageProcessor.call() for details.   output_hidden_states (bool, optional) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more detail.   return_dict (bool, optional) —
Whether or not to return a ModelOutput instead of a plain tuple.   Returns
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the c