---
local: custom-layers-and-utilities
sections:
- local: transformers.Conv1D
  title: Pytorch custom modules
- local: transformers.apply_chunking_to_forward
  title: PyTorch Helper Functions
- local: transformers.modeling_tf_utils.TFConv1D
  title: TensorFlow custom layers
- local: transformers.modeling_tf_utils.TFCausalLanguageModelingLoss
  title: TensorFlow loss functions
- local: transformers.modeling_tf_utils.get_initializer
  title: TensorFlow Helper Functions
title: Custom Layers and Utilities
---
<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="custom-layers-and-utilities">Custom Layers and Utilities</h1>

This page lists all the custom layers used by the library, as well as the utility functions it provides for modeling.

Most of those are only useful if you are studying the code of the models in the library.


<h2 id="transformers.Conv1D">Pytorch custom modules</h2>

<div class="docstring">

<docstring><name>class transformers.Conv1D</name><anchor>transformers.Conv1D</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1846</source><parameters>[{"name": "nf", "val": ""}, {"name": "nx", "val": ""}]</parameters><paramsdesc>- **nf** (`int`) -- The number of output features.
- **nx** (`int`) -- The number of input features.</paramsdesc><paramgroups>0</paramgroups></docstring>

1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).

Basically works like a linear layer but the weights are transposed.




</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_utils.PoolerStartLogits</name><anchor>transformers.modeling_utils.PoolerStartLogits</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1872</source><parameters>[{"name": "config", "val": ": PretrainedConfig"}]</parameters><paramsdesc>- **config** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig)) --
  The config used by the model, will be used to grab the `hidden_size` of the model.</paramsdesc><paramgroups>0</paramgroups></docstring>

Compute SQuAD start logits from sequence hidden states.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.modeling_utils.PoolerStartLogits.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1885</source><parameters>[{"name": "hidden_states", "val": ": FloatTensor"}, {"name": "p_mask", "val": ": typing.Optional[torch.FloatTensor] = None"}]</parameters><paramsdesc>- **hidden_states** (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`) --
  The final hidden states of the model.
- **p_mask** (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*) --
  Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  should be masked.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.FloatTensor`</rettype><retdesc>The start logits for SQuAD.</retdesc></docstring>








</div></div>

<div class="docstring">

<docstring><name>class transformers.modeling\_utils.PoolerEndLogits</name><anchor>transformers.modeling_utils.PoolerEndLogits</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1910</source><parameters>[{"name": "config", "val": ": PretrainedConfig"}]</parameters><paramsdesc>- **config** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig)) --
  The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
  to use.</paramsdesc><paramgroups>0</paramgroups></docstring>

Compute SQuAD end logits from sequence hidden states.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.modeling_utils.PoolerEndLogits.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1927</source><parameters>[{"name": "hidden_states", "val": ": FloatTensor"}, {"name": "start_states", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "start_positions", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "p_mask", "val": ": typing.Optional[torch.FloatTensor] = None"}]</parameters><paramsdesc>- **hidden_states** (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`) --
  The final hidden states of the model.
- **start_states** (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*) --
  The hidden states of the first tokens for the labeled span.
- **start_positions** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  The position of the first token for the labeled span.
- **p_mask** (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*) --
  Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  should be masked.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.FloatTensor`</rettype><retdesc>The end logits for SQuAD.</retdesc></docstring>



<Tip>

One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
`start_states`.

</Tip>






</div></div>

<div class="docstring">

<docstring><name>class transformers.modeling\_utils.PoolerAnswerClass</name><anchor>transformers.modeling_utils.PoolerAnswerClass</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1979</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig)) --
  The config used by the model, will be used to grab the `hidden_size` of the model.</paramsdesc><paramgroups>0</paramgroups></docstring>

