---
local: reformer
sections:
- local: overview
  title: Overview
- local: axial-positional-encodings
  title: Axial Positional Encodings
- local: lsh-self-attention
  title: LSH Self Attention
- local: local-self-attention
  title: Local Self Attention
- local: training
  title: Training
- local: transformers.ReformerConfig
  title: ReformerConfig
- local: transformers.ReformerTokenizer
  title: ReformerTokenizer
- local: transformers.ReformerTokenizerFast
  title: ReformerTokenizerFast
- local: transformers.ReformerModel
  title: ReformerModel
- local: transformers.ReformerModelWithLMHead
  title: ReformerModelWithLMHead
- local: transformers.ReformerForMaskedLM
  title: ReformerForMaskedLM
- local: transformers.ReformerForSequenceClassification
  title: ReformerForSequenceClassification
- local: transformers.ReformerForQuestionAnswering
  title: ReformerForQuestionAnswering
title: Reformer
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2020 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="reformer">Reformer</h1>

**DISCLAIMER:** This model is still a work in progress, if you see something strange, file a [Github Issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=&template=bug-report.md&title).

<h2 id="overview">Overview</h2>

The Reformer model was proposed in the paper [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451.pdf) 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 model was contributed by [patrickvonplaten](https://huggingface.co/patrickvonplaten). The Authors' code can be
found [here](https://github.com/google/trax/tree/master/trax/models/reformer).

**Note**:

- Reformer does **not** work with *torch.nn.DataParallel* due to a bug in PyTorch, see [issue #36035](https://github.com/pytorch/pytorch/issues/36035)

<h2 id="axial-positional-encodings">Axial Positional Encodings</h2>

Axial Positional Encodings were first implemented in Google's [trax library](https://github.com/google/trax/blob/4d99ad4965bab1deba227539758d59f0df0fef48/trax/layers/research/position_encodings.py#L29)
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 \\(d\\) being the `config.hidden_size` for
every position \\(i, \ldots, n_s\\), with \\(n_s\\) being `config.max_embedding_size`. This means that having
a sequence length of \\(n_s = 2^&amp;lcub;19} \approx 0.5M\\) and a `config.hidden_size` of \\(d = 2^&amp;lcub;10} \approx 1000\\)
would result in a position encoding matrix:

$$X_&amp;lcub;i,j}, \text&amp;lcub; with } i \in \left[1,\ldots, d\right] \text&amp;lcub; and } j \in \left[1,\ldots, n_s\right]$$

which alone has over 500M parameters to store. Axial positional encodings factorize \\(X_&amp;lcub;i,j}\\) into two matrices:

$$X^&amp;lcub;1}_&amp;lcub;i,j}, \text&amp;lcub; with } i \in \left[1,\ldots, d^1\right] \text&amp;lcub; and } j \in \left[1,\ldots, n_s^1\right]$$

and

$$X^&amp;lcub;2}_&amp;lcub;i,j}, \text&amp;lcub; with } i \in \left[1,\ldots, d^2\right] \text&amp;lcub; and } j \in \left[1,\ldots, n_s^2\right]$$

with:

$$d = d^1 + d^2 \text&amp;lcub; and } n_s = n_s^1 \times n_s^2 .$$

Therefore the following holds:

$$X_&amp;lcub;i,j} = \begin&amp;lcub;cases}
X^&amp;lcub;1}_&amp;lcub;i, k}, & \text&amp;lcub;if }\ i &amp;lt; d^1 \text&amp;lcub; with } k = j \mod n_s^1 \\
X^&amp;lcub;2}_&amp;lcub;i - d^1, l}, & \text&amp;lcub;if } i \ge d^1 \text&amp;lcub; with } l = \lfloor\frac&amp;lcub;j}&amp;lcub;n_s^1}\rfloor
\end&amp;lcub;cases}$$

Intuitively, this means that a position embedding vector \\(x_j \in \mathbb&amp;lcub;R}^&amp;lcub;d}\\) is now the composition of two
factorized embedding vectors: \\(x^1_&amp;lcub;k, l} + x^2_&amp;lcub;l, k}\\), where as the `config.max_embedding_size` dimension
\\(j\\) is factorized into \\(k \text&amp;lcub; and } l\\). This design ensures that each position embedding vector
\\(x_j\\) is unique.

Using the above example again, axial position encoding with \\(d^1 = 2^5, d^2 = 2^5, n_s^1 = 2^9, n_s^2 = 2^&amp;lcub;10}\\)
can drastically reduced the number of parameters to \\(2^&amp;lcub;14} + 2^&amp;lcub;15} \approx 49000\\) parameters.