Compute SQuAD 2.0 answer class from classification and start tokens hidden states.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.modeling_utils.PoolerAnswerClass.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L1994</source><parameters>[{"name": "hidden_states", "val": ": FloatTensor"}, {"name": "start_states", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "start_positions", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "cls_index", "val": ": typing.Optional[torch.LongTensor] = None"}]</parameters><paramsdesc>- **hidden_states** (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`) --
  The final hidden states of the model.
- **start_states** (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*) --
  The hidden states of the first tokens for the labeled span.
- **start_positions** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  The position of the first token for the labeled span.
- **cls_index** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Position of the CLS token for each sentence in the batch. If `None`, takes the last token.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.FloatTensor`</rettype><retdesc>The SQuAD 2.0 answer class.</retdesc></docstring>



<Tip>

One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
`start_states`.

</Tip>






</div></div>

<div class="docstring">

<docstring><name>class transformers.modeling\_utils.SquadHeadOutput</name><anchor>transformers.modeling_utils.SquadHeadOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2045</source><parameters>[{"name": "loss", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "start_top_log_probs", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "start_top_index", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "end_top_log_probs", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "end_top_index", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "cls_logits", "val": ": typing.Optional[torch.FloatTensor] = None"}]</parameters><paramsdesc>- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided) --
  Classification loss as the sum of start token, end token (and is_impossible if provided) classification
  losses.
- **start_top_log_probs** (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) --
  Log probabilities for the top config.start_n_top start token possibilities (beam-search).
- **start_top_index** (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) --
  Indices for the top config.start_n_top start token possibilities (beam-search).
- **end_top_log_probs** (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) --
  Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
  (beam-search).
- **end_top_index** (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) --
  Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
- **cls_logits** (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided) --
  Log probabilities for the `is_impossible` label of the answers.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for outputs of question answering models using a [SQuADHead](/docs/transformers/pr_15592/en/internal/modeling_utils#transformers.modeling_utils.SQuADHead).




</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_utils.SQuADHead</name><anchor>transformers.modeling_utils.SQuADHead</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2075</source><parameters>[{"name": "config", "val": ""}]</parameters><paramsdesc>- **config** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig)) --
  The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
  to use.</paramsdesc><paramgroups>0</paramgroups></docstring>

A SQuAD head inspired by XLNet.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.modeling_utils.SQuADHead.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2094</source><parameters>[{"name": "hidden_states", "val": ": FloatTensor"}, {"name": "start_positions", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "end_positions", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "cls_index", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "is_impossible", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "p_mask", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "return_dict", "val": ": bool = False"}]</parameters><paramsdesc>- **hidden_states** (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`) --
  Final hidden states of the model on the sequence tokens.
- **start_positions** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Positions of the first token for the labeled span.
- **end_positions** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Positions of the last token for the labeled span.
- **cls_index** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
- **is_impossible** (`torch.LongTensor` of shape `(batch_size,)`, *optional*) --
  Whether the question has a possible answer in the paragraph or not.
- **p_mask** (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*) --
  Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  should be masked.
- **return_dict** (`bool`, *optional*, defaults to `False`) --
  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.modeling_utils.SquadHeadOutput](/docs/transformers/pr_15592/en/internal/modeling_utils#transformers.modeling_utils.SquadHeadOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.modeling_utils.SquadHeadOutput](/docs/transformers/pr_15592/en/internal/modeling_utils#transformers.modeling_utils.SquadHeadOutput) 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 (`&amp;lt;class 'transformers.configuration_utils.PretrainedConfig'>`) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided) -- Classification loss as the sum of start token, end token (and is_impossible if provided) classification
  losses.
- **start_top_log_probs** (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) -- Log probabilities for the top config.start_n_top start token possibilities (beam-search).
- **start_top_index** (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) -- Indices for the top config.start_n_top start token possibilities (beam-search).
- **end_top_log_probs** (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) -- Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
  (beam-search).
- **end_top_index** (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided) -- Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
- **cls_logits** (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided) -- Log probabilities for the `is_impossible` label of the answers.</retdesc></docstring>








</div></div>

<div class="docstring">

<docstring><name>class transformers.modeling\_utils.SequenceSummary</name><anchor>transformers.modeling_utils.SequenceSummary</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2192</source><parameters>[{"name": "config", "val": ": PretrainedConfig"}]</parameters><paramsdesc>- **config** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig)) --
  The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
  config class of your model for the default values it uses):

  - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:

    - `"last"` -- Take the last token hidden state (like XLNet)
    - `"first"` -- Take the first token hidden state (like Bert)
    - `"mean"` -- Take the mean of all tokens hidden states
    - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
    - `"attn"` -- Not implemented now, use multi-head attention

  - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
  - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
    (otherwise to `config.hidden_size`).
  - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
    another string or `None` will add no activation.
  - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
  - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.</paramsdesc><paramgroups>0</paramgroups></docstring>

Compute a single vector summary of a sequence hidden states.





<div class="docstring">
<docstring><name>forward</name><anchor>transformers.modeling_utils.SequenceSummary.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2247</source><parameters>[{"name": "hidden_states", "val": ": FloatTensor"}, {"name": "cls_index", "val": ": typing.Optional[torch.LongTensor] = None"}]</parameters><paramsdesc>- **hidden_states** (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`) --
  The hidden states of the last layer.
- **cls_index** (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*) --
  Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.FloatTensor`</rettype><retdesc>The summary of the sequence hidden states.</retdesc></docstring>

Compute a single vector summary of a sequence hidden states.








</div></div>

<h2 id="transformers.apply_chunking_to_forward">PyTorch Helper Functions</h2>

<div class="docstring">

<docstring><name>transformers.apply\_chunking\_to\_forward</name><anchor>transformers.apply_chunking_to_forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2396</source><parameters>[{"name": "forward_fn", "val": ": typing.Callable[..., torch.Tensor]"}, {"name": "chunk_size", "val": ": int"}, {"name": "chunk_dim", "val": ": int"}, {"name": "*input_tensors", "val": ""}]</parameters><paramsdesc>- **forward_fn** (`Callable[..., torch.Tensor]`) --
  The forward function of the model.
- **chunk_size** (`int`) --
  The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`.
- **chunk_dim** (`int`) --
  The dimension over which the `input_tensors` should be chunked.
- **input_tensors** (`Tuple[torch.Tensor]`) --
  The input tensors of `forward_fn` which will be chunked</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.Tensor`</rettype><retdesc>A tensor with the same shape as the `forward_fn` would have given if applied`.</retdesc></docstring>

This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension
`chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory.

If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly
applying `forward_fn` to `input_tensors`.







Examples:

```python
# rename the usual forward() fn to forward_chunk()
def forward_chunk(self, hidden_states):
    hidden_states = self.decoder(hidden_states)
    return hidden_states


# implement a chunked forward function
def forward(self, hidden_states):
    return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)