In practice, the parameter `config.axial_pos_embds_dim` is set to a tuple \\((d^1, d^2)\\) which sum has to be
equal to `config.hidden_size` and `config.axial_pos_shape` is set to a tuple \\((n_s^1, n_s^2)\\) 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_ids`.


<h2 id="lsh-self-attention">LSH Self Attention</h2>

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](https://arxiv.org/abs/1509.02897) 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 then 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](https://arxiv.org/abs/2001.04451) or this great [blog post](https://www.pragmatic.ml/reformer-deep-dive/).

Note that `config.num_buckets` can also be factorized into a list \\((n_&amp;lcub;\text&amp;lcub;buckets}}^1,
n_&amp;lcub;\text&amp;lcub;buckets}}^2)\\). This way instead of assigning the query key embedding vectors to one of \\((1,\ldots,
n_&amp;lcub;\text&amp;lcub;buckets}})\\) they are assigned to one of \\((1-1,\ldots, n_&amp;lcub;\text&amp;lcub;buckets}}^1-1, \ldots,
1-n_&amp;lcub;\text&amp;lcub;buckets}}^2, \ldots, n_&amp;lcub;\text&amp;lcub;buckets}}^1-n_&amp;lcub;\text&amp;lcub;buckets}}^2)\\). 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
\\(\mathcal&amp;lcub;O}(n_s \times n_s)\\) to \\(\mathcal&amp;lcub;O}(n_s \times \log(n_s))\\), which usually represents the memory
and time bottleneck in a transformer model, with \\(n_s\\) being the sequence length.


<h2 id="local-self-attention">Local Self Attention</h2>

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
\\(\mathcal&amp;lcub;O}(n_s \times n_s)\\) to \\(\mathcal&amp;lcub;O}(n_s \times \log(n_s))\\), which usually represents the memory
and time bottleneck in a transformer model, with \\(n_s\\) being the sequence length.


<h2 id="training">Training</h2>

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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerModelWithLMHead) should be used as follows:

```python
input_ids = tokenizer.encode("This is a sentence from the training data", return_tensors="pt")
loss = model(input_ids, labels=input_ids)[0]
```

<h2 id="transformers.ReformerConfig">ReformerConfig</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerConfig</name><anchor>transformers.ReformerConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/configuration_reformer.py#L30</source><parameters>[{"name": "attention_head_size", "val": " = 64"}, {"name": "attn_layers", "val": " = ['local', 'lsh', 'local', 'lsh', 'local', 'lsh']"}, {"name": "axial_norm_std", "val": " = 1.0"}, {"name": "axial_pos_embds", "val": " = True"}, {"name": "axial_pos_shape", "val": " = [64, 64]"}, {"name": "axial_pos_embds_dim", "val": " = [64, 192]"}, {"name": "chunk_size_lm_head", "val": " = 0"}, {"name": "eos_token_id", "val": " = 2"}, {"name": "feed_forward_size", "val": " = 512"}, {"name": "hash_seed", "val": " = None"}, {"name": "hidden_act", "val": " = 'relu'"}, {"name": "hidden_dropout_prob", "val": " = 0.05"}, {"name": "hidden_size", "val": " = 256"}, {"name": "initializer_range", "val": " = 0.02"}, {"name": "is_decoder", "val": " = False"}, {"name": "layer_norm_eps", "val": " = 1e-12"}, {"name": "local_num_chunks_before", "val": " = 1"}, {"name": "local_num_chunks_after", "val": " = 0"}, {"name": "local_attention_probs_dropout_prob", "val": " = 0.05"}, {"name": "local_attn_chunk_length", "val": " = 64"}, {"name": "lsh_attn_chunk_length", "val": " = 64"}, {"name": "lsh_attention_probs_dropout_prob", "val": " = 0.0"}, {"name": "lsh_num_chunks_before", "val": " = 1"}, {"name": "lsh_num_chunks_after", "val": " = 0"}, {"name": "max_position_embeddings", "val": " = 4096"}, {"name": "num_attention_heads", "val": " = 12"}, {"name": "num_buckets", "val": " = None"}, {"name": "num_hashes", "val": " = 1"}, {"name": "pad_token_id", "val": " = 0"}, {"name": "vocab_size", "val": " = 320"}, {"name": "tie_word_embeddings", "val": " = False"}, {"name": "use_cache", "val": " = True"}, {"name": "classifier_dropout", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **attention_head_size** (`int`, *optional*, 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](reformer#lsh-self-attention). For
  more information on LocalSelfAttention layer, see [Local Self Attention](reformer#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](reformer#axial-positional-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 position 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](reformer#axial-positional-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](reformer#axial-positional-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 &amp;lt;
  sequence_length embeddings at a time.

  For more information on feed forward chunking, see [How does Feed Forward Chunking
  work?](../glossary#feed-forward-chunking).
- **eos_token_id** (`int`, *optional*, defaults to 2) --
  The token id for the end-of-sentence token.
- **feed_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.
- **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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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.
- **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`, *optional*, 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 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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 by all models).
- **classifier_dropout** (`float`, *optional*) --
  The dropout ratio for the classification head.</paramsdesc><paramgroups>0</paramgroups></docstring>