```

</div>

<div class="docstring">

<docstring><name>transformers.modeling\_utils.find\_pruneable\_heads\_and\_indices</name><anchor>transformers.modeling_utils.find_pruneable_heads_and_indices</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L95</source><parameters>[{"name": "heads", "val": ": typing.List[int]"}, {"name": "n_heads", "val": ": int"}, {"name": "head_size", "val": ": int"}, {"name": "already_pruned_heads", "val": ": typing.Set[int]"}]</parameters><paramsdesc>- **heads** (`List[int]`) -- List of the indices of heads to prune.
- **n_heads** (`int`) -- The number of heads in the model.
- **head_size** (`int`) -- The size of each head.
- **already_pruned_heads** (`Set[int]`) -- A set of already pruned heads.</paramsdesc><paramgroups>0</paramgroups><rettype>`Tuple[Set[int], torch.LongTensor]`</rettype><retdesc>A tuple with the remaining heads and their corresponding indices.</retdesc></docstring>

Finds the heads and their indices taking `already_pruned_heads` into account.








</div>

<div class="docstring">

<docstring><name>transformers.prune\_layer</name><anchor>transformers.prune_layer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2372</source><parameters>[{"name": "layer", "val": ": typing.Union[torch.nn.modules.linear.Linear, transformers.modeling_utils.Conv1D]"}, {"name": "index", "val": ": LongTensor"}, {"name": "dim", "val": ": typing.Optional[int] = None"}]</parameters><paramsdesc>- **layer** (`Union[torch.nn.Linear, Conv1D]`) -- The layer to prune.
- **index** (`torch.LongTensor`) -- The indices to keep in the layer.
- **dim** (`int`, *optional*) -- The dimension on which to keep the indices.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.nn.Linear` or [Conv1D](/docs/transformers/pr_15592/en/internal/modeling_utils#transformers.Conv1D)</rettype><retdesc>The pruned layer as a new layer with `requires_grad=True`.</retdesc></docstring>

Prune a Conv1D or linear layer to keep only entries in index.

Used to remove heads.








</div>

<div class="docstring">

<docstring><name>transformers.modeling\_utils.prune\_conv1d\_layer</name><anchor>transformers.modeling_utils.prune_conv1d_layer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2339</source><parameters>[{"name": "layer", "val": ": Conv1D"}, {"name": "index", "val": ": LongTensor"}, {"name": "dim", "val": ": int = 1"}]</parameters><paramsdesc>- **layer** ([Conv1D](/docs/transformers/pr_15592/en/internal/modeling_utils#transformers.Conv1D)) -- The layer to prune.
- **index** (`torch.LongTensor`) -- The indices to keep in the layer.
- **dim** (`int`, *optional*, defaults to 1) -- The dimension on which to keep the indices.</paramsdesc><paramgroups>0</paramgroups><rettype>[Conv1D](/docs/transformers/pr_15592/en/internal/modeling_utils#transformers.Conv1D)</rettype><retdesc>The pruned layer as a new layer with `requires_grad=True`.</retdesc></docstring>

Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights
are transposed.

Used to remove heads.








</div>

<div class="docstring">

<docstring><name>transformers.modeling\_utils.prune\_linear\_layer</name><anchor>transformers.modeling_utils.prune_linear_layer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_utils.py#L2305</source><parameters>[{"name": "layer", "val": ": Linear"}, {"name": "index", "val": ": LongTensor"}, {"name": "dim", "val": ": int = 0"}]</parameters><paramsdesc>- **layer** (`torch.nn.Linear`) -- The layer to prune.
- **index** (`torch.LongTensor`) -- The indices to keep in the layer.
- **dim** (`int`, *optional*, defaults to 0) -- The dimension on which to keep the indices.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.nn.Linear`</rettype><retdesc>The pruned layer as a new layer with `requires_grad=True`.</retdesc></docstring>

Prune a linear layer to keep only entries in index.

Used to remove heads.








</div>

<h2 id="transformers.modeling_tf_utils.TFConv1D">TensorFlow custom layers</h2>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFConv1D</name><anchor>transformers.modeling_tf_utils.TFConv1D</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L1768</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **nf** (`int`) --
  The number of output features.
- **nx** (`int`) --
  The number of input features.
- **initializer_range** (`float`, *optional*, defaults to 0.02) --
  The standard deviation to use to initialize the weights.
  kwargs --
  Additional keyword arguments passed along to the `__init__` of `tf.keras.layers.Layer`.</paramsdesc><paramgroups>0</paramgroups></docstring>

1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2).

Basically works like a linear layer but the weights are transposed.




</div>

<div class="docstring">

<docstring><name>class transformers.TFSharedEmbeddings</name><anchor>transformers.TFSharedEmbeddings</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L1808</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **vocab_size** (`int`) --
  The size of the vocabulary, e.g., the number of unique tokens.
- **hidden_size** (`int`) --
  The size of the embedding vectors.
- **initializer_range** (`float`, *optional*) --
  The standard deviation to use when initializing the weights. If no value is provided, it will default to
  \\(1/\sqrt&amp;lcub;hidden\_size}\\).
  kwargs --
  Additional keyword arguments passed along to the `__init__` of `tf.keras.layers.Layer`.</paramsdesc><paramgroups>0</paramgroups></docstring>

Construct shared token embeddings.

The weights of the embedding layer is usually shared with the weights of the linear decoder when doing language
modeling.





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFSharedEmbeddings.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L1853</source><parameters>[{"name": "inputs", "val": ": Tensor"}, {"name": "mode", "val": ": str = 'embedding'"}]</parameters><paramsdesc>- **inputs** (`tf.Tensor`) --
  In embedding mode, should be an int64 tensor with shape `[batch_size, length]`.

  In linear mode, should be a float tensor with shape `[batch_size, length, hidden_size]`.
- **mode** (`str`, defaults to `"embedding"`) --
  A valid value is either `"embedding"` or `"linear"`, the first one indicates that the layer should be
  used as an embedding layer, the second one that the layer should be used as a linear decoder.</paramsdesc><paramgroups>0</paramgroups><rettype>`tf.Tensor`</rettype><retdesc>In embedding mode, the output is a float32 embedding tensor, with shape `[batch_size, length,
embedding_size]`.

In linear mode, the output is a float32 with shape `[batch_size, length, vocab_size]`.</retdesc><raises>- `ValueError` -- if `mode` is not valid.</raises><raisederrors>`ValueError`</raisederrors></docstring>

Get token embeddings of inputs or decode final hidden state.











Shared weights logic is adapted from
[here](https://github.com/tensorflow/models/blob/a009f4fb9d2fc4949e32192a944688925ef78659/official/transformer/v2/embedding_layer.py#L24).


</div></div>

<div class="docstring">

<docstring><name>class transformers.TFSequenceSummary</name><anchor>transformers.TFSequenceSummary</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L1906</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig)) --
  The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
  config class of your model for the default values it uses):

  - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:

    - `"last"` -- Take the last token hidden state (like XLNet)
    - `"first"` -- Take the first token hidden state (like Bert)
    - `"mean"` -- Take the mean of all tokens hidden states
    - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
    - `"attn"` -- Not implemented now, use multi-head attention

  - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
  - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
    (otherwise to `config.hidden_size`).
  - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
    another string or `None` will add no activation.
  - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
  - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.

- **initializer_range** (`float`, defaults to 0.02) -- The standard deviation to use to initialize the weights.
  kwargs --
  Additional keyword arguments passed along to the `__init__` of `tf.keras.layers.Layer`.</paramsdesc><paramgroups>0</paramgroups></docstring>

Compute a single vector summary of a sequence hidden states.





<div class="docstring">
<docstring><name>register\_for\_auto\_class</name><anchor>transformers.TFSequenceSummary.register_for_auto_class</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L2021</source><parameters>[{"name": "auto_class", "val": " = 'TFAutoModel'"}]</parameters><paramsdesc>- **auto_class** (`str` or `type`, *optional*, defaults to `"TFAutoModel"`) --
  The auto class to register this new model with.</paramsdesc><paramgroups>0</paramgroups></docstring>

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

<Tip warning=&amp;lcub;true}>

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

</Tip>




</div></div>

<h2 id="transformers.modeling_tf_utils.TFCausalLanguageModelingLoss">TensorFlow loss functions</h2>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFCausalLanguageModelingLoss</name><anchor>transformers.modeling_tf_utils.TFCausalLanguageModelingLoss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L170</source><parameters>[]</parameters></docstring>

Loss function suitable for causal language modeling (CLM), that is, the task of guessing the next token.

<Tip>

Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.

</Tip>


</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFMaskedLanguageModelingLoss</name><anchor>transformers.modeling_tf_utils.TFMaskedLanguageModelingLoss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L261</source><parameters>[]</parameters></docstring>

Loss function suitable for masked language modeling (MLM), that is, the task of guessing the masked tokens.

<Tip>

Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.

</Tip>


</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFMultipleChoiceLoss</name><anchor>transformers.modeling_tf_utils.TFMultipleChoiceLoss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L251</source><parameters>[]</parameters></docstring>
Loss function suitable for multiple choice tasks.

</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFQuestionAnsweringLoss</name><anchor>transformers.modeling_tf_utils.TFQuestionAnsweringLoss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L192</source><parameters>[]</parameters></docstring>

Loss function suitable for question answering.


</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFSequenceClassificationLoss</name><anchor>transformers.modeling_tf_utils.TFSequenceClassificationLoss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L235</source><parameters>[]</parameters></docstring>

Loss function suitable for sequence classification.


</div>

<div class="docstring">

<docstring><name>class transformers.modeling\_tf\_utils.TFTokenClassificationLoss</name><anchor>transformers.modeling_tf_utils.TFTokenClassificationLoss</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L207</source><parameters>[]</parameters></docstring>

Loss function suitable for token classification.

<Tip>

Any label of -100 will be ignored (along with the corresponding logits) in the loss computation.

</Tip>


</div>

<h2 id="transformers.modeling_tf_utils.get_initializer">TensorFlow Helper Functions</h2>

<div class="docstring">

<docstring><name>transformers.modeling\_tf\_utils.get\_initializer</name><anchor>transformers.modeling_tf_utils.get_initializer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L2048</source><parameters>[{"name": "initializer_range", "val": ": float = 0.02"}]</parameters><paramsdesc>- **initializer_range** (*float*, defaults to 0.02) -- Standard deviation of the initializer range.</paramsdesc><paramgroups>0</paramgroups><rettype>`tf.initializers.TruncatedNormal`</rettype><retdesc>The truncated normal initializer.</retdesc></docstring>

Creates a `tf.initializers.TruncatedNormal` with the given range.








</div>

<div class="docstring">

<docstring><name>transformers.modeling\_tf\_utils.keras\_serializable</name><anchor>transformers.modeling_tf_utils.keras_serializable</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/modeling_tf_utils.py#L105</source><parameters>[]</parameters><paramsdesc>- **cls** (a `tf.keras.layers.Layers subclass`) --
  Typically a `TF.MainLayer` class in this project, in general must accept a `config` argument to its
  initializer.</paramsdesc><paramgroups>0</paramgroups><retdesc>The same class object, with modifications for Keras deserialization.</retdesc></docstring>

Decorate a Keras Layer class to support Keras serialization.

This is done by:

1. Adding a `transformers_config` dict to the Keras config dictionary in `get_config` (called by Keras at
   serialization time.
2. Wrapping `__init__` to accept that `transformers_config` dict (passed by Keras at deserialization time) and
   convert it to a config object for the actual layer initializer.
3. Registering the class as a custom object in Keras (if the Tensorflow version supports this), so that it does not
   need to be supplied in `custom_objects` in the call to `tf.keras.models.load_model`.






</div>

<div class="docstring">

<docstring><name>transformers.shape\_list</name><anchor>transformers.shape_list</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/tf_utils.py#L31</source><parameters>[{"name": "tensor", "val": ": typing.Union[tensorflow.python.framework.ops.Tensor, numpy.ndarray]"}]</parameters><paramsdesc>- **tensor** (`tf.Tensor` or `np.ndarray`) -- The tensor we want the shape of.</paramsdesc><paramgroups>0</paramgroups><rettype>`List[int]`</rettype><retdesc>The shape of the tensor as a list.</retdesc></docstring>

Deal with dynamic shape in tensorflow cleanly.








</div>