This is the configuration class to store the configuration of a [ReformerModel](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerModel). It is used to instantiate a
Reformer model according to the specified arguments, defining the model architecture.

Configuration objects inherit from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) and can be used to control the model outputs. Read the
documentation from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) for more information.



Examples:

```python
>>> from transformers import ReformerModel, ReformerConfig

>>> # Initializing a Reformer configuration
>>> configuration = ReformerConfig()

>>> # Initializing a Reformer model
>>> model = ReformerModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```


</div>

<h2 id="transformers.ReformerTokenizer">ReformerTokenizer</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerTokenizer</name><anchor>transformers.ReformerTokenizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/tokenization_reformer.py#L46</source><parameters>[{"name": "vocab_file", "val": ""}, {"name": "eos_token", "val": " = '</s>'"}, {"name": "unk_token", "val": " = '<unk>'"}, {"name": "additional_special_tokens", "val": " = []"}, {"name": "sp_model_kwargs", "val": ": typing.Union[typing.Dict[str, typing.Any], NoneType] = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  contains the vocabulary necessary to instantiate a tokenizer.
- **eos_token** (`str`, *optional*, defaults to `"&amp;lt;/s>"`) --
  The end of sequence token.

  <Tip>

  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`.

  </Tip>

- **unk_token** (`str`, *optional*, defaults to `"&amp;lt;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.
- **pad_token** (`str`, *optional*, defaults to `"&amp;lt;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.
- **sp_model_kwargs** (`dict`, *optional*) --
  Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  SentencePiece](https://github.com/google/sentencepiece/tree/master/python) 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 = &amp;lcub;0,1}`: No sampling is performed.
    - `nbest_size > 1`: samples from the nbest_size results.
    - `nbest_size &amp;lt; 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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct a Reformer tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece) .

This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.





<div class="docstring"></div></div>

<h2 id="transformers.ReformerTokenizerFast">ReformerTokenizerFast</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerTokenizerFast</name><anchor>transformers.ReformerTokenizerFast</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/tokenization_reformer_fast.py#L54</source><parameters>[{"name": "vocab_file", "val": " = None"}, {"name": "tokenizer_file", "val": " = None"}, {"name": "eos_token", "val": " = '</s>'"}, {"name": "unk_token", "val": " = '<unk>'"}, {"name": "additional_special_tokens", "val": " = []"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_file** (`str`) --
  [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  contains the vocabulary necessary to instantiate a tokenizer.
- **eos_token** (`str`, *optional*, defaults to `"&amp;lt;/s>"`) --
  The end of sequence token.

  <Tip>

  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`.

  </Tip>

- **unk_token** (`str`, *optional*, defaults to `"&amp;lt;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.
- **pad_token** (`str`, *optional*, defaults to `"&amp;lt;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.</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct a "fast" Reformer tokenizer (backed by HuggingFace's *tokenizers* library). Based on
[Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).

This tokenizer inherits from [PreTrainedTokenizerFast](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast) which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.




</div>

<h2 id="transformers.ReformerModel">ReformerModel</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerModel</name><anchor>transformers.ReformerModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L1961</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([ReformerConfig](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
The bare Reformer Model transformer outputting raw hidden-stateswithout any specific head on top.
Reformer was proposed in [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.ReformerModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L1989</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "num_hashes", "val": " = None"}, {"name": "past_buckets_states", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **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 [ReformerTokenizer](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#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?](../glossary#attention-mask)
- **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?](../glossary#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.reformer.modeling_reformer.ReformerModelOutput`or `tuple(torch.FloatTensor)`</rettype><retdesc>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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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 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 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.</retdesc></docstring>
The [ReformerModel](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerModel) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import ReformerTokenizer, ReformerModel
>>> import torch

>>> tokenizer = ReformerTokenizer.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_state
```


</div></div>

<h2 id="transformers.ReformerModelWithLMHead">ReformerModelWithLMHead</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerModelWithLMHead</name><anchor>transformers.ReformerModelWithLMHead</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2173</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([ReformerConfig](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
Reformer Model with a `language modeling` head on top.
Reformer was proposed in [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.ReformerModelWithLMHead.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2196</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "num_hashes", "val": " = None"}, {"name": "past_buckets_states", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "labels", "val": " = None"}]</parameters><paramsdesc>- **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 [ReformerTokenizer](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#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?](../glossary#attention-mask)
- **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?](../glossary#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.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]`</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.CausalLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.CausalLMOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.CausalLMOutput](/docs/transformers/pr_15592/en/main_classes/output#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss (for next-token prediction).
- **logits** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) -- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- **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 + 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 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.</retdesc></docstring>
The [ReformerModelWithLMHead](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerModelWithLMHead) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> import torch
>>> from transformers import ReformerTokenizer, ReformerModelWithLMHead

>>> tokenizer = ReformerTokenizer.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.logits
```


</div></div>

<h2 id="transformers.ReformerForMaskedLM">ReformerForMaskedLM</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerForMaskedLM</name><anchor>transformers.ReformerForMaskedLM</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2294</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([ReformerConfig](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>
Reformer Model with a `language modeling` head on top.
Reformer was proposed in [Reformer: The Efficient Transformer](https://arxiv.org/abs/2001.04451) by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.ReformerForMaskedLM.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2312</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "num_hashes", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **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 [ReformerTokenizer](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#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?](../glossary#attention-mask)
- **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?](../glossary#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.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</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.MaskedLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.MaskedLMOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.MaskedLMOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.MaskedLMOutput) 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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 + 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 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.</retdesc></docstring>
The [ReformerForMaskedLM](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerForMaskedLM) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import ReformerTokenizer, ReformerForMaskedLM
>>> import torch

>>> tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerForMaskedLM.from_pretrained("google/reformer-crime-and-punishment")

>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt")
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]

>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
```


</div></div>

<h2 id="transformers.ReformerForSequenceClassification">ReformerForSequenceClassification</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerForSequenceClassification</name><anchor>transformers.ReformerForSequenceClassification</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2380</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([ReformerConfig](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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](https://arxiv.org/abs/2001.04451) by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.ReformerForSequenceClassification.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2394</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "num_hashes", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **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 [ReformerTokenizer](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#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?](../glossary#attention-mask)
- **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?](../glossary#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.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 == 1` a regression loss is computed (Mean-Square loss), If
  `config.num_labels > 1` a classification loss is computed (Cross-Entropy).</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.SequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.SequenceClassifierOutput](/docs/transformers/pr_15592/en/main_classes/output#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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(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.</retdesc></docstring>
The [ReformerForSequenceClassification](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerForSequenceClassification) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example of single-label classification:

```python
>>> from transformers import ReformerTokenizer, ReformerForSequenceClassification
>>> import torch

>>> tokenizer = ReformerTokenizer.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")
>>> labels = torch.tensor([1]).unsqueeze(0)  # Batch size 1
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
```

Example of multi-label classification:

```python
>>> from transformers import ReformerTokenizer, ReformerForSequenceClassification
>>> import torch

>>> tokenizer = ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerForSequenceClassification.from_pretrained("google/reformer-crime-and-punishment", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> labels = torch.tensor([[1, 1]], dtype=torch.float)  # need dtype=float for BCEWithLogitsLoss
>>> outputs = model(**inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits
```


</div></div>

<h2 id="transformers.ReformerForQuestionAnswering">ReformerForQuestionAnswering</h2>

<div class="docstring">

<docstring><name>class transformers.ReformerForQuestionAnswering</name><anchor>transformers.ReformerForQuestionAnswering</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2501</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([ReformerConfig](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.</paramsdesc><paramgroups>0</paramgroups></docstring>

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](https://arxiv.org/abs/2001.04451) by Nikita Kitaev,
Łukasz Kaiser, Anselm Levskaya.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.ReformerForQuestionAnswering.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/reformer/modeling_reformer.py#L2513</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "position_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "head_mask", "val": " = None"}, {"name": "inputs_embeds", "val": " = None"}, {"name": "num_hashes", "val": " = None"}, {"name": "start_positions", "val": " = None"}, {"name": "end_positions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "return_dict", "val": " = None"}]</parameters><paramsdesc>- **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 [ReformerTokenizer](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and
  [PreTrainedTokenizer.__call__()](/docs/transformers/pr_15592/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.

  [What are input IDs?](../glossary#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?](../glossary#attention-mask)
- **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?](../glossary#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 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](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.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.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.modeling_outputs.QuestionAnsweringModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.modeling_outputs.QuestionAnsweringModelOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_outputs.QuestionAnsweringModelOutput](/docs/transformers/pr_15592/en/main_classes/output#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](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.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 + 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 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.</retdesc></docstring>
The [ReformerForQuestionAnswering](/docs/transformers/pr_15592/en/model_doc/reformer#transformers.ReformerForQuestionAnswering) forward method, overrides the `__call__` special method.

<Tip>

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.

</Tip>







Example:

```python
>>> from transformers import ReformerTokenizer, ReformerForQuestionAnswering
>>> import torch

>>> tokenizer = ReformerTokenizer.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")
>>> start_positions = torch.tensor([1])
>>> end_positions = torch.tensor([3])

>>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions)
>>> loss = outputs.loss
>>> start_scores = outputs.start_logits
>>> end_scores = outputs.end_logits
```


</div></div>
