.
+ kernel_size (int): The convolution kernel size of the middle layer, .
+ padding (int): Padding value of the convolution in the middle layer.
+ dilation (int, optional): Dilation value of the convolution in the middle layer.
+ no_redisual (bool, optional): Disable residual block/output.
+
+ Note:
+ This implementation corresponds to the "non-causal" setting in the paper.
+ """
+
+ def __init__(
+ self,
+ io_channels: int,
+ hidden_channels: int,
+ kernel_size: int,
+ padding: int,
+ dilation: int = 1,
+ no_residual: bool = False,
+ ):
+ super().__init__()
+
+ self.conv_layers = torch.nn.Sequential(
+ torch.nn.Conv1d(in_channels=io_channels, out_channels=hidden_channels, kernel_size=1),
+ torch.nn.PReLU(),
+ torch.nn.GroupNorm(num_groups=1, num_channels=hidden_channels, eps=1e-08),
+ torch.nn.Conv1d(
+ in_channels=hidden_channels,
+ out_channels=hidden_channels,
+ kernel_size=kernel_size,
+ padding=padding,
+ dilation=dilation,
+ groups=hidden_channels,
+ ),
+ torch.nn.PReLU(),
+ torch.nn.GroupNorm(num_groups=1, num_channels=hidden_channels, eps=1e-08),
+ )
+
+ self.res_out = (
+ None
+ if no_residual
+ else torch.nn.Conv1d(in_channels=hidden_channels, out_channels=io_channels, kernel_size=1)
+ )
+ self.skip_out = torch.nn.Conv1d(in_channels=hidden_channels, out_channels=io_channels, kernel_size=1)
+
+ def forward(self, input: torch.Tensor) -> Tuple[Optional[torch.Tensor], torch.Tensor]:
+ feature = self.conv_layers(input)
+ if self.res_out is None:
+ residual = None
+ else:
+ residual = self.res_out(feature)
+ skip_out = self.skip_out(feature)
+ return residual, skip_out
+
+
+class MaskGenerator(torch.nn.Module):
+ """TCN (Temporal Convolution Network) Separation Module
+
+ Generates masks for separation.
+
+ Args:
+ input_dim (int): Input feature dimension, .
+ num_sources (int): The number of sources to separate.
+ kernel_size (int): The convolution kernel size of conv blocks, .
+ num_featrs (int): Input/output feature dimenstion of conv blocks, .
+ num_hidden (int): Intermediate feature dimention of conv blocks,
+ num_layers (int): The number of conv blocks in one stack, .
+ num_stacks (int): The number of conv block stacks, .
+ msk_activate (str): The activation function of the mask output.
+
+ Note:
+ This implementation corresponds to the "non-causal" setting in the paper.
+ """
+
+ def __init__(
+ self,
+ input_dim: int,
+ num_sources: int,
+ kernel_size: int,
+ num_feats: int,
+ num_hidden: int,
+ num_layers: int,
+ num_stacks: int,
+ msk_activate: str,
+ ):
+ super().__init__()
+
+ self.input_dim = input_dim
+ self.num_sources = num_sources
+
+ self.input_norm = torch.nn.GroupNorm(num_groups=1, num_channels=input_dim, eps=1e-8)
+ self.input_conv = torch.nn.Conv1d(in_channels=input_dim, out_channels=num_feats, kernel_size=1)
+
+ self.receptive_field = 0
+ self.conv_layers = torch.nn.ModuleList([])
+ for s in range(num_stacks):
+ for l in range(num_layers):
+ multi = 2**l
+ self.conv_layers.append(
+ ConvBlock(
+ io_channels=num_feats,
+ hidden_channels=num_hidden,
+ kernel_size=kernel_size,
+ dilation=multi,
+ padding=multi,
+ # The last ConvBlock does not need residual
+ no_residual=(l == (num_layers - 1) and s == (num_stacks - 1)),
+ )
+ )
+ self.receptive_field += kernel_size if s == 0 and l == 0 else (kernel_size - 1) * multi
+ self.output_prelu = torch.nn.PReLU()
+ self.output_conv = torch.nn.Conv1d(
+ in_channels=num_feats,
+ out_channels=input_dim * num_sources,
+ kernel_size=1,
+ )
+ if msk_activate == "sigmoid":
+ self.mask_activate = torch.nn.Sigmoid()
+ elif msk_activate == "relu":
+ self.mask_activate = torch.nn.ReLU()
+ else:
+ raise ValueError(f"Unsupported activation {msk_activate}")
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Generate separation mask.
+
+ Args:
+ input (torch.Tensor): 3D Tensor with shape [batch, features, frames]
+
+ Returns:
+ Tensor: shape [batch, num_sources, features, frames]
+ """
+ batch_size = input.shape[0]
+ feats = self.input_norm(input)
+ feats = self.input_conv(feats)
+ output = 0.0
+ for layer in self.conv_layers:
+ residual, skip = layer(feats)
+ if residual is not None: # the last conv layer does not produce residual
+ feats = feats + residual
+ output = output + skip
+ output = self.output_prelu(output)
+ output = self.output_conv(output)
+ output = self.mask_activate(output)
+ return output.view(batch_size, self.num_sources, self.input_dim, -1)
+
+
+class ConvTasNet(torch.nn.Module):
+ """Conv-TasNet architecture introduced in
+ *Conv-TasNet: Surpassing Ideal Time–Frequency Magnitude Masking for Speech Separation*
+ :cite:`Luo_2019`.
+
+ Note:
+ This implementation corresponds to the "non-causal" setting in the paper.
+
+ See Also:
+ * :class:`torchaudio.pipelines.SourceSeparationBundle`: Source separation pipeline with pre-trained models.
+
+ Args:
+ num_sources (int, optional): The number of sources to split.
+ enc_kernel_size (int, optional): The convolution kernel size of the encoder/decoder, .
+ enc_num_feats (int, optional): The feature dimensions passed to mask generator, .
+ msk_kernel_size (int, optional): The convolution kernel size of the mask generator, .
+ msk_num_feats (int, optional): The input/output feature dimension of conv block in the mask generator, .
+ msk_num_hidden_feats (int, optional): The internal feature dimension of conv block of the mask generator, .
+ msk_num_layers (int, optional): The number of layers in one conv block of the mask generator, .
+ msk_num_stacks (int, optional): The numbr of conv blocks of the mask generator, .
+ msk_activate (str, optional): The activation function of the mask output (Default: ``sigmoid``).
+ """
+
+ def __init__(
+ self,
+ num_sources: int = 2,
+ # encoder/decoder parameters
+ enc_kernel_size: int = 16,
+ enc_num_feats: int = 512,
+ # mask generator parameters
+ msk_kernel_size: int = 3,
+ msk_num_feats: int = 128,
+ msk_num_hidden_feats: int = 512,
+ msk_num_layers: int = 8,
+ msk_num_stacks: int = 3,
+ msk_activate: str = "sigmoid",
+ ):
+ super().__init__()
+
+ self.num_sources = num_sources
+ self.enc_num_feats = enc_num_feats
+ self.enc_kernel_size = enc_kernel_size
+ self.enc_stride = enc_kernel_size // 2
+
+ self.encoder = torch.nn.Conv1d(
+ in_channels=1,
+ out_channels=enc_num_feats,
+ kernel_size=enc_kernel_size,
+ stride=self.enc_stride,
+ padding=self.enc_stride,
+ bias=False,
+ )
+ self.mask_generator = MaskGenerator(
+ input_dim=enc_num_feats,
+ num_sources=num_sources,
+ kernel_size=msk_kernel_size,
+ num_feats=msk_num_feats,
+ num_hidden=msk_num_hidden_feats,
+ num_layers=msk_num_layers,
+ num_stacks=msk_num_stacks,
+ msk_activate=msk_activate,
+ )
+ self.decoder = torch.nn.ConvTranspose1d(
+ in_channels=enc_num_feats,
+ out_channels=1,
+ kernel_size=enc_kernel_size,
+ stride=self.enc_stride,
+ padding=self.enc_stride,
+ bias=False,
+ )
+
+ def _align_num_frames_with_strides(self, input: torch.Tensor) -> Tuple[torch.Tensor, int]:
+ """Pad input Tensor so that the end of the input tensor corresponds with
+
+ 1. (if kernel size is odd) the center of the last convolution kernel
+ or 2. (if kernel size is even) the end of the first half of the last convolution kernel
+
+ Assumption:
+ The resulting Tensor will be padded with the size of stride (== kernel_width // 2)
+ on the both ends in Conv1D
+
+ |<--- k_1 --->|
+ | | |<-- k_n-1 -->|
+ | | | |<--- k_n --->|
+ | | | | |
+ | | | | |
+ | v v v |
+ |<---->|<--- input signal --->|<--->|<---->|
+ stride PAD stride
+
+ Args:
+ input (torch.Tensor): 3D Tensor with shape (batch_size, channels==1, frames)
+
+ Returns:
+ Tensor: Padded Tensor
+ int: Number of paddings performed
+ """
+ batch_size, num_channels, num_frames = input.shape
+ is_odd = self.enc_kernel_size % 2
+ num_strides = (num_frames - is_odd) // self.enc_stride
+ num_remainings = num_frames - (is_odd + num_strides * self.enc_stride)
+ if num_remainings == 0:
+ return input, 0
+
+ num_paddings = self.enc_stride - num_remainings
+ pad = torch.zeros(
+ batch_size,
+ num_channels,
+ num_paddings,
+ dtype=input.dtype,
+ device=input.device,
+ )
+ return torch.cat([input, pad], 2), num_paddings
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Perform source separation. Generate audio source waveforms.
+
+ Args:
+ input (torch.Tensor): 3D Tensor with shape [batch, channel==1, frames]
+
+ Returns:
+ Tensor: 3D Tensor with shape [batch, channel==num_sources, frames]
+ """
+ if input.ndim != 3 or input.shape[1] != 1:
+ raise ValueError(f"Expected 3D tensor (batch, channel==1, frames). Found: {input.shape}")
+
+ # B: batch size
+ # L: input frame length
+ # L': padded input frame length
+ # F: feature dimension
+ # M: feature frame length
+ # S: number of sources
+
+ padded, num_pads = self._align_num_frames_with_strides(input) # B, 1, L'
+ batch_size, num_padded_frames = padded.shape[0], padded.shape[2]
+ feats = self.encoder(padded) # B, F, M
+ masked = self.mask_generator(feats) * feats.unsqueeze(1) # B, S, F, M
+ masked = masked.view(batch_size * self.num_sources, self.enc_num_feats, -1) # B*S, F, M
+ decoded = self.decoder(masked) # B*S, 1, L'
+ output = decoded.view(batch_size, self.num_sources, num_padded_frames) # B, S, L'
+ if num_pads > 0:
+ output = output[..., :-num_pads] # B, S, L
+ return output
+
+
+def conv_tasnet_base(num_sources: int = 2) -> ConvTasNet:
+ r"""Builds non-causal version of :class:`~torchaudio.models.ConvTasNet`.
+
+ The parameter settings follow the ones with the highest Si-SNR metirc score in the paper,
+ except the mask activation function is changed from "sigmoid" to "relu" for performance improvement.
+
+ Args:
+ num_sources (int, optional): Number of sources in the output.
+ (Default: 2)
+ Returns:
+ ConvTasNet:
+ ConvTasNet model.
+ """
+ return ConvTasNet(
+ num_sources=num_sources,
+ enc_kernel_size=16,
+ enc_num_feats=512,
+ msk_kernel_size=3,
+ msk_num_feats=128,
+ msk_num_hidden_feats=512,
+ msk_num_layers=8,
+ msk_num_stacks=3,
+ msk_activate="relu",
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/deepspeech.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/deepspeech.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a6a0faa006a3fa6868ccb7e39e68118d8dbe277
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/deepspeech.py
@@ -0,0 +1,84 @@
+import torch
+
+__all__ = ["DeepSpeech"]
+
+
+class FullyConnected(torch.nn.Module):
+ """
+ Args:
+ n_feature: Number of input features
+ n_hidden: Internal hidden unit size.
+ """
+
+ def __init__(self, n_feature: int, n_hidden: int, dropout: float, relu_max_clip: int = 20) -> None:
+ super(FullyConnected, self).__init__()
+ self.fc = torch.nn.Linear(n_feature, n_hidden, bias=True)
+ self.relu_max_clip = relu_max_clip
+ self.dropout = dropout
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.fc(x)
+ x = torch.nn.functional.relu(x)
+ x = torch.nn.functional.hardtanh(x, 0, self.relu_max_clip)
+ if self.dropout:
+ x = torch.nn.functional.dropout(x, self.dropout, self.training)
+ return x
+
+
+class DeepSpeech(torch.nn.Module):
+ """DeepSpeech architecture introduced in
+ *Deep Speech: Scaling up end-to-end speech recognition* :cite:`hannun2014deep`.
+
+ Args:
+ n_feature: Number of input features
+ n_hidden: Internal hidden unit size.
+ n_class: Number of output classes
+ """
+
+ def __init__(
+ self,
+ n_feature: int,
+ n_hidden: int = 2048,
+ n_class: int = 40,
+ dropout: float = 0.0,
+ ) -> None:
+ super(DeepSpeech, self).__init__()
+ self.n_hidden = n_hidden
+ self.fc1 = FullyConnected(n_feature, n_hidden, dropout)
+ self.fc2 = FullyConnected(n_hidden, n_hidden, dropout)
+ self.fc3 = FullyConnected(n_hidden, n_hidden, dropout)
+ self.bi_rnn = torch.nn.RNN(n_hidden, n_hidden, num_layers=1, nonlinearity="relu", bidirectional=True)
+ self.fc4 = FullyConnected(n_hidden, n_hidden, dropout)
+ self.out = torch.nn.Linear(n_hidden, n_class)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ x (torch.Tensor): Tensor of dimension (batch, channel, time, feature).
+ Returns:
+ Tensor: Predictor tensor of dimension (batch, time, class).
+ """
+ # N x C x T x F
+ x = self.fc1(x)
+ # N x C x T x H
+ x = self.fc2(x)
+ # N x C x T x H
+ x = self.fc3(x)
+ # N x C x T x H
+ x = x.squeeze(1)
+ # N x T x H
+ x = x.transpose(0, 1)
+ # T x N x H
+ x, _ = self.bi_rnn(x)
+ # The fifth (non-recurrent) layer takes both the forward and backward units as inputs
+ x = x[:, :, : self.n_hidden] + x[:, :, self.n_hidden :]
+ # T x N x H
+ x = self.fc4(x)
+ # T x N x H
+ x = self.out(x)
+ # T x N x n_class
+ x = x.permute(1, 0, 2)
+ # N x T x n_class
+ x = torch.nn.functional.log_softmax(x, dim=2)
+ # N x T x n_class
+ return x
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/emformer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/emformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa678869c07126a9a5556d35f40ca3324b3fe6b4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/emformer.py
@@ -0,0 +1,884 @@
+import math
+from typing import List, Optional, Tuple
+
+import torch
+
+
+__all__ = ["Emformer"]
+
+
+def _lengths_to_padding_mask(lengths: torch.Tensor) -> torch.Tensor:
+ batch_size = lengths.shape[0]
+ max_length = int(torch.max(lengths).item())
+ padding_mask = torch.arange(max_length, device=lengths.device, dtype=lengths.dtype).expand(
+ batch_size, max_length
+ ) >= lengths.unsqueeze(1)
+ return padding_mask
+
+
+def _gen_padding_mask(
+ utterance: torch.Tensor,
+ right_context: torch.Tensor,
+ summary: torch.Tensor,
+ lengths: torch.Tensor,
+ mems: torch.Tensor,
+ left_context_key: Optional[torch.Tensor] = None,
+) -> Optional[torch.Tensor]:
+ T = right_context.size(0) + utterance.size(0) + summary.size(0)
+ B = right_context.size(1)
+ if B == 1:
+ padding_mask = None
+ else:
+ right_context_blocks_length = T - torch.max(lengths).int() - summary.size(0)
+ left_context_blocks_length = left_context_key.size(0) if left_context_key is not None else 0
+ klengths = lengths + mems.size(0) + right_context_blocks_length + left_context_blocks_length
+ padding_mask = _lengths_to_padding_mask(lengths=klengths)
+ return padding_mask
+
+
+def _get_activation_module(activation: str) -> torch.nn.Module:
+ if activation == "relu":
+ return torch.nn.ReLU()
+ elif activation == "gelu":
+ return torch.nn.GELU()
+ elif activation == "silu":
+ return torch.nn.SiLU()
+ else:
+ raise ValueError(f"Unsupported activation {activation}")
+
+
+def _get_weight_init_gains(weight_init_scale_strategy: Optional[str], num_layers: int) -> List[Optional[float]]:
+ if weight_init_scale_strategy is None:
+ return [None for _ in range(num_layers)]
+ elif weight_init_scale_strategy == "depthwise":
+ return [1.0 / math.sqrt(layer_idx + 1) for layer_idx in range(num_layers)]
+ elif weight_init_scale_strategy == "constant":
+ return [1.0 / math.sqrt(2) for layer_idx in range(num_layers)]
+ else:
+ raise ValueError(f"Unsupported weight_init_scale_strategy value {weight_init_scale_strategy}")
+
+
+def _gen_attention_mask_block(
+ col_widths: List[int], col_mask: List[bool], num_rows: int, device: torch.device
+) -> torch.Tensor:
+ if len(col_widths) != len(col_mask):
+ raise ValueError("Length of col_widths must match that of col_mask")
+
+ mask_block = [
+ torch.ones(num_rows, col_width, device=device)
+ if is_ones_col
+ else torch.zeros(num_rows, col_width, device=device)
+ for col_width, is_ones_col in zip(col_widths, col_mask)
+ ]
+ return torch.cat(mask_block, dim=1)
+
+
+class _EmformerAttention(torch.nn.Module):
+ r"""Emformer layer attention module.
+
+ Args:
+ input_dim (int): input dimension.
+ num_heads (int): number of attention heads in each Emformer layer.
+ dropout (float, optional): dropout probability. (Default: 0.0)
+ weight_init_gain (float or None, optional): scale factor to apply when initializing
+ attention module parameters. (Default: ``None``)
+ tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)
+ negative_inf (float, optional): value to use for negative infinity in attention weights. (Default: -1e8)
+ """
+
+ def __init__(
+ self,
+ input_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ weight_init_gain: Optional[float] = None,
+ tanh_on_mem: bool = False,
+ negative_inf: float = -1e8,
+ ):
+ super().__init__()
+
+ if input_dim % num_heads != 0:
+ raise ValueError(f"input_dim ({input_dim}) is not a multiple of num_heads ({num_heads}).")
+
+ self.input_dim = input_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.tanh_on_mem = tanh_on_mem
+ self.negative_inf = negative_inf
+
+ self.scaling = (self.input_dim // self.num_heads) ** -0.5
+
+ self.emb_to_key_value = torch.nn.Linear(input_dim, 2 * input_dim, bias=True)
+ self.emb_to_query = torch.nn.Linear(input_dim, input_dim, bias=True)
+ self.out_proj = torch.nn.Linear(input_dim, input_dim, bias=True)
+
+ if weight_init_gain:
+ torch.nn.init.xavier_uniform_(self.emb_to_key_value.weight, gain=weight_init_gain)
+ torch.nn.init.xavier_uniform_(self.emb_to_query.weight, gain=weight_init_gain)
+
+ def _gen_key_value(self, input: torch.Tensor, mems: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ T, _, _ = input.shape
+ summary_length = mems.size(0) + 1
+ right_ctx_utterance_block = input[: T - summary_length]
+ mems_right_ctx_utterance_block = torch.cat([mems, right_ctx_utterance_block])
+ key, value = self.emb_to_key_value(mems_right_ctx_utterance_block).chunk(chunks=2, dim=2)
+ return key, value
+
+ def _gen_attention_probs(
+ self,
+ attention_weights: torch.Tensor,
+ attention_mask: torch.Tensor,
+ padding_mask: Optional[torch.Tensor],
+ ) -> torch.Tensor:
+ attention_weights_float = attention_weights.float()
+ attention_weights_float = attention_weights_float.masked_fill(attention_mask.unsqueeze(0), self.negative_inf)
+ T = attention_weights.size(1)
+ B = attention_weights.size(0) // self.num_heads
+ if padding_mask is not None:
+ attention_weights_float = attention_weights_float.view(B, self.num_heads, T, -1)
+ attention_weights_float = attention_weights_float.masked_fill(
+ padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), self.negative_inf
+ )
+ attention_weights_float = attention_weights_float.view(B * self.num_heads, T, -1)
+ attention_probs = torch.nn.functional.softmax(attention_weights_float, dim=-1).type_as(attention_weights)
+ return torch.nn.functional.dropout(attention_probs, p=float(self.dropout), training=self.training)
+
+ def _forward_impl(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ summary: torch.Tensor,
+ mems: torch.Tensor,
+ attention_mask: torch.Tensor,
+ left_context_key: Optional[torch.Tensor] = None,
+ left_context_val: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ B = utterance.size(1)
+ T = right_context.size(0) + utterance.size(0) + summary.size(0)
+
+ # Compute query with [right context, utterance, summary].
+ query = self.emb_to_query(torch.cat([right_context, utterance, summary]))
+
+ # Compute key and value with [mems, right context, utterance].
+ key, value = self.emb_to_key_value(torch.cat([mems, right_context, utterance])).chunk(chunks=2, dim=2)
+
+ if left_context_key is not None and left_context_val is not None:
+ right_context_blocks_length = T - torch.max(lengths).int() - summary.size(0)
+ key = torch.cat(
+ [
+ key[: mems.size(0) + right_context_blocks_length],
+ left_context_key,
+ key[mems.size(0) + right_context_blocks_length :],
+ ],
+ )
+ value = torch.cat(
+ [
+ value[: mems.size(0) + right_context_blocks_length],
+ left_context_val,
+ value[mems.size(0) + right_context_blocks_length :],
+ ],
+ )
+
+ # Compute attention weights from query, key, and value.
+ reshaped_query, reshaped_key, reshaped_value = [
+ tensor.contiguous().view(-1, B * self.num_heads, self.input_dim // self.num_heads).transpose(0, 1)
+ for tensor in [query, key, value]
+ ]
+ attention_weights = torch.bmm(reshaped_query * self.scaling, reshaped_key.transpose(1, 2))
+
+ # Compute padding mask.
+ padding_mask = _gen_padding_mask(utterance, right_context, summary, lengths, mems, left_context_key)
+
+ # Compute attention probabilities.
+ attention_probs = self._gen_attention_probs(attention_weights, attention_mask, padding_mask)
+
+ # Compute attention.
+ attention = torch.bmm(attention_probs, reshaped_value)
+ if attention.shape != (
+ B * self.num_heads,
+ T,
+ self.input_dim // self.num_heads,
+ ):
+ raise AssertionError("Computed attention has incorrect dimensions")
+ attention = attention.transpose(0, 1).contiguous().view(T, B, self.input_dim)
+
+ # Apply output projection.
+ output_right_context_mems = self.out_proj(attention)
+
+ summary_length = summary.size(0)
+ output_right_context = output_right_context_mems[: T - summary_length]
+ output_mems = output_right_context_mems[T - summary_length :]
+ if self.tanh_on_mem:
+ output_mems = torch.tanh(output_mems)
+ else:
+ output_mems = torch.clamp(output_mems, min=-10, max=10)
+
+ return output_right_context, output_mems, key, value
+
+ def forward(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ summary: torch.Tensor,
+ mems: torch.Tensor,
+ attention_mask: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Forward pass for training.
+
+ B: batch size;
+ D: feature dimension of each frame;
+ T: number of utterance frames;
+ R: number of right context frames;
+ S: number of summary elements;
+ M: number of memory elements.
+
+ Args:
+ utterance (torch.Tensor): utterance frames, with shape `(T, B, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``utterance``.
+ right_context (torch.Tensor): right context frames, with shape `(R, B, D)`.
+ summary (torch.Tensor): summary elements, with shape `(S, B, D)`.
+ mems (torch.Tensor): memory elements, with shape `(M, B, D)`.
+ attention_mask (torch.Tensor): attention mask for underlying attention module.
+
+ Returns:
+ (Tensor, Tensor):
+ Tensor
+ output frames corresponding to utterance and right_context, with shape `(T + R, B, D)`.
+ Tensor
+ updated memory elements, with shape `(M, B, D)`.
+ """
+ output, output_mems, _, _ = self._forward_impl(utterance, lengths, right_context, summary, mems, attention_mask)
+ return output, output_mems[:-1]
+
+ @torch.jit.export
+ def infer(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ summary: torch.Tensor,
+ mems: torch.Tensor,
+ left_context_key: torch.Tensor,
+ left_context_val: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Forward pass for inference.
+
+ B: batch size;
+ D: feature dimension of each frame;
+ T: number of utterance frames;
+ R: number of right context frames;
+ S: number of summary elements;
+ M: number of memory elements.
+
+ Args:
+ utterance (torch.Tensor): utterance frames, with shape `(T, B, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``utterance``.
+ right_context (torch.Tensor): right context frames, with shape `(R, B, D)`.
+ summary (torch.Tensor): summary elements, with shape `(S, B, D)`.
+ mems (torch.Tensor): memory elements, with shape `(M, B, D)`.
+ left_context_key (torch.Tensor): left context attention key computed from preceding invocation.
+ left_context_val (torch.Tensor): left context attention value computed from preceding invocation.
+
+ Returns:
+ (Tensor, Tensor, Tensor, and Tensor):
+ Tensor
+ output frames corresponding to utterance and right_context, with shape `(T + R, B, D)`.
+ Tensor
+ updated memory elements, with shape `(M, B, D)`.
+ Tensor
+ attention key computed for left context and utterance.
+ Tensor
+ attention value computed for left context and utterance.
+ """
+ query_dim = right_context.size(0) + utterance.size(0) + summary.size(0)
+ key_dim = right_context.size(0) + utterance.size(0) + mems.size(0) + left_context_key.size(0)
+ attention_mask = torch.zeros(query_dim, key_dim).to(dtype=torch.bool, device=utterance.device)
+ attention_mask[-1, : mems.size(0)] = True
+ output, output_mems, key, value = self._forward_impl(
+ utterance,
+ lengths,
+ right_context,
+ summary,
+ mems,
+ attention_mask,
+ left_context_key=left_context_key,
+ left_context_val=left_context_val,
+ )
+ return (
+ output,
+ output_mems,
+ key[mems.size(0) + right_context.size(0) :],
+ value[mems.size(0) + right_context.size(0) :],
+ )
+
+
+class _EmformerLayer(torch.nn.Module):
+ r"""Emformer layer that constitutes Emformer.
+
+ Args:
+ input_dim (int): input dimension.
+ num_heads (int): number of attention heads.
+ ffn_dim: (int): hidden layer dimension of feedforward network.
+ segment_length (int): length of each input segment.
+ dropout (float, optional): dropout probability. (Default: 0.0)
+ activation (str, optional): activation function to use in feedforward network.
+ Must be one of ("relu", "gelu", "silu"). (Default: "relu")
+ left_context_length (int, optional): length of left context. (Default: 0)
+ max_memory_size (int, optional): maximum number of memory elements to use. (Default: 0)
+ weight_init_gain (float or None, optional): scale factor to apply when initializing
+ attention module parameters. (Default: ``None``)
+ tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)
+ negative_inf (float, optional): value to use for negative infinity in attention weights. (Default: -1e8)
+ """
+
+ def __init__(
+ self,
+ input_dim: int,
+ num_heads: int,
+ ffn_dim: int,
+ segment_length: int,
+ dropout: float = 0.0,
+ activation: str = "relu",
+ left_context_length: int = 0,
+ max_memory_size: int = 0,
+ weight_init_gain: Optional[float] = None,
+ tanh_on_mem: bool = False,
+ negative_inf: float = -1e8,
+ ):
+ super().__init__()
+
+ self.attention = _EmformerAttention(
+ input_dim=input_dim,
+ num_heads=num_heads,
+ dropout=dropout,
+ weight_init_gain=weight_init_gain,
+ tanh_on_mem=tanh_on_mem,
+ negative_inf=negative_inf,
+ )
+ self.dropout = torch.nn.Dropout(dropout)
+ self.memory_op = torch.nn.AvgPool1d(kernel_size=segment_length, stride=segment_length, ceil_mode=True)
+
+ activation_module = _get_activation_module(activation)
+ self.pos_ff = torch.nn.Sequential(
+ torch.nn.LayerNorm(input_dim),
+ torch.nn.Linear(input_dim, ffn_dim),
+ activation_module,
+ torch.nn.Dropout(dropout),
+ torch.nn.Linear(ffn_dim, input_dim),
+ torch.nn.Dropout(dropout),
+ )
+ self.layer_norm_input = torch.nn.LayerNorm(input_dim)
+ self.layer_norm_output = torch.nn.LayerNorm(input_dim)
+
+ self.left_context_length = left_context_length
+ self.segment_length = segment_length
+ self.max_memory_size = max_memory_size
+ self.input_dim = input_dim
+
+ self.use_mem = max_memory_size > 0
+
+ def _init_state(self, batch_size: int, device: Optional[torch.device]) -> List[torch.Tensor]:
+ empty_memory = torch.zeros(self.max_memory_size, batch_size, self.input_dim, device=device)
+ left_context_key = torch.zeros(self.left_context_length, batch_size, self.input_dim, device=device)
+ left_context_val = torch.zeros(self.left_context_length, batch_size, self.input_dim, device=device)
+ past_length = torch.zeros(1, batch_size, dtype=torch.int32, device=device)
+ return [empty_memory, left_context_key, left_context_val, past_length]
+
+ def _unpack_state(self, state: List[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ past_length = state[3][0][0].item()
+ past_left_context_length = min(self.left_context_length, past_length)
+ past_mem_length = min(self.max_memory_size, math.ceil(past_length / self.segment_length))
+ pre_mems = state[0][self.max_memory_size - past_mem_length :]
+ lc_key = state[1][self.left_context_length - past_left_context_length :]
+ lc_val = state[2][self.left_context_length - past_left_context_length :]
+ return pre_mems, lc_key, lc_val
+
+ def _pack_state(
+ self,
+ next_k: torch.Tensor,
+ next_v: torch.Tensor,
+ update_length: int,
+ mems: torch.Tensor,
+ state: List[torch.Tensor],
+ ) -> List[torch.Tensor]:
+ new_k = torch.cat([state[1], next_k])
+ new_v = torch.cat([state[2], next_v])
+ state[0] = torch.cat([state[0], mems])[-self.max_memory_size :]
+ state[1] = new_k[new_k.shape[0] - self.left_context_length :]
+ state[2] = new_v[new_v.shape[0] - self.left_context_length :]
+ state[3] = state[3] + update_length
+ return state
+
+ def _process_attention_output(
+ self,
+ rc_output: torch.Tensor,
+ utterance: torch.Tensor,
+ right_context: torch.Tensor,
+ ) -> torch.Tensor:
+ result = self.dropout(rc_output) + torch.cat([right_context, utterance])
+ result = self.pos_ff(result) + result
+ result = self.layer_norm_output(result)
+ return result
+
+ def _apply_pre_attention_layer_norm(
+ self, utterance: torch.Tensor, right_context: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ layer_norm_input = self.layer_norm_input(torch.cat([right_context, utterance]))
+ return (
+ layer_norm_input[right_context.size(0) :],
+ layer_norm_input[: right_context.size(0)],
+ )
+
+ def _apply_post_attention_ffn(
+ self, rc_output: torch.Tensor, utterance: torch.Tensor, right_context: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ rc_output = self._process_attention_output(rc_output, utterance, right_context)
+ return rc_output[right_context.size(0) :], rc_output[: right_context.size(0)]
+
+ def _apply_attention_forward(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ mems: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ if attention_mask is None:
+ raise ValueError("attention_mask must be not None when for_inference is False")
+
+ if self.use_mem:
+ summary = self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)
+ else:
+ summary = torch.empty(0).to(dtype=utterance.dtype, device=utterance.device)
+ rc_output, next_m = self.attention(
+ utterance=utterance,
+ lengths=lengths,
+ right_context=right_context,
+ summary=summary,
+ mems=mems,
+ attention_mask=attention_mask,
+ )
+ return rc_output, next_m
+
+ def _apply_attention_infer(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ mems: torch.Tensor,
+ state: Optional[List[torch.Tensor]],
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor]]:
+ if state is None:
+ state = self._init_state(utterance.size(1), device=utterance.device)
+ pre_mems, lc_key, lc_val = self._unpack_state(state)
+ if self.use_mem:
+ summary = self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)
+ summary = summary[:1]
+ else:
+ summary = torch.empty(0).to(dtype=utterance.dtype, device=utterance.device)
+ rc_output, next_m, next_k, next_v = self.attention.infer(
+ utterance=utterance,
+ lengths=lengths,
+ right_context=right_context,
+ summary=summary,
+ mems=pre_mems,
+ left_context_key=lc_key,
+ left_context_val=lc_val,
+ )
+ state = self._pack_state(next_k, next_v, utterance.size(0), mems, state)
+ return rc_output, next_m, state
+
+ def forward(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ mems: torch.Tensor,
+ attention_mask: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Forward pass for training.
+
+ B: batch size;
+ D: feature dimension of each frame;
+ T: number of utterance frames;
+ R: number of right context frames;
+ M: number of memory elements.
+
+ Args:
+ utterance (torch.Tensor): utterance frames, with shape `(T, B, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``utterance``.
+ right_context (torch.Tensor): right context frames, with shape `(R, B, D)`.
+ mems (torch.Tensor): memory elements, with shape `(M, B, D)`.
+ attention_mask (torch.Tensor): attention mask for underlying attention module.
+
+ Returns:
+ (Tensor, Tensor, Tensor):
+ Tensor
+ encoded utterance frames, with shape `(T, B, D)`.
+ Tensor
+ updated right context frames, with shape `(R, B, D)`.
+ Tensor
+ updated memory elements, with shape `(M, B, D)`.
+ """
+ (
+ layer_norm_utterance,
+ layer_norm_right_context,
+ ) = self._apply_pre_attention_layer_norm(utterance, right_context)
+ rc_output, output_mems = self._apply_attention_forward(
+ layer_norm_utterance,
+ lengths,
+ layer_norm_right_context,
+ mems,
+ attention_mask,
+ )
+ output_utterance, output_right_context = self._apply_post_attention_ffn(rc_output, utterance, right_context)
+ return output_utterance, output_right_context, output_mems
+
+ @torch.jit.export
+ def infer(
+ self,
+ utterance: torch.Tensor,
+ lengths: torch.Tensor,
+ right_context: torch.Tensor,
+ state: Optional[List[torch.Tensor]],
+ mems: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor], torch.Tensor]:
+ r"""Forward pass for inference.
+
+ B: batch size;
+ D: feature dimension of each frame;
+ T: number of utterance frames;
+ R: number of right context frames;
+ M: number of memory elements.
+
+ Args:
+ utterance (torch.Tensor): utterance frames, with shape `(T, B, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``utterance``.
+ right_context (torch.Tensor): right context frames, with shape `(R, B, D)`.
+ state (List[torch.Tensor] or None): list of tensors representing layer internal state
+ generated in preceding invocation of ``infer``.
+ mems (torch.Tensor): memory elements, with shape `(M, B, D)`.
+
+ Returns:
+ (Tensor, Tensor, List[torch.Tensor], Tensor):
+ Tensor
+ encoded utterance frames, with shape `(T, B, D)`.
+ Tensor
+ updated right context frames, with shape `(R, B, D)`.
+ List[Tensor]
+ list of tensors representing layer internal state
+ generated in current invocation of ``infer``.
+ Tensor
+ updated memory elements, with shape `(M, B, D)`.
+ """
+ (
+ layer_norm_utterance,
+ layer_norm_right_context,
+ ) = self._apply_pre_attention_layer_norm(utterance, right_context)
+ rc_output, output_mems, output_state = self._apply_attention_infer(
+ layer_norm_utterance, lengths, layer_norm_right_context, mems, state
+ )
+ output_utterance, output_right_context = self._apply_post_attention_ffn(rc_output, utterance, right_context)
+ return output_utterance, output_right_context, output_state, output_mems
+
+
+class _EmformerImpl(torch.nn.Module):
+ def __init__(
+ self,
+ emformer_layers: torch.nn.ModuleList,
+ segment_length: int,
+ left_context_length: int = 0,
+ right_context_length: int = 0,
+ max_memory_size: int = 0,
+ ):
+ super().__init__()
+
+ self.use_mem = max_memory_size > 0
+ self.memory_op = torch.nn.AvgPool1d(
+ kernel_size=segment_length,
+ stride=segment_length,
+ ceil_mode=True,
+ )
+ self.emformer_layers = emformer_layers
+ self.left_context_length = left_context_length
+ self.right_context_length = right_context_length
+ self.segment_length = segment_length
+ self.max_memory_size = max_memory_size
+
+ def _gen_right_context(self, input: torch.Tensor) -> torch.Tensor:
+ T = input.shape[0]
+ num_segs = math.ceil((T - self.right_context_length) / self.segment_length)
+ right_context_blocks = []
+ for seg_idx in range(num_segs - 1):
+ start = (seg_idx + 1) * self.segment_length
+ end = start + self.right_context_length
+ right_context_blocks.append(input[start:end])
+ right_context_blocks.append(input[T - self.right_context_length :])
+ return torch.cat(right_context_blocks)
+
+ def _gen_attention_mask_col_widths(self, seg_idx: int, utterance_length: int) -> List[int]:
+ num_segs = math.ceil(utterance_length / self.segment_length)
+ rc = self.right_context_length
+ lc = self.left_context_length
+ rc_start = seg_idx * rc
+ rc_end = rc_start + rc
+ seg_start = max(seg_idx * self.segment_length - lc, 0)
+ seg_end = min((seg_idx + 1) * self.segment_length, utterance_length)
+ rc_length = self.right_context_length * num_segs
+
+ if self.use_mem:
+ m_start = max(seg_idx - self.max_memory_size, 0)
+ mem_length = num_segs - 1
+ col_widths = [
+ m_start, # before memory
+ seg_idx - m_start, # memory
+ mem_length - seg_idx, # after memory
+ rc_start, # before right context
+ rc, # right context
+ rc_length - rc_end, # after right context
+ seg_start, # before query segment
+ seg_end - seg_start, # query segment
+ utterance_length - seg_end, # after query segment
+ ]
+ else:
+ col_widths = [
+ rc_start, # before right context
+ rc, # right context
+ rc_length - rc_end, # after right context
+ seg_start, # before query segment
+ seg_end - seg_start, # query segment
+ utterance_length - seg_end, # after query segment
+ ]
+
+ return col_widths
+
+ def _gen_attention_mask(self, input: torch.Tensor) -> torch.Tensor:
+ utterance_length = input.size(0)
+ num_segs = math.ceil(utterance_length / self.segment_length)
+
+ rc_mask = []
+ query_mask = []
+ summary_mask = []
+
+ if self.use_mem:
+ num_cols = 9
+ # memory, right context, query segment
+ rc_q_cols_mask = [idx in [1, 4, 7] for idx in range(num_cols)]
+ # right context, query segment
+ s_cols_mask = [idx in [4, 7] for idx in range(num_cols)]
+ masks_to_concat = [rc_mask, query_mask, summary_mask]
+ else:
+ num_cols = 6
+ # right context, query segment
+ rc_q_cols_mask = [idx in [1, 4] for idx in range(num_cols)]
+ s_cols_mask = None
+ masks_to_concat = [rc_mask, query_mask]
+
+ for seg_idx in range(num_segs):
+ col_widths = self._gen_attention_mask_col_widths(seg_idx, utterance_length)
+
+ rc_mask_block = _gen_attention_mask_block(
+ col_widths, rc_q_cols_mask, self.right_context_length, input.device
+ )
+ rc_mask.append(rc_mask_block)
+
+ query_mask_block = _gen_attention_mask_block(
+ col_widths,
+ rc_q_cols_mask,
+ min(
+ self.segment_length,
+ utterance_length - seg_idx * self.segment_length,
+ ),
+ input.device,
+ )
+ query_mask.append(query_mask_block)
+
+ if s_cols_mask is not None:
+ summary_mask_block = _gen_attention_mask_block(col_widths, s_cols_mask, 1, input.device)
+ summary_mask.append(summary_mask_block)
+
+ attention_mask = (1 - torch.cat([torch.cat(mask) for mask in masks_to_concat])).to(torch.bool)
+ return attention_mask
+
+ def forward(self, input: torch.Tensor, lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Forward pass for training and non-streaming inference.
+
+ B: batch size;
+ T: max number of input frames in batch;
+ D: feature dimension of each frame.
+
+ Args:
+ input (torch.Tensor): utterance frames right-padded with right context frames, with
+ shape `(B, T + right_context_length, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid utterance frames for i-th batch element in ``input``.
+
+ Returns:
+ (Tensor, Tensor):
+ Tensor
+ output frames, with shape `(B, T, D)`.
+ Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in output frames.
+ """
+ input = input.permute(1, 0, 2)
+ right_context = self._gen_right_context(input)
+ utterance = input[: input.size(0) - self.right_context_length]
+ attention_mask = self._gen_attention_mask(utterance)
+ mems = (
+ self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)[:-1]
+ if self.use_mem
+ else torch.empty(0).to(dtype=input.dtype, device=input.device)
+ )
+ output = utterance
+ for layer in self.emformer_layers:
+ output, right_context, mems = layer(output, lengths, right_context, mems, attention_mask)
+ return output.permute(1, 0, 2), lengths
+
+ @torch.jit.export
+ def infer(
+ self,
+ input: torch.Tensor,
+ lengths: torch.Tensor,
+ states: Optional[List[List[torch.Tensor]]] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ r"""Forward pass for streaming inference.
+
+ B: batch size;
+ D: feature dimension of each frame.
+
+ Args:
+ input (torch.Tensor): utterance frames right-padded with right context frames, with
+ shape `(B, segment_length + right_context_length, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``input``.
+ states (List[List[torch.Tensor]] or None, optional): list of lists of tensors
+ representing internal state generated in preceding invocation of ``infer``. (Default: ``None``)
+
+ Returns:
+ (Tensor, Tensor, List[List[Tensor]]):
+ Tensor
+ output frames, with shape `(B, segment_length, D)`.
+ Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in output frames.
+ List[List[Tensor]]
+ output states; list of lists of tensors representing internal state
+ generated in current invocation of ``infer``.
+ """
+ if input.size(1) != self.segment_length + self.right_context_length:
+ raise ValueError(
+ "Per configured segment_length and right_context_length"
+ f", expected size of {self.segment_length + self.right_context_length} for dimension 1 of input"
+ f", but got {input.size(1)}."
+ )
+ input = input.permute(1, 0, 2)
+ right_context_start_idx = input.size(0) - self.right_context_length
+ right_context = input[right_context_start_idx:]
+ utterance = input[:right_context_start_idx]
+ output_lengths = torch.clamp(lengths - self.right_context_length, min=0)
+ mems = (
+ self.memory_op(utterance.permute(1, 2, 0)).permute(2, 0, 1)
+ if self.use_mem
+ else torch.empty(0).to(dtype=input.dtype, device=input.device)
+ )
+ output = utterance
+ output_states: List[List[torch.Tensor]] = []
+ for layer_idx, layer in enumerate(self.emformer_layers):
+ output, right_context, output_state, mems = layer.infer(
+ output,
+ output_lengths,
+ right_context,
+ None if states is None else states[layer_idx],
+ mems,
+ )
+ output_states.append(output_state)
+
+ return output.permute(1, 0, 2), output_lengths, output_states
+
+
+class Emformer(_EmformerImpl):
+ r"""Emformer architecture introduced in
+ *Emformer: Efficient Memory Transformer Based Acoustic Model for Low Latency Streaming Speech Recognition*
+ :cite:`shi2021emformer`.
+
+ See Also:
+ * :func:`~torchaudio.models.emformer_rnnt_model`,
+ :func:`~torchaudio.models.emformer_rnnt_base`: factory functions.
+ * :class:`torchaudio.pipelines.RNNTBundle`: ASR pipelines with pretrained model.
+
+ Args:
+ input_dim (int): input dimension.
+ num_heads (int): number of attention heads in each Emformer layer.
+ ffn_dim (int): hidden layer dimension of each Emformer layer's feedforward network.
+ num_layers (int): number of Emformer layers to instantiate.
+ segment_length (int): length of each input segment.
+ dropout (float, optional): dropout probability. (Default: 0.0)
+ activation (str, optional): activation function to use in each Emformer layer's
+ feedforward network. Must be one of ("relu", "gelu", "silu"). (Default: "relu")
+ left_context_length (int, optional): length of left context. (Default: 0)
+ right_context_length (int, optional): length of right context. (Default: 0)
+ max_memory_size (int, optional): maximum number of memory elements to use. (Default: 0)
+ weight_init_scale_strategy (str or None, optional): per-layer weight initialization scaling
+ strategy. Must be one of ("depthwise", "constant", ``None``). (Default: "depthwise")
+ tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)
+ negative_inf (float, optional): value to use for negative infinity in attention weights. (Default: -1e8)
+
+ Examples:
+ >>> emformer = Emformer(512, 8, 2048, 20, 4, right_context_length=1)
+ >>> input = torch.rand(128, 400, 512) # batch, num_frames, feature_dim
+ >>> lengths = torch.randint(1, 200, (128,)) # batch
+ >>> output, lengths = emformer(input, lengths)
+ >>> input = torch.rand(128, 5, 512)
+ >>> lengths = torch.ones(128) * 5
+ >>> output, lengths, states = emformer.infer(input, lengths, None)
+ """
+
+ def __init__(
+ self,
+ input_dim: int,
+ num_heads: int,
+ ffn_dim: int,
+ num_layers: int,
+ segment_length: int,
+ dropout: float = 0.0,
+ activation: str = "relu",
+ left_context_length: int = 0,
+ right_context_length: int = 0,
+ max_memory_size: int = 0,
+ weight_init_scale_strategy: Optional[str] = "depthwise",
+ tanh_on_mem: bool = False,
+ negative_inf: float = -1e8,
+ ):
+ weight_init_gains = _get_weight_init_gains(weight_init_scale_strategy, num_layers)
+ emformer_layers = torch.nn.ModuleList(
+ [
+ _EmformerLayer(
+ input_dim,
+ num_heads,
+ ffn_dim,
+ segment_length,
+ dropout=dropout,
+ activation=activation,
+ left_context_length=left_context_length,
+ max_memory_size=max_memory_size,
+ weight_init_gain=weight_init_gains[layer_idx],
+ tanh_on_mem=tanh_on_mem,
+ negative_inf=negative_inf,
+ )
+ for layer_idx in range(num_layers)
+ ]
+ )
+ super().__init__(
+ emformer_layers,
+ segment_length,
+ left_context_length=left_context_length,
+ right_context_length=right_context_length,
+ max_memory_size=max_memory_size,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/rnnt.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/rnnt.py
new file mode 100644
index 0000000000000000000000000000000000000000..659c7b93442095ad3d7c86e38e328094ce552d0c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/rnnt.py
@@ -0,0 +1,816 @@
+from abc import ABC, abstractmethod
+from typing import List, Optional, Tuple
+
+import torch
+from torchaudio.models import Emformer
+
+
+__all__ = ["RNNT", "emformer_rnnt_base", "emformer_rnnt_model"]
+
+
+class _TimeReduction(torch.nn.Module):
+ r"""Coalesces frames along time dimension into a
+ fewer number of frames with higher feature dimensionality.
+
+ Args:
+ stride (int): number of frames to merge for each output frame.
+ """
+
+ def __init__(self, stride: int) -> None:
+ super().__init__()
+ self.stride = stride
+
+ def forward(self, input: torch.Tensor, lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Forward pass.
+
+ B: batch size;
+ T: maximum input sequence length in batch;
+ D: feature dimension of each input sequence frame.
+
+ Args:
+ input (torch.Tensor): input sequences, with shape `(B, T, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``input``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor):
+ torch.Tensor
+ output sequences, with shape
+ `(B, T // stride, D * stride)`
+ torch.Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in output sequences.
+ """
+ B, T, D = input.shape
+ num_frames = T - (T % self.stride)
+ input = input[:, :num_frames, :]
+ lengths = lengths.div(self.stride, rounding_mode="trunc")
+ T_max = num_frames // self.stride
+
+ output = input.reshape(B, T_max, D * self.stride)
+ output = output.contiguous()
+ return output, lengths
+
+
+class _CustomLSTM(torch.nn.Module):
+ r"""Custom long-short-term memory (LSTM) block that applies layer normalization
+ to internal nodes.
+
+ Args:
+ input_dim (int): input dimension.
+ hidden_dim (int): hidden dimension.
+ layer_norm (bool, optional): if ``True``, enables layer normalization. (Default: ``False``)
+ layer_norm_epsilon (float, optional): value of epsilon to use in
+ layer normalization layers (Default: 1e-5)
+ """
+
+ def __init__(
+ self,
+ input_dim: int,
+ hidden_dim: int,
+ layer_norm: bool = False,
+ layer_norm_epsilon: float = 1e-5,
+ ) -> None:
+ super().__init__()
+ self.x2g = torch.nn.Linear(input_dim, 4 * hidden_dim, bias=(not layer_norm))
+ self.p2g = torch.nn.Linear(hidden_dim, 4 * hidden_dim, bias=False)
+ if layer_norm:
+ self.c_norm = torch.nn.LayerNorm(hidden_dim, eps=layer_norm_epsilon)
+ self.g_norm = torch.nn.LayerNorm(4 * hidden_dim, eps=layer_norm_epsilon)
+ else:
+ self.c_norm = torch.nn.Identity()
+ self.g_norm = torch.nn.Identity()
+
+ self.hidden_dim = hidden_dim
+
+ def forward(
+ self, input: torch.Tensor, state: Optional[List[torch.Tensor]]
+ ) -> Tuple[torch.Tensor, List[torch.Tensor]]:
+ r"""Forward pass.
+
+ B: batch size;
+ T: maximum sequence length in batch;
+ D: feature dimension of each input sequence element.
+
+ Args:
+ input (torch.Tensor): with shape `(T, B, D)`.
+ state (List[torch.Tensor] or None): list of tensors
+ representing internal state generated in preceding invocation
+ of ``forward``.
+
+ Returns:
+ (torch.Tensor, List[torch.Tensor]):
+ torch.Tensor
+ output, with shape `(T, B, hidden_dim)`.
+ List[torch.Tensor]
+ list of tensors representing internal state generated
+ in current invocation of ``forward``.
+ """
+ if state is None:
+ B = input.size(1)
+ h = torch.zeros(B, self.hidden_dim, device=input.device, dtype=input.dtype)
+ c = torch.zeros(B, self.hidden_dim, device=input.device, dtype=input.dtype)
+ else:
+ h, c = state
+
+ gated_input = self.x2g(input)
+ outputs = []
+ for gates in gated_input.unbind(0):
+ gates = gates + self.p2g(h)
+ gates = self.g_norm(gates)
+ input_gate, forget_gate, cell_gate, output_gate = gates.chunk(4, 1)
+ input_gate = input_gate.sigmoid()
+ forget_gate = forget_gate.sigmoid()
+ cell_gate = cell_gate.tanh()
+ output_gate = output_gate.sigmoid()
+ c = forget_gate * c + input_gate * cell_gate
+ c = self.c_norm(c)
+ h = output_gate * c.tanh()
+ outputs.append(h)
+
+ output = torch.stack(outputs, dim=0)
+ state = [h, c]
+
+ return output, state
+
+
+class _Transcriber(ABC):
+ @abstractmethod
+ def forward(self, input: torch.Tensor, lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ pass
+
+ @abstractmethod
+ def infer(
+ self,
+ input: torch.Tensor,
+ lengths: torch.Tensor,
+ states: Optional[List[List[torch.Tensor]]],
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ pass
+
+
+class _EmformerEncoder(torch.nn.Module, _Transcriber):
+ r"""Emformer-based recurrent neural network transducer (RNN-T) encoder (transcription network).
+
+ Args:
+ input_dim (int): feature dimension of each input sequence element.
+ output_dim (int): feature dimension of each output sequence element.
+ segment_length (int): length of input segment expressed as number of frames.
+ right_context_length (int): length of right context expressed as number of frames.
+ time_reduction_input_dim (int): dimension to scale each element in input sequences to
+ prior to applying time reduction block.
+ time_reduction_stride (int): factor by which to reduce length of input sequence.
+ transformer_num_heads (int): number of attention heads in each Emformer layer.
+ transformer_ffn_dim (int): hidden layer dimension of each Emformer layer's feedforward network.
+ transformer_num_layers (int): number of Emformer layers to instantiate.
+ transformer_left_context_length (int): length of left context.
+ transformer_dropout (float, optional): transformer dropout probability. (Default: 0.0)
+ transformer_activation (str, optional): activation function to use in each Emformer layer's
+ feedforward network. Must be one of ("relu", "gelu", "silu"). (Default: "relu")
+ transformer_max_memory_size (int, optional): maximum number of memory elements to use. (Default: 0)
+ transformer_weight_init_scale_strategy (str, optional): per-layer weight initialization scaling
+ strategy. Must be one of ("depthwise", "constant", ``None``). (Default: "depthwise")
+ transformer_tanh_on_mem (bool, optional): if ``True``, applies tanh to memory elements. (Default: ``False``)
+ """
+
+ def __init__(
+ self,
+ *,
+ input_dim: int,
+ output_dim: int,
+ segment_length: int,
+ right_context_length: int,
+ time_reduction_input_dim: int,
+ time_reduction_stride: int,
+ transformer_num_heads: int,
+ transformer_ffn_dim: int,
+ transformer_num_layers: int,
+ transformer_left_context_length: int,
+ transformer_dropout: float = 0.0,
+ transformer_activation: str = "relu",
+ transformer_max_memory_size: int = 0,
+ transformer_weight_init_scale_strategy: str = "depthwise",
+ transformer_tanh_on_mem: bool = False,
+ ) -> None:
+ super().__init__()
+ self.input_linear = torch.nn.Linear(
+ input_dim,
+ time_reduction_input_dim,
+ bias=False,
+ )
+ self.time_reduction = _TimeReduction(time_reduction_stride)
+ transformer_input_dim = time_reduction_input_dim * time_reduction_stride
+ self.transformer = Emformer(
+ transformer_input_dim,
+ transformer_num_heads,
+ transformer_ffn_dim,
+ transformer_num_layers,
+ segment_length // time_reduction_stride,
+ dropout=transformer_dropout,
+ activation=transformer_activation,
+ left_context_length=transformer_left_context_length,
+ right_context_length=right_context_length // time_reduction_stride,
+ max_memory_size=transformer_max_memory_size,
+ weight_init_scale_strategy=transformer_weight_init_scale_strategy,
+ tanh_on_mem=transformer_tanh_on_mem,
+ )
+ self.output_linear = torch.nn.Linear(transformer_input_dim, output_dim)
+ self.layer_norm = torch.nn.LayerNorm(output_dim)
+
+ def forward(self, input: torch.Tensor, lengths: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Forward pass for training.
+
+ B: batch size;
+ T: maximum input sequence length in batch;
+ D: feature dimension of each input sequence frame (input_dim).
+
+ Args:
+ input (torch.Tensor): input frame sequences right-padded with right context, with
+ shape `(B, T + right context length, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``input``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor):
+ torch.Tensor
+ output frame sequences, with
+ shape `(B, T // time_reduction_stride, output_dim)`.
+ torch.Tensor
+ output input lengths, with shape `(B,)` and i-th element representing
+ number of valid elements for i-th batch element in output frame sequences.
+ """
+ input_linear_out = self.input_linear(input)
+ time_reduction_out, time_reduction_lengths = self.time_reduction(input_linear_out, lengths)
+ transformer_out, transformer_lengths = self.transformer(time_reduction_out, time_reduction_lengths)
+ output_linear_out = self.output_linear(transformer_out)
+ layer_norm_out = self.layer_norm(output_linear_out)
+ return layer_norm_out, transformer_lengths
+
+ @torch.jit.export
+ def infer(
+ self,
+ input: torch.Tensor,
+ lengths: torch.Tensor,
+ states: Optional[List[List[torch.Tensor]]],
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ r"""Forward pass for inference.
+
+ B: batch size;
+ T: maximum input sequence segment length in batch;
+ D: feature dimension of each input sequence frame (input_dim).
+
+ Args:
+ input (torch.Tensor): input frame sequence segments right-padded with right context, with
+ shape `(B, T + right context length, D)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``input``.
+ state (List[List[torch.Tensor]] or None): list of lists of tensors
+ representing internal state generated in preceding invocation
+ of ``infer``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
+ torch.Tensor
+ output frame sequences, with
+ shape `(B, T // time_reduction_stride, output_dim)`.
+ torch.Tensor
+ output input lengths, with shape `(B,)` and i-th element representing
+ number of valid elements for i-th batch element in output.
+ List[List[torch.Tensor]]
+ output states; list of lists of tensors
+ representing internal state generated in current invocation
+ of ``infer``.
+ """
+ input_linear_out = self.input_linear(input)
+ time_reduction_out, time_reduction_lengths = self.time_reduction(input_linear_out, lengths)
+ (
+ transformer_out,
+ transformer_lengths,
+ transformer_states,
+ ) = self.transformer.infer(time_reduction_out, time_reduction_lengths, states)
+ output_linear_out = self.output_linear(transformer_out)
+ layer_norm_out = self.layer_norm(output_linear_out)
+ return layer_norm_out, transformer_lengths, transformer_states
+
+
+class _Predictor(torch.nn.Module):
+ r"""Recurrent neural network transducer (RNN-T) prediction network.
+
+ Args:
+ num_symbols (int): size of target token lexicon.
+ output_dim (int): feature dimension of each output sequence element.
+ symbol_embedding_dim (int): dimension of each target token embedding.
+ num_lstm_layers (int): number of LSTM layers to instantiate.
+ lstm_hidden_dim (int): output dimension of each LSTM layer.
+ lstm_layer_norm (bool, optional): if ``True``, enables layer normalization
+ for LSTM layers. (Default: ``False``)
+ lstm_layer_norm_epsilon (float, optional): value of epsilon to use in
+ LSTM layer normalization layers. (Default: 1e-5)
+ lstm_dropout (float, optional): LSTM dropout probability. (Default: 0.0)
+
+ """
+
+ def __init__(
+ self,
+ num_symbols: int,
+ output_dim: int,
+ symbol_embedding_dim: int,
+ num_lstm_layers: int,
+ lstm_hidden_dim: int,
+ lstm_layer_norm: bool = False,
+ lstm_layer_norm_epsilon: float = 1e-5,
+ lstm_dropout: float = 0.0,
+ ) -> None:
+ super().__init__()
+ self.embedding = torch.nn.Embedding(num_symbols, symbol_embedding_dim)
+ self.input_layer_norm = torch.nn.LayerNorm(symbol_embedding_dim)
+ self.lstm_layers = torch.nn.ModuleList(
+ [
+ _CustomLSTM(
+ symbol_embedding_dim if idx == 0 else lstm_hidden_dim,
+ lstm_hidden_dim,
+ layer_norm=lstm_layer_norm,
+ layer_norm_epsilon=lstm_layer_norm_epsilon,
+ )
+ for idx in range(num_lstm_layers)
+ ]
+ )
+ self.dropout = torch.nn.Dropout(p=lstm_dropout)
+ self.linear = torch.nn.Linear(lstm_hidden_dim, output_dim)
+ self.output_layer_norm = torch.nn.LayerNorm(output_dim)
+
+ self.lstm_dropout = lstm_dropout
+
+ def forward(
+ self,
+ input: torch.Tensor,
+ lengths: torch.Tensor,
+ state: Optional[List[List[torch.Tensor]]] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ r"""Forward pass.
+
+ B: batch size;
+ U: maximum sequence length in batch;
+ D: feature dimension of each input sequence element.
+
+ Args:
+ input (torch.Tensor): target sequences, with shape `(B, U)` and each element
+ mapping to a target symbol, i.e. in range `[0, num_symbols)`.
+ lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``input``.
+ state (List[List[torch.Tensor]] or None, optional): list of lists of tensors
+ representing internal state generated in preceding invocation
+ of ``forward``. (Default: ``None``)
+
+ Returns:
+ (torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
+ torch.Tensor
+ output encoding sequences, with shape `(B, U, output_dim)`
+ torch.Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid elements for i-th batch element in output encoding sequences.
+ List[List[torch.Tensor]]
+ output states; list of lists of tensors
+ representing internal state generated in current invocation of ``forward``.
+ """
+ input_tb = input.permute(1, 0)
+ embedding_out = self.embedding(input_tb)
+ input_layer_norm_out = self.input_layer_norm(embedding_out)
+
+ lstm_out = input_layer_norm_out
+ state_out: List[List[torch.Tensor]] = []
+ for layer_idx, lstm in enumerate(self.lstm_layers):
+ lstm_out, lstm_state_out = lstm(lstm_out, None if state is None else state[layer_idx])
+ lstm_out = self.dropout(lstm_out)
+ state_out.append(lstm_state_out)
+
+ linear_out = self.linear(lstm_out)
+ output_layer_norm_out = self.output_layer_norm(linear_out)
+ return output_layer_norm_out.permute(1, 0, 2), lengths, state_out
+
+
+class _Joiner(torch.nn.Module):
+ r"""Recurrent neural network transducer (RNN-T) joint network.
+
+ Args:
+ input_dim (int): source and target input dimension.
+ output_dim (int): output dimension.
+ activation (str, optional): activation function to use in the joiner.
+ Must be one of ("relu", "tanh"). (Default: "relu")
+
+ """
+
+ def __init__(self, input_dim: int, output_dim: int, activation: str = "relu") -> None:
+ super().__init__()
+ self.linear = torch.nn.Linear(input_dim, output_dim, bias=True)
+ if activation == "relu":
+ self.activation = torch.nn.ReLU()
+ elif activation == "tanh":
+ self.activation = torch.nn.Tanh()
+ else:
+ raise ValueError(f"Unsupported activation {activation}")
+
+ def forward(
+ self,
+ source_encodings: torch.Tensor,
+ source_lengths: torch.Tensor,
+ target_encodings: torch.Tensor,
+ target_lengths: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Forward pass for training.
+
+ B: batch size;
+ T: maximum source sequence length in batch;
+ U: maximum target sequence length in batch;
+ D: dimension of each source and target sequence encoding.
+
+ Args:
+ source_encodings (torch.Tensor): source encoding sequences, with
+ shape `(B, T, D)`.
+ source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ valid sequence length of i-th batch element in ``source_encodings``.
+ target_encodings (torch.Tensor): target encoding sequences, with shape `(B, U, D)`.
+ target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ valid sequence length of i-th batch element in ``target_encodings``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor, torch.Tensor):
+ torch.Tensor
+ joint network output, with shape `(B, T, U, output_dim)`.
+ torch.Tensor
+ output source lengths, with shape `(B,)` and i-th element representing
+ number of valid elements along dim 1 for i-th batch element in joint network output.
+ torch.Tensor
+ output target lengths, with shape `(B,)` and i-th element representing
+ number of valid elements along dim 2 for i-th batch element in joint network output.
+ """
+ joint_encodings = source_encodings.unsqueeze(2).contiguous() + target_encodings.unsqueeze(1).contiguous()
+ activation_out = self.activation(joint_encodings)
+ output = self.linear(activation_out)
+ return output, source_lengths, target_lengths
+
+
+class RNNT(torch.nn.Module):
+ r"""torchaudio.models.RNNT()
+
+ Recurrent neural network transducer (RNN-T) model.
+
+ Note:
+ To build the model, please use one of the factory functions.
+
+ See Also:
+ :class:`torchaudio.pipelines.RNNTBundle`: ASR pipeline with pre-trained models.
+
+ Args:
+ transcriber (torch.nn.Module): transcription network.
+ predictor (torch.nn.Module): prediction network.
+ joiner (torch.nn.Module): joint network.
+ """
+
+ def __init__(self, transcriber: _Transcriber, predictor: _Predictor, joiner: _Joiner) -> None:
+ super().__init__()
+ self.transcriber = transcriber
+ self.predictor = predictor
+ self.joiner = joiner
+
+ def forward(
+ self,
+ sources: torch.Tensor,
+ source_lengths: torch.Tensor,
+ targets: torch.Tensor,
+ target_lengths: torch.Tensor,
+ predictor_state: Optional[List[List[torch.Tensor]]] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ r"""Forward pass for training.
+
+ B: batch size;
+ T: maximum source sequence length in batch;
+ U: maximum target sequence length in batch;
+ D: feature dimension of each source sequence element.
+
+ Args:
+ sources (torch.Tensor): source frame sequences right-padded with right context, with
+ shape `(B, T, D)`.
+ source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``sources``.
+ targets (torch.Tensor): target sequences, with shape `(B, U)` and each element
+ mapping to a target symbol.
+ target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``targets``.
+ predictor_state (List[List[torch.Tensor]] or None, optional): list of lists of tensors
+ representing prediction network internal state generated in preceding invocation
+ of ``forward``. (Default: ``None``)
+
+ Returns:
+ (torch.Tensor, torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
+ torch.Tensor
+ joint network output, with shape
+ `(B, max output source length, max output target length, output_dim (number of target symbols))`.
+ torch.Tensor
+ output source lengths, with shape `(B,)` and i-th element representing
+ number of valid elements along dim 1 for i-th batch element in joint network output.
+ torch.Tensor
+ output target lengths, with shape `(B,)` and i-th element representing
+ number of valid elements along dim 2 for i-th batch element in joint network output.
+ List[List[torch.Tensor]]
+ output states; list of lists of tensors
+ representing prediction network internal state generated in current invocation
+ of ``forward``.
+ """
+ source_encodings, source_lengths = self.transcriber(
+ input=sources,
+ lengths=source_lengths,
+ )
+ target_encodings, target_lengths, predictor_state = self.predictor(
+ input=targets,
+ lengths=target_lengths,
+ state=predictor_state,
+ )
+ output, source_lengths, target_lengths = self.joiner(
+ source_encodings=source_encodings,
+ source_lengths=source_lengths,
+ target_encodings=target_encodings,
+ target_lengths=target_lengths,
+ )
+
+ return (
+ output,
+ source_lengths,
+ target_lengths,
+ predictor_state,
+ )
+
+ @torch.jit.export
+ def transcribe_streaming(
+ self,
+ sources: torch.Tensor,
+ source_lengths: torch.Tensor,
+ state: Optional[List[List[torch.Tensor]]],
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ r"""Applies transcription network to sources in streaming mode.
+
+ B: batch size;
+ T: maximum source sequence segment length in batch;
+ D: feature dimension of each source sequence frame.
+
+ Args:
+ sources (torch.Tensor): source frame sequence segments right-padded with right context, with
+ shape `(B, T + right context length, D)`.
+ source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``sources``.
+ state (List[List[torch.Tensor]] or None): list of lists of tensors
+ representing transcription network internal state generated in preceding invocation
+ of ``transcribe_streaming``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
+ torch.Tensor
+ output frame sequences, with
+ shape `(B, T // time_reduction_stride, output_dim)`.
+ torch.Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid elements for i-th batch element in output.
+ List[List[torch.Tensor]]
+ output states; list of lists of tensors
+ representing transcription network internal state generated in current invocation
+ of ``transcribe_streaming``.
+ """
+ return self.transcriber.infer(sources, source_lengths, state)
+
+ @torch.jit.export
+ def transcribe(
+ self,
+ sources: torch.Tensor,
+ source_lengths: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Applies transcription network to sources in non-streaming mode.
+
+ B: batch size;
+ T: maximum source sequence length in batch;
+ D: feature dimension of each source sequence frame.
+
+ Args:
+ sources (torch.Tensor): source frame sequences right-padded with right context, with
+ shape `(B, T + right context length, D)`.
+ source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``sources``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor):
+ torch.Tensor
+ output frame sequences, with
+ shape `(B, T // time_reduction_stride, output_dim)`.
+ torch.Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid elements for i-th batch element in output frame sequences.
+ """
+ return self.transcriber(sources, source_lengths)
+
+ @torch.jit.export
+ def predict(
+ self,
+ targets: torch.Tensor,
+ target_lengths: torch.Tensor,
+ state: Optional[List[List[torch.Tensor]]],
+ ) -> Tuple[torch.Tensor, torch.Tensor, List[List[torch.Tensor]]]:
+ r"""Applies prediction network to targets.
+
+ B: batch size;
+ U: maximum target sequence length in batch;
+ D: feature dimension of each target sequence frame.
+
+ Args:
+ targets (torch.Tensor): target sequences, with shape `(B, U)` and each element
+ mapping to a target symbol, i.e. in range `[0, num_symbols)`.
+ target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ number of valid frames for i-th batch element in ``targets``.
+ state (List[List[torch.Tensor]] or None): list of lists of tensors
+ representing internal state generated in preceding invocation
+ of ``predict``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor, List[List[torch.Tensor]]):
+ torch.Tensor
+ output frame sequences, with shape `(B, U, output_dim)`.
+ torch.Tensor
+ output lengths, with shape `(B,)` and i-th element representing
+ number of valid elements for i-th batch element in output.
+ List[List[torch.Tensor]]
+ output states; list of lists of tensors
+ representing internal state generated in current invocation of ``predict``.
+ """
+ return self.predictor(input=targets, lengths=target_lengths, state=state)
+
+ @torch.jit.export
+ def join(
+ self,
+ source_encodings: torch.Tensor,
+ source_lengths: torch.Tensor,
+ target_encodings: torch.Tensor,
+ target_lengths: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Applies joint network to source and target encodings.
+
+ B: batch size;
+ T: maximum source sequence length in batch;
+ U: maximum target sequence length in batch;
+ D: dimension of each source and target sequence encoding.
+
+ Args:
+ source_encodings (torch.Tensor): source encoding sequences, with
+ shape `(B, T, D)`.
+ source_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ valid sequence length of i-th batch element in ``source_encodings``.
+ target_encodings (torch.Tensor): target encoding sequences, with shape `(B, U, D)`.
+ target_lengths (torch.Tensor): with shape `(B,)` and i-th element representing
+ valid sequence length of i-th batch element in ``target_encodings``.
+
+ Returns:
+ (torch.Tensor, torch.Tensor, torch.Tensor):
+ torch.Tensor
+ joint network output, with shape `(B, T, U, output_dim)`.
+ torch.Tensor
+ output source lengths, with shape `(B,)` and i-th element representing
+ number of valid elements along dim 1 for i-th batch element in joint network output.
+ torch.Tensor
+ output target lengths, with shape `(B,)` and i-th element representing
+ number of valid elements along dim 2 for i-th batch element in joint network output.
+ """
+ output, source_lengths, target_lengths = self.joiner(
+ source_encodings=source_encodings,
+ source_lengths=source_lengths,
+ target_encodings=target_encodings,
+ target_lengths=target_lengths,
+ )
+ return output, source_lengths, target_lengths
+
+
+def emformer_rnnt_model(
+ *,
+ input_dim: int,
+ encoding_dim: int,
+ num_symbols: int,
+ segment_length: int,
+ right_context_length: int,
+ time_reduction_input_dim: int,
+ time_reduction_stride: int,
+ transformer_num_heads: int,
+ transformer_ffn_dim: int,
+ transformer_num_layers: int,
+ transformer_dropout: float,
+ transformer_activation: str,
+ transformer_left_context_length: int,
+ transformer_max_memory_size: int,
+ transformer_weight_init_scale_strategy: str,
+ transformer_tanh_on_mem: bool,
+ symbol_embedding_dim: int,
+ num_lstm_layers: int,
+ lstm_layer_norm: bool,
+ lstm_layer_norm_epsilon: float,
+ lstm_dropout: float,
+) -> RNNT:
+ r"""Builds Emformer-based :class:`~torchaudio.models.RNNT`.
+
+ Note:
+ For non-streaming inference, the expectation is for `transcribe` to be called on input
+ sequences right-concatenated with `right_context_length` frames.
+
+ For streaming inference, the expectation is for `transcribe_streaming` to be called
+ on input chunks comprising `segment_length` frames right-concatenated with `right_context_length`
+ frames.
+
+ Args:
+ input_dim (int): dimension of input sequence frames passed to transcription network.
+ encoding_dim (int): dimension of transcription- and prediction-network-generated encodings
+ passed to joint network.
+ num_symbols (int): cardinality of set of target tokens.
+ segment_length (int): length of input segment expressed as number of frames.
+ right_context_length (int): length of right context expressed as number of frames.
+ time_reduction_input_dim (int): dimension to scale each element in input sequences to
+ prior to applying time reduction block.
+ time_reduction_stride (int): factor by which to reduce length of input sequence.
+ transformer_num_heads (int): number of attention heads in each Emformer layer.
+ transformer_ffn_dim (int): hidden layer dimension of each Emformer layer's feedforward network.
+ transformer_num_layers (int): number of Emformer layers to instantiate.
+ transformer_left_context_length (int): length of left context considered by Emformer.
+ transformer_dropout (float): Emformer dropout probability.
+ transformer_activation (str): activation function to use in each Emformer layer's
+ feedforward network. Must be one of ("relu", "gelu", "silu").
+ transformer_max_memory_size (int): maximum number of memory elements to use.
+ transformer_weight_init_scale_strategy (str): per-layer weight initialization scaling
+ strategy. Must be one of ("depthwise", "constant", ``None``).
+ transformer_tanh_on_mem (bool): if ``True``, applies tanh to memory elements.
+ symbol_embedding_dim (int): dimension of each target token embedding.
+ num_lstm_layers (int): number of LSTM layers to instantiate.
+ lstm_layer_norm (bool): if ``True``, enables layer normalization for LSTM layers.
+ lstm_layer_norm_epsilon (float): value of epsilon to use in LSTM layer normalization layers.
+ lstm_dropout (float): LSTM dropout probability.
+
+ Returns:
+ RNNT:
+ Emformer RNN-T model.
+ """
+ encoder = _EmformerEncoder(
+ input_dim=input_dim,
+ output_dim=encoding_dim,
+ segment_length=segment_length,
+ right_context_length=right_context_length,
+ time_reduction_input_dim=time_reduction_input_dim,
+ time_reduction_stride=time_reduction_stride,
+ transformer_num_heads=transformer_num_heads,
+ transformer_ffn_dim=transformer_ffn_dim,
+ transformer_num_layers=transformer_num_layers,
+ transformer_dropout=transformer_dropout,
+ transformer_activation=transformer_activation,
+ transformer_left_context_length=transformer_left_context_length,
+ transformer_max_memory_size=transformer_max_memory_size,
+ transformer_weight_init_scale_strategy=transformer_weight_init_scale_strategy,
+ transformer_tanh_on_mem=transformer_tanh_on_mem,
+ )
+ predictor = _Predictor(
+ num_symbols,
+ encoding_dim,
+ symbol_embedding_dim=symbol_embedding_dim,
+ num_lstm_layers=num_lstm_layers,
+ lstm_hidden_dim=symbol_embedding_dim,
+ lstm_layer_norm=lstm_layer_norm,
+ lstm_layer_norm_epsilon=lstm_layer_norm_epsilon,
+ lstm_dropout=lstm_dropout,
+ )
+ joiner = _Joiner(encoding_dim, num_symbols)
+ return RNNT(encoder, predictor, joiner)
+
+
+def emformer_rnnt_base(num_symbols: int) -> RNNT:
+ r"""Builds basic version of Emformer-based :class:`~torchaudio.models.RNNT`.
+
+ Args:
+ num_symbols (int): The size of target token lexicon.
+
+ Returns:
+ RNNT:
+ Emformer RNN-T model.
+ """
+ return emformer_rnnt_model(
+ input_dim=80,
+ encoding_dim=1024,
+ num_symbols=num_symbols,
+ segment_length=16,
+ right_context_length=4,
+ time_reduction_input_dim=128,
+ time_reduction_stride=4,
+ transformer_num_heads=8,
+ transformer_ffn_dim=2048,
+ transformer_num_layers=20,
+ transformer_dropout=0.1,
+ transformer_activation="gelu",
+ transformer_left_context_length=30,
+ transformer_max_memory_size=0,
+ transformer_weight_init_scale_strategy="depthwise",
+ transformer_tanh_on_mem=True,
+ symbol_embedding_dim=512,
+ num_lstm_layers=3,
+ lstm_layer_norm=True,
+ lstm_layer_norm_epsilon=1e-3,
+ lstm_dropout=0.3,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/rnnt_decoder.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/rnnt_decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fe03715513a077984f5c3d4fcf95e0fa653b5f7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/rnnt_decoder.py
@@ -0,0 +1,339 @@
+from typing import Callable, Dict, List, Optional, Tuple
+
+import torch
+from torchaudio.models import RNNT
+
+
+__all__ = ["Hypothesis", "RNNTBeamSearch"]
+
+
+Hypothesis = Tuple[List[int], torch.Tensor, List[List[torch.Tensor]], float]
+Hypothesis.__doc__ = """Hypothesis generated by RNN-T beam search decoder,
+ represented as tuple of (tokens, prediction network output, prediction network state, score).
+ """
+
+
+def _get_hypo_tokens(hypo: Hypothesis) -> List[int]:
+ return hypo[0]
+
+
+def _get_hypo_predictor_out(hypo: Hypothesis) -> torch.Tensor:
+ return hypo[1]
+
+
+def _get_hypo_state(hypo: Hypothesis) -> List[List[torch.Tensor]]:
+ return hypo[2]
+
+
+def _get_hypo_score(hypo: Hypothesis) -> float:
+ return hypo[3]
+
+
+def _get_hypo_key(hypo: Hypothesis) -> str:
+ return str(hypo[0])
+
+
+def _batch_state(hypos: List[Hypothesis]) -> List[List[torch.Tensor]]:
+ states: List[List[torch.Tensor]] = []
+ for i in range(len(_get_hypo_state(hypos[0]))):
+ batched_state_components: List[torch.Tensor] = []
+ for j in range(len(_get_hypo_state(hypos[0])[i])):
+ batched_state_components.append(torch.cat([_get_hypo_state(hypo)[i][j] for hypo in hypos]))
+ states.append(batched_state_components)
+ return states
+
+
+def _slice_state(states: List[List[torch.Tensor]], idx: int, device: torch.device) -> List[List[torch.Tensor]]:
+ idx_tensor = torch.tensor([idx], device=device)
+ return [[state.index_select(0, idx_tensor) for state in state_tuple] for state_tuple in states]
+
+
+def _default_hypo_sort_key(hypo: Hypothesis) -> float:
+ return _get_hypo_score(hypo) / (len(_get_hypo_tokens(hypo)) + 1)
+
+
+def _compute_updated_scores(
+ hypos: List[Hypothesis],
+ next_token_probs: torch.Tensor,
+ beam_width: int,
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ hypo_scores = torch.tensor([_get_hypo_score(h) for h in hypos]).unsqueeze(1)
+ nonblank_scores = hypo_scores + next_token_probs[:, :-1] # [beam_width, num_tokens - 1]
+ nonblank_nbest_scores, nonblank_nbest_idx = nonblank_scores.reshape(-1).topk(beam_width)
+ nonblank_nbest_hypo_idx = nonblank_nbest_idx.div(nonblank_scores.shape[1], rounding_mode="trunc")
+ nonblank_nbest_token = nonblank_nbest_idx % nonblank_scores.shape[1]
+ return nonblank_nbest_scores, nonblank_nbest_hypo_idx, nonblank_nbest_token
+
+
+def _remove_hypo(hypo: Hypothesis, hypo_list: List[Hypothesis]) -> None:
+ for i, elem in enumerate(hypo_list):
+ if _get_hypo_key(hypo) == _get_hypo_key(elem):
+ del hypo_list[i]
+ break
+
+
+class RNNTBeamSearch(torch.nn.Module):
+ r"""Beam search decoder for RNN-T model.
+
+ See Also:
+ * :class:`torchaudio.pipelines.RNNTBundle`: ASR pipeline with pretrained model.
+
+ Args:
+ model (RNNT): RNN-T model to use.
+ blank (int): index of blank token in vocabulary.
+ temperature (float, optional): temperature to apply to joint network output.
+ Larger values yield more uniform samples. (Default: 1.0)
+ hypo_sort_key (Callable[[Hypothesis], float] or None, optional): callable that computes a score
+ for a given hypothesis to rank hypotheses by. If ``None``, defaults to callable that returns
+ hypothesis score normalized by token sequence length. (Default: None)
+ step_max_tokens (int, optional): maximum number of tokens to emit per input time step. (Default: 100)
+ """
+
+ def __init__(
+ self,
+ model: RNNT,
+ blank: int,
+ temperature: float = 1.0,
+ hypo_sort_key: Optional[Callable[[Hypothesis], float]] = None,
+ step_max_tokens: int = 100,
+ ) -> None:
+ super().__init__()
+ self.model = model
+ self.blank = blank
+ self.temperature = temperature
+
+ if hypo_sort_key is None:
+ self.hypo_sort_key = _default_hypo_sort_key
+ else:
+ self.hypo_sort_key = hypo_sort_key
+
+ self.step_max_tokens = step_max_tokens
+
+ def _init_b_hypos(self, device: torch.device) -> List[Hypothesis]:
+ token = self.blank
+ state = None
+
+ one_tensor = torch.tensor([1], device=device)
+ pred_out, _, pred_state = self.model.predict(torch.tensor([[token]], device=device), one_tensor, state)
+ init_hypo = (
+ [token],
+ pred_out[0].detach(),
+ pred_state,
+ 0.0,
+ )
+ return [init_hypo]
+
+ def _gen_next_token_probs(
+ self, enc_out: torch.Tensor, hypos: List[Hypothesis], device: torch.device
+ ) -> torch.Tensor:
+ one_tensor = torch.tensor([1], device=device)
+ predictor_out = torch.stack([_get_hypo_predictor_out(h) for h in hypos], dim=0)
+ joined_out, _, _ = self.model.join(
+ enc_out,
+ one_tensor,
+ predictor_out,
+ torch.tensor([1] * len(hypos), device=device),
+ ) # [beam_width, 1, 1, num_tokens]
+ joined_out = torch.nn.functional.log_softmax(joined_out / self.temperature, dim=3)
+ return joined_out[:, 0, 0]
+
+ def _gen_b_hypos(
+ self,
+ b_hypos: List[Hypothesis],
+ a_hypos: List[Hypothesis],
+ next_token_probs: torch.Tensor,
+ key_to_b_hypo: Dict[str, Hypothesis],
+ ) -> List[Hypothesis]:
+ for i in range(len(a_hypos)):
+ h_a = a_hypos[i]
+ append_blank_score = _get_hypo_score(h_a) + next_token_probs[i, -1]
+ if _get_hypo_key(h_a) in key_to_b_hypo:
+ h_b = key_to_b_hypo[_get_hypo_key(h_a)]
+ _remove_hypo(h_b, b_hypos)
+ score = float(torch.tensor(_get_hypo_score(h_b)).logaddexp(append_blank_score))
+ else:
+ score = float(append_blank_score)
+ h_b = (
+ _get_hypo_tokens(h_a),
+ _get_hypo_predictor_out(h_a),
+ _get_hypo_state(h_a),
+ score,
+ )
+ b_hypos.append(h_b)
+ key_to_b_hypo[_get_hypo_key(h_b)] = h_b
+ _, sorted_idx = torch.tensor([_get_hypo_score(hypo) for hypo in b_hypos]).sort()
+ return [b_hypos[idx] for idx in sorted_idx]
+
+ def _gen_a_hypos(
+ self,
+ a_hypos: List[Hypothesis],
+ b_hypos: List[Hypothesis],
+ next_token_probs: torch.Tensor,
+ t: int,
+ beam_width: int,
+ device: torch.device,
+ ) -> List[Hypothesis]:
+ (
+ nonblank_nbest_scores,
+ nonblank_nbest_hypo_idx,
+ nonblank_nbest_token,
+ ) = _compute_updated_scores(a_hypos, next_token_probs, beam_width)
+
+ if len(b_hypos) < beam_width:
+ b_nbest_score = -float("inf")
+ else:
+ b_nbest_score = _get_hypo_score(b_hypos[-beam_width])
+
+ base_hypos: List[Hypothesis] = []
+ new_tokens: List[int] = []
+ new_scores: List[float] = []
+ for i in range(beam_width):
+ score = float(nonblank_nbest_scores[i])
+ if score > b_nbest_score:
+ a_hypo_idx = int(nonblank_nbest_hypo_idx[i])
+ base_hypos.append(a_hypos[a_hypo_idx])
+ new_tokens.append(int(nonblank_nbest_token[i]))
+ new_scores.append(score)
+
+ if base_hypos:
+ new_hypos = self._gen_new_hypos(base_hypos, new_tokens, new_scores, t, device)
+ else:
+ new_hypos: List[Hypothesis] = []
+
+ return new_hypos
+
+ def _gen_new_hypos(
+ self,
+ base_hypos: List[Hypothesis],
+ tokens: List[int],
+ scores: List[float],
+ t: int,
+ device: torch.device,
+ ) -> List[Hypothesis]:
+ tgt_tokens = torch.tensor([[token] for token in tokens], device=device)
+ states = _batch_state(base_hypos)
+ pred_out, _, pred_states = self.model.predict(
+ tgt_tokens,
+ torch.tensor([1] * len(base_hypos), device=device),
+ states,
+ )
+ new_hypos: List[Hypothesis] = []
+ for i, h_a in enumerate(base_hypos):
+ new_tokens = _get_hypo_tokens(h_a) + [tokens[i]]
+ new_hypos.append((new_tokens, pred_out[i].detach(), _slice_state(pred_states, i, device), scores[i]))
+ return new_hypos
+
+ def _search(
+ self,
+ enc_out: torch.Tensor,
+ hypo: Optional[List[Hypothesis]],
+ beam_width: int,
+ ) -> List[Hypothesis]:
+ n_time_steps = enc_out.shape[1]
+ device = enc_out.device
+
+ a_hypos: List[Hypothesis] = []
+ b_hypos = self._init_b_hypos(device) if hypo is None else hypo
+ for t in range(n_time_steps):
+ a_hypos = b_hypos
+ b_hypos = torch.jit.annotate(List[Hypothesis], [])
+ key_to_b_hypo: Dict[str, Hypothesis] = {}
+ symbols_current_t = 0
+
+ while a_hypos:
+ next_token_probs = self._gen_next_token_probs(enc_out[:, t : t + 1], a_hypos, device)
+ next_token_probs = next_token_probs.cpu()
+ b_hypos = self._gen_b_hypos(b_hypos, a_hypos, next_token_probs, key_to_b_hypo)
+
+ if symbols_current_t == self.step_max_tokens:
+ break
+
+ a_hypos = self._gen_a_hypos(
+ a_hypos,
+ b_hypos,
+ next_token_probs,
+ t,
+ beam_width,
+ device,
+ )
+ if a_hypos:
+ symbols_current_t += 1
+
+ _, sorted_idx = torch.tensor([self.hypo_sort_key(hyp) for hyp in b_hypos]).topk(beam_width)
+ b_hypos = [b_hypos[idx] for idx in sorted_idx]
+
+ return b_hypos
+
+ def forward(self, input: torch.Tensor, length: torch.Tensor, beam_width: int) -> List[Hypothesis]:
+ r"""Performs beam search for the given input sequence.
+
+ T: number of frames;
+ D: feature dimension of each frame.
+
+ Args:
+ input (torch.Tensor): sequence of input frames, with shape (T, D) or (1, T, D).
+ length (torch.Tensor): number of valid frames in input
+ sequence, with shape () or (1,).
+ beam_width (int): beam size to use during search.
+
+ Returns:
+ List[Hypothesis]: top-``beam_width`` hypotheses found by beam search.
+ """
+ if input.dim() != 2 and not (input.dim() == 3 and input.shape[0] == 1):
+ raise ValueError("input must be of shape (T, D) or (1, T, D)")
+ if input.dim() == 2:
+ input = input.unsqueeze(0)
+
+ if length.shape != () and length.shape != (1,):
+ raise ValueError("length must be of shape () or (1,)")
+ if length.dim() == 0:
+ length = length.unsqueeze(0)
+
+ enc_out, _ = self.model.transcribe(input, length)
+ return self._search(enc_out, None, beam_width)
+
+ @torch.jit.export
+ def infer(
+ self,
+ input: torch.Tensor,
+ length: torch.Tensor,
+ beam_width: int,
+ state: Optional[List[List[torch.Tensor]]] = None,
+ hypothesis: Optional[List[Hypothesis]] = None,
+ ) -> Tuple[List[Hypothesis], List[List[torch.Tensor]]]:
+ r"""Performs beam search for the given input sequence in streaming mode.
+
+ T: number of frames;
+ D: feature dimension of each frame.
+
+ Args:
+ input (torch.Tensor): sequence of input frames, with shape (T, D) or (1, T, D).
+ length (torch.Tensor): number of valid frames in input
+ sequence, with shape () or (1,).
+ beam_width (int): beam size to use during search.
+ state (List[List[torch.Tensor]] or None, optional): list of lists of tensors
+ representing transcription network internal state generated in preceding
+ invocation. (Default: ``None``)
+ hypothesis (List[Hypothesis] or None): hypotheses from preceding invocation to seed
+ search with. (Default: ``None``)
+
+ Returns:
+ (List[Hypothesis], List[List[torch.Tensor]]):
+ List[Hypothesis]
+ top-``beam_width`` hypotheses found by beam search.
+ List[List[torch.Tensor]]
+ list of lists of tensors representing transcription network
+ internal state generated in current invocation.
+ """
+ if input.dim() != 2 and not (input.dim() == 3 and input.shape[0] == 1):
+ raise ValueError("input must be of shape (T, D) or (1, T, D)")
+ if input.dim() == 2:
+ input = input.unsqueeze(0)
+
+ if length.shape != () and length.shape != (1,):
+ raise ValueError("length must be of shape () or (1,)")
+ if length.dim() == 0:
+ length = length.unsqueeze(0)
+
+ enc_out, _, state = self.model.transcribe_streaming(input, length, state)
+ return self._search(enc_out, hypothesis, beam_width), state
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/tacotron2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/tacotron2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad4f9b21a66e69c3e0fdb8bb80e80cbcbe2ef429
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/tacotron2.py
@@ -0,0 +1,1046 @@
+# *****************************************************************************
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# * Neither the name of the NVIDIA CORPORATION nor the
+# names of its contributors may be used to endorse or promote products
+# derived from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# *****************************************************************************
+
+import warnings
+from typing import List, Optional, Tuple, Union
+
+import torch
+from torch import nn, Tensor
+from torch.nn import functional as F
+
+
+__all__ = [
+ "Tacotron2",
+]
+
+
+def _get_linear_layer(in_dim: int, out_dim: int, bias: bool = True, w_init_gain: str = "linear") -> torch.nn.Linear:
+ r"""Linear layer with xavier uniform initialization.
+
+ Args:
+ in_dim (int): Size of each input sample.
+ out_dim (int): Size of each output sample.
+ bias (bool, optional): If set to ``False``, the layer will not learn an additive bias. (Default: ``True``)
+ w_init_gain (str, optional): Parameter passed to ``torch.nn.init.calculate_gain``
+ for setting the gain parameter of ``xavier_uniform_``. (Default: ``linear``)
+
+ Returns:
+ (torch.nn.Linear): The corresponding linear layer.
+ """
+ linear = torch.nn.Linear(in_dim, out_dim, bias=bias)
+ torch.nn.init.xavier_uniform_(linear.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
+ return linear
+
+
+def _get_conv1d_layer(
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int = 1,
+ stride: int = 1,
+ padding: Optional[Union[str, int, Tuple[int]]] = None,
+ dilation: int = 1,
+ bias: bool = True,
+ w_init_gain: str = "linear",
+) -> torch.nn.Conv1d:
+ r"""1D convolution with xavier uniform initialization.
+
+ Args:
+ in_channels (int): Number of channels in the input image.
+ out_channels (int): Number of channels produced by the convolution.
+ kernel_size (int, optional): Number of channels in the input image. (Default: ``1``)
+ stride (int, optional): Number of channels in the input image. (Default: ``1``)
+ padding (str, int or tuple, optional): Padding added to both sides of the input.
+ (Default: dilation * (kernel_size - 1) / 2)
+ dilation (int, optional): Number of channels in the input image. (Default: ``1``)
+ w_init_gain (str, optional): Parameter passed to ``torch.nn.init.calculate_gain``
+ for setting the gain parameter of ``xavier_uniform_``. (Default: ``linear``)
+
+ Returns:
+ (torch.nn.Conv1d): The corresponding Conv1D layer.
+ """
+ if padding is None:
+ if kernel_size % 2 != 1:
+ raise ValueError("kernel_size must be odd")
+ padding = int(dilation * (kernel_size - 1) / 2)
+
+ conv1d = torch.nn.Conv1d(
+ in_channels,
+ out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=bias,
+ )
+
+ torch.nn.init.xavier_uniform_(conv1d.weight, gain=torch.nn.init.calculate_gain(w_init_gain))
+
+ return conv1d
+
+
+def _get_mask_from_lengths(lengths: Tensor) -> Tensor:
+ r"""Returns a binary mask based on ``lengths``. The ``i``-th row and ``j``-th column of the mask
+ is ``1`` if ``j`` is smaller than ``i``-th element of ``lengths.
+
+ Args:
+ lengths (Tensor): The length of each element in the batch, with shape (n_batch, ).
+
+ Returns:
+ mask (Tensor): The binary mask, with shape (n_batch, max of ``lengths``).
+ """
+ max_len = torch.max(lengths).item()
+ ids = torch.arange(0, max_len, device=lengths.device, dtype=lengths.dtype)
+ mask = (ids < lengths.unsqueeze(1)).byte()
+ mask = torch.le(mask, 0)
+ return mask
+
+
+class _LocationLayer(nn.Module):
+ r"""Location layer used in the Attention model.
+
+ Args:
+ attention_n_filter (int): Number of filters for attention model.
+ attention_kernel_size (int): Kernel size for attention model.
+ attention_hidden_dim (int): Dimension of attention hidden representation.
+ """
+
+ def __init__(
+ self,
+ attention_n_filter: int,
+ attention_kernel_size: int,
+ attention_hidden_dim: int,
+ ):
+ super().__init__()
+ padding = int((attention_kernel_size - 1) / 2)
+ self.location_conv = _get_conv1d_layer(
+ 2,
+ attention_n_filter,
+ kernel_size=attention_kernel_size,
+ padding=padding,
+ bias=False,
+ stride=1,
+ dilation=1,
+ )
+ self.location_dense = _get_linear_layer(
+ attention_n_filter, attention_hidden_dim, bias=False, w_init_gain="tanh"
+ )
+
+ def forward(self, attention_weights_cat: Tensor) -> Tensor:
+ r"""Location layer used in the Attention model.
+
+ Args:
+ attention_weights_cat (Tensor): Cumulative and previous attention weights
+ with shape (n_batch, 2, max of ``text_lengths``).
+
+ Returns:
+ processed_attention (Tensor): Cumulative and previous attention weights
+ with shape (n_batch, ``attention_hidden_dim``).
+ """
+ # (n_batch, attention_n_filter, text_lengths.max())
+ processed_attention = self.location_conv(attention_weights_cat)
+ processed_attention = processed_attention.transpose(1, 2)
+ # (n_batch, text_lengths.max(), attention_hidden_dim)
+ processed_attention = self.location_dense(processed_attention)
+ return processed_attention
+
+
+class _Attention(nn.Module):
+ r"""Locally sensitive attention model.
+
+ Args:
+ attention_rnn_dim (int): Number of hidden units for RNN.
+ encoder_embedding_dim (int): Number of embedding dimensions in the Encoder.
+ attention_hidden_dim (int): Dimension of attention hidden representation.
+ attention_location_n_filter (int): Number of filters for Attention model.
+ attention_location_kernel_size (int): Kernel size for Attention model.
+ """
+
+ def __init__(
+ self,
+ attention_rnn_dim: int,
+ encoder_embedding_dim: int,
+ attention_hidden_dim: int,
+ attention_location_n_filter: int,
+ attention_location_kernel_size: int,
+ ) -> None:
+ super().__init__()
+ self.query_layer = _get_linear_layer(attention_rnn_dim, attention_hidden_dim, bias=False, w_init_gain="tanh")
+ self.memory_layer = _get_linear_layer(
+ encoder_embedding_dim, attention_hidden_dim, bias=False, w_init_gain="tanh"
+ )
+ self.v = _get_linear_layer(attention_hidden_dim, 1, bias=False)
+ self.location_layer = _LocationLayer(
+ attention_location_n_filter,
+ attention_location_kernel_size,
+ attention_hidden_dim,
+ )
+ self.score_mask_value = -float("inf")
+
+ def _get_alignment_energies(self, query: Tensor, processed_memory: Tensor, attention_weights_cat: Tensor) -> Tensor:
+ r"""Get the alignment vector.
+
+ Args:
+ query (Tensor): Decoder output with shape (n_batch, n_mels * n_frames_per_step).
+ processed_memory (Tensor): Processed Encoder outputs
+ with shape (n_batch, max of ``text_lengths``, attention_hidden_dim).
+ attention_weights_cat (Tensor): Cumulative and previous attention weights
+ with shape (n_batch, 2, max of ``text_lengths``).
+
+ Returns:
+ alignment (Tensor): attention weights, it is a tensor with shape (batch, max of ``text_lengths``).
+ """
+
+ processed_query = self.query_layer(query.unsqueeze(1))
+ processed_attention_weights = self.location_layer(attention_weights_cat)
+ energies = self.v(torch.tanh(processed_query + processed_attention_weights + processed_memory))
+
+ alignment = energies.squeeze(2)
+ return alignment
+
+ def forward(
+ self,
+ attention_hidden_state: Tensor,
+ memory: Tensor,
+ processed_memory: Tensor,
+ attention_weights_cat: Tensor,
+ mask: Tensor,
+ ) -> Tuple[Tensor, Tensor]:
+ r"""Pass the input through the Attention model.
+
+ Args:
+ attention_hidden_state (Tensor): Attention rnn last output with shape (n_batch, ``attention_rnn_dim``).
+ memory (Tensor): Encoder outputs with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+ processed_memory (Tensor): Processed Encoder outputs
+ with shape (n_batch, max of ``text_lengths``, ``attention_hidden_dim``).
+ attention_weights_cat (Tensor): Previous and cumulative attention weights
+ with shape (n_batch, current_num_frames * 2, max of ``text_lengths``).
+ mask (Tensor): Binary mask for padded data with shape (n_batch, current_num_frames).
+
+ Returns:
+ attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
+ attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
+ """
+ alignment = self._get_alignment_energies(attention_hidden_state, processed_memory, attention_weights_cat)
+
+ alignment = alignment.masked_fill(mask, self.score_mask_value)
+
+ attention_weights = F.softmax(alignment, dim=1)
+ attention_context = torch.bmm(attention_weights.unsqueeze(1), memory)
+ attention_context = attention_context.squeeze(1)
+
+ return attention_context, attention_weights
+
+
+class _Prenet(nn.Module):
+ r"""Prenet Module. It is consists of ``len(output_size)`` linear layers.
+
+ Args:
+ in_dim (int): The size of each input sample.
+ output_sizes (list): The output dimension of each linear layers.
+ """
+
+ def __init__(self, in_dim: int, out_sizes: List[int]) -> None:
+ super().__init__()
+ in_sizes = [in_dim] + out_sizes[:-1]
+ self.layers = nn.ModuleList(
+ [_get_linear_layer(in_size, out_size, bias=False) for (in_size, out_size) in zip(in_sizes, out_sizes)]
+ )
+
+ def forward(self, x: Tensor) -> Tensor:
+ r"""Pass the input through Prenet.
+
+ Args:
+ x (Tensor): The input sequence to Prenet with shape (n_batch, in_dim).
+
+ Return:
+ x (Tensor): Tensor with shape (n_batch, sizes[-1])
+ """
+
+ for linear in self.layers:
+ x = F.dropout(F.relu(linear(x)), p=0.5, training=True)
+ return x
+
+
+class _Postnet(nn.Module):
+ r"""Postnet Module.
+
+ Args:
+ n_mels (int): Number of mel bins.
+ postnet_embedding_dim (int): Postnet embedding dimension.
+ postnet_kernel_size (int): Postnet kernel size.
+ postnet_n_convolution (int): Number of postnet convolutions.
+ """
+
+ def __init__(
+ self,
+ n_mels: int,
+ postnet_embedding_dim: int,
+ postnet_kernel_size: int,
+ postnet_n_convolution: int,
+ ):
+ super().__init__()
+ self.convolutions = nn.ModuleList()
+
+ for i in range(postnet_n_convolution):
+ in_channels = n_mels if i == 0 else postnet_embedding_dim
+ out_channels = n_mels if i == (postnet_n_convolution - 1) else postnet_embedding_dim
+ init_gain = "linear" if i == (postnet_n_convolution - 1) else "tanh"
+ num_features = n_mels if i == (postnet_n_convolution - 1) else postnet_embedding_dim
+ self.convolutions.append(
+ nn.Sequential(
+ _get_conv1d_layer(
+ in_channels,
+ out_channels,
+ kernel_size=postnet_kernel_size,
+ stride=1,
+ padding=int((postnet_kernel_size - 1) / 2),
+ dilation=1,
+ w_init_gain=init_gain,
+ ),
+ nn.BatchNorm1d(num_features),
+ )
+ )
+
+ self.n_convs = len(self.convolutions)
+
+ def forward(self, x: Tensor) -> Tensor:
+ r"""Pass the input through Postnet.
+
+ Args:
+ x (Tensor): The input sequence with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
+
+ Return:
+ x (Tensor): Tensor with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
+ """
+
+ for i, conv in enumerate(self.convolutions):
+ if i < self.n_convs - 1:
+ x = F.dropout(torch.tanh(conv(x)), 0.5, training=self.training)
+ else:
+ x = F.dropout(conv(x), 0.5, training=self.training)
+
+ return x
+
+
+class _Encoder(nn.Module):
+ r"""Encoder Module.
+
+ Args:
+ encoder_embedding_dim (int): Number of embedding dimensions in the encoder.
+ encoder_n_convolution (int): Number of convolution layers in the encoder.
+ encoder_kernel_size (int): The kernel size in the encoder.
+
+ Examples
+ >>> encoder = _Encoder(3, 512, 5)
+ >>> input = torch.rand(10, 20, 30)
+ >>> output = encoder(input) # shape: (10, 30, 512)
+ """
+
+ def __init__(
+ self,
+ encoder_embedding_dim: int,
+ encoder_n_convolution: int,
+ encoder_kernel_size: int,
+ ) -> None:
+ super().__init__()
+
+ self.convolutions = nn.ModuleList()
+ for _ in range(encoder_n_convolution):
+ conv_layer = nn.Sequential(
+ _get_conv1d_layer(
+ encoder_embedding_dim,
+ encoder_embedding_dim,
+ kernel_size=encoder_kernel_size,
+ stride=1,
+ padding=int((encoder_kernel_size - 1) / 2),
+ dilation=1,
+ w_init_gain="relu",
+ ),
+ nn.BatchNorm1d(encoder_embedding_dim),
+ )
+ self.convolutions.append(conv_layer)
+
+ self.lstm = nn.LSTM(
+ encoder_embedding_dim,
+ int(encoder_embedding_dim / 2),
+ 1,
+ batch_first=True,
+ bidirectional=True,
+ )
+ self.lstm.flatten_parameters()
+
+ def forward(self, x: Tensor, input_lengths: Tensor) -> Tensor:
+ r"""Pass the input through the Encoder.
+
+ Args:
+ x (Tensor): The input sequences with shape (n_batch, encoder_embedding_dim, n_seq).
+ input_lengths (Tensor): The length of each input sequence with shape (n_batch, ).
+
+ Return:
+ x (Tensor): A tensor with shape (n_batch, n_seq, encoder_embedding_dim).
+ """
+
+ for conv in self.convolutions:
+ x = F.dropout(F.relu(conv(x)), 0.5, self.training)
+
+ x = x.transpose(1, 2)
+
+ input_lengths = input_lengths.cpu()
+ x = nn.utils.rnn.pack_padded_sequence(x, input_lengths, batch_first=True)
+
+ outputs, _ = self.lstm(x)
+ outputs, _ = nn.utils.rnn.pad_packed_sequence(outputs, batch_first=True)
+
+ return outputs
+
+
+class _Decoder(nn.Module):
+ r"""Decoder with Attention model.
+
+ Args:
+ n_mels (int): number of mel bins
+ n_frames_per_step (int): number of frames processed per step, only 1 is supported
+ encoder_embedding_dim (int): the number of embedding dimensions in the encoder.
+ decoder_rnn_dim (int): number of units in decoder LSTM
+ decoder_max_step (int): maximum number of output mel spectrograms
+ decoder_dropout (float): dropout probability for decoder LSTM
+ decoder_early_stopping (bool): stop decoding when all samples are finished
+ attention_rnn_dim (int): number of units in attention LSTM
+ attention_hidden_dim (int): dimension of attention hidden representation
+ attention_location_n_filter (int): number of filters for attention model
+ attention_location_kernel_size (int): kernel size for attention model
+ attention_dropout (float): dropout probability for attention LSTM
+ prenet_dim (int): number of ReLU units in prenet layers
+ gate_threshold (float): probability threshold for stop token
+ """
+
+ def __init__(
+ self,
+ n_mels: int,
+ n_frames_per_step: int,
+ encoder_embedding_dim: int,
+ decoder_rnn_dim: int,
+ decoder_max_step: int,
+ decoder_dropout: float,
+ decoder_early_stopping: bool,
+ attention_rnn_dim: int,
+ attention_hidden_dim: int,
+ attention_location_n_filter: int,
+ attention_location_kernel_size: int,
+ attention_dropout: float,
+ prenet_dim: int,
+ gate_threshold: float,
+ ) -> None:
+
+ super().__init__()
+ self.n_mels = n_mels
+ self.n_frames_per_step = n_frames_per_step
+ self.encoder_embedding_dim = encoder_embedding_dim
+ self.attention_rnn_dim = attention_rnn_dim
+ self.decoder_rnn_dim = decoder_rnn_dim
+ self.prenet_dim = prenet_dim
+ self.decoder_max_step = decoder_max_step
+ self.gate_threshold = gate_threshold
+ self.attention_dropout = attention_dropout
+ self.decoder_dropout = decoder_dropout
+ self.decoder_early_stopping = decoder_early_stopping
+
+ self.prenet = _Prenet(n_mels * n_frames_per_step, [prenet_dim, prenet_dim])
+
+ self.attention_rnn = nn.LSTMCell(prenet_dim + encoder_embedding_dim, attention_rnn_dim)
+
+ self.attention_layer = _Attention(
+ attention_rnn_dim,
+ encoder_embedding_dim,
+ attention_hidden_dim,
+ attention_location_n_filter,
+ attention_location_kernel_size,
+ )
+
+ self.decoder_rnn = nn.LSTMCell(attention_rnn_dim + encoder_embedding_dim, decoder_rnn_dim, True)
+
+ self.linear_projection = _get_linear_layer(decoder_rnn_dim + encoder_embedding_dim, n_mels * n_frames_per_step)
+
+ self.gate_layer = _get_linear_layer(
+ decoder_rnn_dim + encoder_embedding_dim, 1, bias=True, w_init_gain="sigmoid"
+ )
+
+ def _get_initial_frame(self, memory: Tensor) -> Tensor:
+ r"""Gets all zeros frames to use as the first decoder input.
+
+ Args:
+ memory (Tensor): Encoder outputs with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+
+ Returns:
+ decoder_input (Tensor): all zeros frames with shape
+ (n_batch, max of ``text_lengths``, ``n_mels * n_frames_per_step``).
+ """
+
+ n_batch = memory.size(0)
+ dtype = memory.dtype
+ device = memory.device
+ decoder_input = torch.zeros(n_batch, self.n_mels * self.n_frames_per_step, dtype=dtype, device=device)
+ return decoder_input
+
+ def _initialize_decoder_states(
+ self, memory: Tensor
+ ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
+ r"""Initializes attention rnn states, decoder rnn states, attention
+ weights, attention cumulative weights, attention context, stores memory
+ and stores processed memory.
+
+ Args:
+ memory (Tensor): Encoder outputs with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+
+ Returns:
+ attention_hidden (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
+ attention_cell (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
+ decoder_hidden (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
+ decoder_cell (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
+ attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
+ attention_weights_cum (Tensor): Cumulated attention weights with shape (n_batch, max of ``text_lengths``).
+ attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
+ processed_memory (Tensor): Processed encoder outputs
+ with shape (n_batch, max of ``text_lengths``, ``attention_hidden_dim``).
+ """
+ n_batch = memory.size(0)
+ max_time = memory.size(1)
+ dtype = memory.dtype
+ device = memory.device
+
+ attention_hidden = torch.zeros(n_batch, self.attention_rnn_dim, dtype=dtype, device=device)
+ attention_cell = torch.zeros(n_batch, self.attention_rnn_dim, dtype=dtype, device=device)
+
+ decoder_hidden = torch.zeros(n_batch, self.decoder_rnn_dim, dtype=dtype, device=device)
+ decoder_cell = torch.zeros(n_batch, self.decoder_rnn_dim, dtype=dtype, device=device)
+
+ attention_weights = torch.zeros(n_batch, max_time, dtype=dtype, device=device)
+ attention_weights_cum = torch.zeros(n_batch, max_time, dtype=dtype, device=device)
+ attention_context = torch.zeros(n_batch, self.encoder_embedding_dim, dtype=dtype, device=device)
+
+ processed_memory = self.attention_layer.memory_layer(memory)
+
+ return (
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ processed_memory,
+ )
+
+ def _parse_decoder_inputs(self, decoder_inputs: Tensor) -> Tensor:
+ r"""Prepares decoder inputs.
+
+ Args:
+ decoder_inputs (Tensor): Inputs used for teacher-forced training, i.e. mel-specs,
+ with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``)
+
+ Returns:
+ inputs (Tensor): Processed decoder inputs with shape (max of ``mel_specgram_lengths``, n_batch, ``n_mels``).
+ """
+ # (n_batch, n_mels, mel_specgram_lengths.max()) -> (n_batch, mel_specgram_lengths.max(), n_mels)
+ decoder_inputs = decoder_inputs.transpose(1, 2)
+ decoder_inputs = decoder_inputs.view(
+ decoder_inputs.size(0),
+ int(decoder_inputs.size(1) / self.n_frames_per_step),
+ -1,
+ )
+ # (n_batch, mel_specgram_lengths.max(), n_mels) -> (mel_specgram_lengths.max(), n_batch, n_mels)
+ decoder_inputs = decoder_inputs.transpose(0, 1)
+ return decoder_inputs
+
+ def _parse_decoder_outputs(
+ self, mel_specgram: Tensor, gate_outputs: Tensor, alignments: Tensor
+ ) -> Tuple[Tensor, Tensor, Tensor]:
+ r"""Prepares decoder outputs for output
+
+ Args:
+ mel_specgram (Tensor): mel spectrogram with shape (max of ``mel_specgram_lengths``, n_batch, ``n_mels``)
+ gate_outputs (Tensor): predicted stop token with shape (max of ``mel_specgram_lengths``, n_batch)
+ alignments (Tensor): sequence of attention weights from the decoder
+ with shape (max of ``mel_specgram_lengths``, n_batch, max of ``text_lengths``)
+
+ Returns:
+ mel_specgram (Tensor): mel spectrogram with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``)
+ gate_outputs (Tensor): predicted stop token with shape (n_batch, max of ``mel_specgram_lengths``)
+ alignments (Tensor): sequence of attention weights from the decoder
+ with shape (n_batch, max of ``mel_specgram_lengths``, max of ``text_lengths``)
+ """
+ # (mel_specgram_lengths.max(), n_batch, text_lengths.max())
+ # -> (n_batch, mel_specgram_lengths.max(), text_lengths.max())
+ alignments = alignments.transpose(0, 1).contiguous()
+ # (mel_specgram_lengths.max(), n_batch) -> (n_batch, mel_specgram_lengths.max())
+ gate_outputs = gate_outputs.transpose(0, 1).contiguous()
+ # (mel_specgram_lengths.max(), n_batch, n_mels) -> (n_batch, mel_specgram_lengths.max(), n_mels)
+ mel_specgram = mel_specgram.transpose(0, 1).contiguous()
+ # decouple frames per step
+ shape = (mel_specgram.shape[0], -1, self.n_mels)
+ mel_specgram = mel_specgram.view(*shape)
+ # (n_batch, mel_specgram_lengths.max(), n_mels) -> (n_batch, n_mels, T_out)
+ mel_specgram = mel_specgram.transpose(1, 2)
+
+ return mel_specgram, gate_outputs, alignments
+
+ def decode(
+ self,
+ decoder_input: Tensor,
+ attention_hidden: Tensor,
+ attention_cell: Tensor,
+ decoder_hidden: Tensor,
+ decoder_cell: Tensor,
+ attention_weights: Tensor,
+ attention_weights_cum: Tensor,
+ attention_context: Tensor,
+ memory: Tensor,
+ processed_memory: Tensor,
+ mask: Tensor,
+ ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
+ r"""Decoder step using stored states, attention and memory
+
+ Args:
+ decoder_input (Tensor): Output of the Prenet with shape (n_batch, ``prenet_dim``).
+ attention_hidden (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
+ attention_cell (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
+ decoder_hidden (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
+ decoder_cell (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
+ attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
+ attention_weights_cum (Tensor): Cumulated attention weights with shape (n_batch, max of ``text_lengths``).
+ attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
+ memory (Tensor): Encoder output with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+ processed_memory (Tensor): Processed Encoder outputs
+ with shape (n_batch, max of ``text_lengths``, ``attention_hidden_dim``).
+ mask (Tensor): Binary mask for padded data with shape (n_batch, current_num_frames).
+
+ Returns:
+ decoder_output: Predicted mel spectrogram for the current frame with shape (n_batch, ``n_mels``).
+ gate_prediction (Tensor): Prediction of the stop token with shape (n_batch, ``1``).
+ attention_hidden (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
+ attention_cell (Tensor): Hidden state of the attention LSTM with shape (n_batch, ``attention_rnn_dim``).
+ decoder_hidden (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
+ decoder_cell (Tensor): Hidden state of the decoder LSTM with shape (n_batch, ``decoder_rnn_dim``).
+ attention_weights (Tensor): Attention weights with shape (n_batch, max of ``text_lengths``).
+ attention_weights_cum (Tensor): Cumulated attention weights with shape (n_batch, max of ``text_lengths``).
+ attention_context (Tensor): Context vector with shape (n_batch, ``encoder_embedding_dim``).
+ """
+ cell_input = torch.cat((decoder_input, attention_context), -1)
+
+ attention_hidden, attention_cell = self.attention_rnn(cell_input, (attention_hidden, attention_cell))
+ attention_hidden = F.dropout(attention_hidden, self.attention_dropout, self.training)
+
+ attention_weights_cat = torch.cat((attention_weights.unsqueeze(1), attention_weights_cum.unsqueeze(1)), dim=1)
+ attention_context, attention_weights = self.attention_layer(
+ attention_hidden, memory, processed_memory, attention_weights_cat, mask
+ )
+
+ attention_weights_cum += attention_weights
+ decoder_input = torch.cat((attention_hidden, attention_context), -1)
+
+ decoder_hidden, decoder_cell = self.decoder_rnn(decoder_input, (decoder_hidden, decoder_cell))
+ decoder_hidden = F.dropout(decoder_hidden, self.decoder_dropout, self.training)
+
+ decoder_hidden_attention_context = torch.cat((decoder_hidden, attention_context), dim=1)
+ decoder_output = self.linear_projection(decoder_hidden_attention_context)
+
+ gate_prediction = self.gate_layer(decoder_hidden_attention_context)
+
+ return (
+ decoder_output,
+ gate_prediction,
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ )
+
+ def forward(
+ self, memory: Tensor, mel_specgram_truth: Tensor, memory_lengths: Tensor
+ ) -> Tuple[Tensor, Tensor, Tensor]:
+ r"""Decoder forward pass for training.
+
+ Args:
+ memory (Tensor): Encoder outputs
+ with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+ mel_specgram_truth (Tensor): Decoder ground-truth mel-specs for teacher forcing
+ with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
+ memory_lengths (Tensor): Encoder output lengths for attention masking
+ (the same as ``text_lengths``) with shape (n_batch, ).
+
+ Returns:
+ mel_specgram (Tensor): Predicted mel spectrogram
+ with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
+ gate_outputs (Tensor): Predicted stop token for each timestep
+ with shape (n_batch, max of ``mel_specgram_lengths``).
+ alignments (Tensor): Sequence of attention weights from the decoder
+ with shape (n_batch, max of ``mel_specgram_lengths``, max of ``text_lengths``).
+ """
+
+ decoder_input = self._get_initial_frame(memory).unsqueeze(0)
+ decoder_inputs = self._parse_decoder_inputs(mel_specgram_truth)
+ decoder_inputs = torch.cat((decoder_input, decoder_inputs), dim=0)
+ decoder_inputs = self.prenet(decoder_inputs)
+
+ mask = _get_mask_from_lengths(memory_lengths)
+ (
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ processed_memory,
+ ) = self._initialize_decoder_states(memory)
+
+ mel_outputs, gate_outputs, alignments = [], [], []
+ while len(mel_outputs) < decoder_inputs.size(0) - 1:
+ decoder_input = decoder_inputs[len(mel_outputs)]
+ (
+ mel_output,
+ gate_output,
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ ) = self.decode(
+ decoder_input,
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ memory,
+ processed_memory,
+ mask,
+ )
+
+ mel_outputs += [mel_output.squeeze(1)]
+ gate_outputs += [gate_output.squeeze(1)]
+ alignments += [attention_weights]
+
+ mel_specgram, gate_outputs, alignments = self._parse_decoder_outputs(
+ torch.stack(mel_outputs), torch.stack(gate_outputs), torch.stack(alignments)
+ )
+
+ return mel_specgram, gate_outputs, alignments
+
+ def _get_go_frame(self, memory: Tensor) -> Tensor:
+ """Gets all zeros frames to use as the first decoder input
+
+ args:
+ memory (Tensor): Encoder outputs
+ with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+
+ returns:
+ decoder_input (Tensor): All zeros frames with shape(n_batch, ``n_mels`` * ``n_frame_per_step``).
+ """
+
+ n_batch = memory.size(0)
+ dtype = memory.dtype
+ device = memory.device
+ decoder_input = torch.zeros(n_batch, self.n_mels * self.n_frames_per_step, dtype=dtype, device=device)
+ return decoder_input
+
+ @torch.jit.export
+ def infer(self, memory: Tensor, memory_lengths: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+ """Decoder inference
+
+ Args:
+ memory (Tensor): Encoder outputs
+ with shape (n_batch, max of ``text_lengths``, ``encoder_embedding_dim``).
+ memory_lengths (Tensor): Encoder output lengths for attention masking
+ (the same as ``text_lengths``) with shape (n_batch, ).
+
+ Returns:
+ mel_specgram (Tensor): Predicted mel spectrogram
+ with shape (n_batch, ``n_mels``, max of ``mel_specgram_lengths``).
+ mel_specgram_lengths (Tensor): the length of the predicted mel spectrogram (n_batch, ))
+ gate_outputs (Tensor): Predicted stop token for each timestep
+ with shape (n_batch, max of ``mel_specgram_lengths``).
+ alignments (Tensor): Sequence of attention weights from the decoder
+ with shape (n_batch, max of ``mel_specgram_lengths``, max of ``text_lengths``).
+ """
+ batch_size, device = memory.size(0), memory.device
+
+ decoder_input = self._get_go_frame(memory)
+
+ mask = _get_mask_from_lengths(memory_lengths)
+ (
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ processed_memory,
+ ) = self._initialize_decoder_states(memory)
+
+ mel_specgram_lengths = torch.zeros([batch_size], dtype=torch.int32, device=device)
+ finished = torch.zeros([batch_size], dtype=torch.bool, device=device)
+ mel_specgrams: List[Tensor] = []
+ gate_outputs: List[Tensor] = []
+ alignments: List[Tensor] = []
+ for _ in range(self.decoder_max_step):
+ decoder_input = self.prenet(decoder_input)
+ (
+ mel_specgram,
+ gate_output,
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ ) = self.decode(
+ decoder_input,
+ attention_hidden,
+ attention_cell,
+ decoder_hidden,
+ decoder_cell,
+ attention_weights,
+ attention_weights_cum,
+ attention_context,
+ memory,
+ processed_memory,
+ mask,
+ )
+
+ mel_specgrams.append(mel_specgram.unsqueeze(0))
+ gate_outputs.append(gate_output.transpose(0, 1))
+ alignments.append(attention_weights)
+ mel_specgram_lengths[~finished] += 1
+
+ finished |= torch.sigmoid(gate_output.squeeze(1)) > self.gate_threshold
+ if self.decoder_early_stopping and torch.all(finished):
+ break
+
+ decoder_input = mel_specgram
+
+ if len(mel_specgrams) == self.decoder_max_step:
+ warnings.warn(
+ "Reached max decoder steps. The generated spectrogram might not cover " "the whole transcript."
+ )
+
+ mel_specgrams = torch.cat(mel_specgrams, dim=0)
+ gate_outputs = torch.cat(gate_outputs, dim=0)
+ alignments = torch.cat(alignments, dim=0)
+
+ mel_specgrams, gate_outputs, alignments = self._parse_decoder_outputs(mel_specgrams, gate_outputs, alignments)
+
+ return mel_specgrams, mel_specgram_lengths, gate_outputs, alignments
+
+
+class Tacotron2(nn.Module):
+ r"""Tacotron2 model from *Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions*
+ :cite:`shen2018natural` based on the implementation from
+ `Nvidia Deep Learning Examples `_.
+
+ See Also:
+ * :class:`torchaudio.pipelines.Tacotron2TTSBundle`: TTS pipeline with pretrained model.
+
+ Args:
+ mask_padding (bool, optional): Use mask padding (Default: ``False``).
+ n_mels (int, optional): Number of mel bins (Default: ``80``).
+ n_symbol (int, optional): Number of symbols for the input text (Default: ``148``).
+ n_frames_per_step (int, optional): Number of frames processed per step, only 1 is supported (Default: ``1``).
+ symbol_embedding_dim (int, optional): Input embedding dimension (Default: ``512``).
+ encoder_n_convolution (int, optional): Number of encoder convolutions (Default: ``3``).
+ encoder_kernel_size (int, optional): Encoder kernel size (Default: ``5``).
+ encoder_embedding_dim (int, optional): Encoder embedding dimension (Default: ``512``).
+ decoder_rnn_dim (int, optional): Number of units in decoder LSTM (Default: ``1024``).
+ decoder_max_step (int, optional): Maximum number of output mel spectrograms (Default: ``2000``).
+ decoder_dropout (float, optional): Dropout probability for decoder LSTM (Default: ``0.1``).
+ decoder_early_stopping (bool, optional): Continue decoding after all samples are finished (Default: ``True``).
+ attention_rnn_dim (int, optional): Number of units in attention LSTM (Default: ``1024``).
+ attention_hidden_dim (int, optional): Dimension of attention hidden representation (Default: ``128``).
+ attention_location_n_filter (int, optional): Number of filters for attention model (Default: ``32``).
+ attention_location_kernel_size (int, optional): Kernel size for attention model (Default: ``31``).
+ attention_dropout (float, optional): Dropout probability for attention LSTM (Default: ``0.1``).
+ prenet_dim (int, optional): Number of ReLU units in prenet layers (Default: ``256``).
+ postnet_n_convolution (int, optional): Number of postnet convolutions (Default: ``5``).
+ postnet_kernel_size (int, optional): Postnet kernel size (Default: ``5``).
+ postnet_embedding_dim (int, optional): Postnet embedding dimension (Default: ``512``).
+ gate_threshold (float, optional): Probability threshold for stop token (Default: ``0.5``).
+ """
+
+ def __init__(
+ self,
+ mask_padding: bool = False,
+ n_mels: int = 80,
+ n_symbol: int = 148,
+ n_frames_per_step: int = 1,
+ symbol_embedding_dim: int = 512,
+ encoder_embedding_dim: int = 512,
+ encoder_n_convolution: int = 3,
+ encoder_kernel_size: int = 5,
+ decoder_rnn_dim: int = 1024,
+ decoder_max_step: int = 2000,
+ decoder_dropout: float = 0.1,
+ decoder_early_stopping: bool = True,
+ attention_rnn_dim: int = 1024,
+ attention_hidden_dim: int = 128,
+ attention_location_n_filter: int = 32,
+ attention_location_kernel_size: int = 31,
+ attention_dropout: float = 0.1,
+ prenet_dim: int = 256,
+ postnet_n_convolution: int = 5,
+ postnet_kernel_size: int = 5,
+ postnet_embedding_dim: int = 512,
+ gate_threshold: float = 0.5,
+ ) -> None:
+ super().__init__()
+
+ self.mask_padding = mask_padding
+ self.n_mels = n_mels
+ self.n_frames_per_step = n_frames_per_step
+ self.embedding = nn.Embedding(n_symbol, symbol_embedding_dim)
+ torch.nn.init.xavier_uniform_(self.embedding.weight)
+ self.encoder = _Encoder(encoder_embedding_dim, encoder_n_convolution, encoder_kernel_size)
+ self.decoder = _Decoder(
+ n_mels,
+ n_frames_per_step,
+ encoder_embedding_dim,
+ decoder_rnn_dim,
+ decoder_max_step,
+ decoder_dropout,
+ decoder_early_stopping,
+ attention_rnn_dim,
+ attention_hidden_dim,
+ attention_location_n_filter,
+ attention_location_kernel_size,
+ attention_dropout,
+ prenet_dim,
+ gate_threshold,
+ )
+ self.postnet = _Postnet(n_mels, postnet_embedding_dim, postnet_kernel_size, postnet_n_convolution)
+
+ def forward(
+ self,
+ tokens: Tensor,
+ token_lengths: Tensor,
+ mel_specgram: Tensor,
+ mel_specgram_lengths: Tensor,
+ ) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+ r"""Pass the input through the Tacotron2 model. This is in teacher
+ forcing mode, which is generally used for training.
+
+ The input ``tokens`` should be padded with zeros to length max of ``token_lengths``.
+ The input ``mel_specgram`` should be padded with zeros to length max of ``mel_specgram_lengths``.
+
+ Args:
+ tokens (Tensor): The input tokens to Tacotron2 with shape `(n_batch, max of token_lengths)`.
+ token_lengths (Tensor): The valid length of each sample in ``tokens`` with shape `(n_batch, )`.
+ mel_specgram (Tensor): The target mel spectrogram
+ with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
+ mel_specgram_lengths (Tensor): The length of each mel spectrogram with shape `(n_batch, )`.
+
+ Returns:
+ [Tensor, Tensor, Tensor, Tensor]:
+ Tensor
+ Mel spectrogram before Postnet with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
+ Tensor
+ Mel spectrogram after Postnet with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
+ Tensor
+ The output for stop token at each time step with shape `(n_batch, max of mel_specgram_lengths)`.
+ Tensor
+ Sequence of attention weights from the decoder with
+ shape `(n_batch, max of mel_specgram_lengths, max of token_lengths)`.
+ """
+
+ embedded_inputs = self.embedding(tokens).transpose(1, 2)
+
+ encoder_outputs = self.encoder(embedded_inputs, token_lengths)
+ mel_specgram, gate_outputs, alignments = self.decoder(
+ encoder_outputs, mel_specgram, memory_lengths=token_lengths
+ )
+
+ mel_specgram_postnet = self.postnet(mel_specgram)
+ mel_specgram_postnet = mel_specgram + mel_specgram_postnet
+
+ if self.mask_padding:
+ mask = _get_mask_from_lengths(mel_specgram_lengths)
+ mask = mask.expand(self.n_mels, mask.size(0), mask.size(1))
+ mask = mask.permute(1, 0, 2)
+
+ mel_specgram.masked_fill_(mask, 0.0)
+ mel_specgram_postnet.masked_fill_(mask, 0.0)
+ gate_outputs.masked_fill_(mask[:, 0, :], 1e3)
+
+ return mel_specgram, mel_specgram_postnet, gate_outputs, alignments
+
+ @torch.jit.export
+ def infer(self, tokens: Tensor, lengths: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:
+ r"""Using Tacotron2 for inference. The input is a batch of encoded
+ sentences (``tokens``) and its corresponding lengths (``lengths``). The
+ output is the generated mel spectrograms, its corresponding lengths, and
+ the attention weights from the decoder.
+
+ The input `tokens` should be padded with zeros to length max of ``lengths``.
+
+ Args:
+ tokens (Tensor): The input tokens to Tacotron2 with shape `(n_batch, max of lengths)`.
+ lengths (Tensor or None, optional):
+ The valid length of each sample in ``tokens`` with shape `(n_batch, )`.
+ If ``None``, it is assumed that the all the tokens are valid. Default: ``None``
+
+ Returns:
+ (Tensor, Tensor, Tensor):
+ Tensor
+ The predicted mel spectrogram with shape `(n_batch, n_mels, max of mel_specgram_lengths)`.
+ Tensor
+ The length of the predicted mel spectrogram with shape `(n_batch, )`.
+ Tensor
+ Sequence of attention weights from the decoder with shape
+ `(n_batch, max of mel_specgram_lengths, max of lengths)`.
+ """
+ n_batch, max_length = tokens.shape
+ if lengths is None:
+ lengths = torch.tensor([max_length]).expand(n_batch).to(tokens.device, tokens.dtype)
+
+ assert lengths is not None # For TorchScript compiler
+ embedded_inputs = self.embedding(tokens).transpose(1, 2)
+ encoder_outputs = self.encoder(embedded_inputs, lengths)
+ mel_specgram, mel_specgram_lengths, _, alignments = self.decoder.infer(encoder_outputs, lengths)
+
+ mel_outputs_postnet = self.postnet(mel_specgram)
+ mel_outputs_postnet = mel_specgram + mel_outputs_postnet
+
+ alignments = alignments.unfold(1, n_batch, n_batch).transpose(0, 2)
+
+ return mel_outputs_postnet, mel_specgram_lengths, alignments
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/wav2letter.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/wav2letter.py
new file mode 100644
index 0000000000000000000000000000000000000000..defe7902fbe3c20aeb9fdaa5b5f32840691f6c66
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/wav2letter.py
@@ -0,0 +1,72 @@
+from torch import nn, Tensor
+
+__all__ = [
+ "Wav2Letter",
+]
+
+
+class Wav2Letter(nn.Module):
+ r"""Wav2Letter model architecture from *Wav2Letter: an End-to-End ConvNet-based Speech
+ Recognition System* :cite:`collobert2016wav2letter`.
+
+ See Also:
+ * `Training example `__
+
+ Args:
+ num_classes (int, optional): Number of classes to be classified. (Default: ``40``)
+ input_type (str, optional): Wav2Letter can use as input: ``waveform``, ``power_spectrum``
+ or ``mfcc`` (Default: ``waveform``).
+ num_features (int, optional): Number of input features that the network will receive (Default: ``1``).
+ """
+
+ def __init__(self, num_classes: int = 40, input_type: str = "waveform", num_features: int = 1) -> None:
+ super().__init__()
+
+ acoustic_num_features = 250 if input_type == "waveform" else num_features
+ acoustic_model = nn.Sequential(
+ nn.Conv1d(in_channels=acoustic_num_features, out_channels=250, kernel_size=48, stride=2, padding=23),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=250, kernel_size=7, stride=1, padding=3),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=250, out_channels=2000, kernel_size=32, stride=1, padding=16),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=2000, out_channels=2000, kernel_size=1, stride=1, padding=0),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=2000, out_channels=num_classes, kernel_size=1, stride=1, padding=0),
+ nn.ReLU(inplace=True),
+ )
+
+ if input_type == "waveform":
+ waveform_model = nn.Sequential(
+ nn.Conv1d(in_channels=num_features, out_channels=250, kernel_size=250, stride=160, padding=45),
+ nn.ReLU(inplace=True),
+ )
+ self.acoustic_model = nn.Sequential(waveform_model, acoustic_model)
+
+ if input_type in ["power_spectrum", "mfcc"]:
+ self.acoustic_model = acoustic_model
+
+ def forward(self, x: Tensor) -> Tensor:
+ r"""
+ Args:
+ x (torch.Tensor): Tensor of dimension (batch_size, num_features, input_length).
+
+ Returns:
+ Tensor: Predictor tensor of dimension (batch_size, number_of_classes, input_length).
+ """
+
+ x = self.acoustic_model(x)
+ x = nn.functional.log_softmax(x, dim=1)
+ return x
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/wavernn.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/wavernn.py
new file mode 100644
index 0000000000000000000000000000000000000000..90bc2fca7240235e2a8e67ba454ba29a4a9e667b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/models/wavernn.py
@@ -0,0 +1,409 @@
+import math
+from typing import List, Optional, Tuple
+
+import torch
+import torch.nn.functional as F
+from torch import nn, Tensor
+
+__all__ = [
+ "ResBlock",
+ "MelResNet",
+ "Stretch2d",
+ "UpsampleNetwork",
+ "WaveRNN",
+]
+
+
+class ResBlock(nn.Module):
+ r"""ResNet block based on *Efficient Neural Audio Synthesis* :cite:`kalchbrenner2018efficient`.
+
+ Args:
+ n_freq: the number of bins in a spectrogram. (Default: ``128``)
+
+ Examples
+ >>> resblock = ResBlock()
+ >>> input = torch.rand(10, 128, 512) # a random spectrogram
+ >>> output = resblock(input) # shape: (10, 128, 512)
+ """
+
+ def __init__(self, n_freq: int = 128) -> None:
+ super().__init__()
+
+ self.resblock_model = nn.Sequential(
+ nn.Conv1d(in_channels=n_freq, out_channels=n_freq, kernel_size=1, bias=False),
+ nn.BatchNorm1d(n_freq),
+ nn.ReLU(inplace=True),
+ nn.Conv1d(in_channels=n_freq, out_channels=n_freq, kernel_size=1, bias=False),
+ nn.BatchNorm1d(n_freq),
+ )
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""Pass the input through the ResBlock layer.
+ Args:
+ specgram (Tensor): the input sequence to the ResBlock layer (n_batch, n_freq, n_time).
+
+ Return:
+ Tensor shape: (n_batch, n_freq, n_time)
+ """
+
+ return self.resblock_model(specgram) + specgram
+
+
+class MelResNet(nn.Module):
+ r"""MelResNet layer uses a stack of ResBlocks on spectrogram.
+
+ Args:
+ n_res_block: the number of ResBlock in stack. (Default: ``10``)
+ n_freq: the number of bins in a spectrogram. (Default: ``128``)
+ n_hidden: the number of hidden dimensions of resblock. (Default: ``128``)
+ n_output: the number of output dimensions of melresnet. (Default: ``128``)
+ kernel_size: the number of kernel size in the first Conv1d layer. (Default: ``5``)
+
+ Examples
+ >>> melresnet = MelResNet()
+ >>> input = torch.rand(10, 128, 512) # a random spectrogram
+ >>> output = melresnet(input) # shape: (10, 128, 508)
+ """
+
+ def __init__(
+ self, n_res_block: int = 10, n_freq: int = 128, n_hidden: int = 128, n_output: int = 128, kernel_size: int = 5
+ ) -> None:
+ super().__init__()
+
+ ResBlocks = [ResBlock(n_hidden) for _ in range(n_res_block)]
+
+ self.melresnet_model = nn.Sequential(
+ nn.Conv1d(in_channels=n_freq, out_channels=n_hidden, kernel_size=kernel_size, bias=False),
+ nn.BatchNorm1d(n_hidden),
+ nn.ReLU(inplace=True),
+ *ResBlocks,
+ nn.Conv1d(in_channels=n_hidden, out_channels=n_output, kernel_size=1),
+ )
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""Pass the input through the MelResNet layer.
+ Args:
+ specgram (Tensor): the input sequence to the MelResNet layer (n_batch, n_freq, n_time).
+
+ Return:
+ Tensor shape: (n_batch, n_output, n_time - kernel_size + 1)
+ """
+
+ return self.melresnet_model(specgram)
+
+
+class Stretch2d(nn.Module):
+ r"""Upscale the frequency and time dimensions of a spectrogram.
+
+ Args:
+ time_scale: the scale factor in time dimension
+ freq_scale: the scale factor in frequency dimension
+
+ Examples
+ >>> stretch2d = Stretch2d(time_scale=10, freq_scale=5)
+
+ >>> input = torch.rand(10, 100, 512) # a random spectrogram
+ >>> output = stretch2d(input) # shape: (10, 500, 5120)
+ """
+
+ def __init__(self, time_scale: int, freq_scale: int) -> None:
+ super().__init__()
+
+ self.freq_scale = freq_scale
+ self.time_scale = time_scale
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""Pass the input through the Stretch2d layer.
+
+ Args:
+ specgram (Tensor): the input sequence to the Stretch2d layer (..., n_freq, n_time).
+
+ Return:
+ Tensor shape: (..., n_freq * freq_scale, n_time * time_scale)
+ """
+
+ return specgram.repeat_interleave(self.freq_scale, -2).repeat_interleave(self.time_scale, -1)
+
+
+class UpsampleNetwork(nn.Module):
+ r"""Upscale the dimensions of a spectrogram.
+
+ Args:
+ upsample_scales: the list of upsample scales.
+ n_res_block: the number of ResBlock in stack. (Default: ``10``)
+ n_freq: the number of bins in a spectrogram. (Default: ``128``)
+ n_hidden: the number of hidden dimensions of resblock. (Default: ``128``)
+ n_output: the number of output dimensions of melresnet. (Default: ``128``)
+ kernel_size: the number of kernel size in the first Conv1d layer. (Default: ``5``)
+
+ Examples
+ >>> upsamplenetwork = UpsampleNetwork(upsample_scales=[4, 4, 16])
+ >>> input = torch.rand(10, 128, 10) # a random spectrogram
+ >>> output = upsamplenetwork(input) # shape: (10, 128, 1536), (10, 128, 1536)
+ """
+
+ def __init__(
+ self,
+ upsample_scales: List[int],
+ n_res_block: int = 10,
+ n_freq: int = 128,
+ n_hidden: int = 128,
+ n_output: int = 128,
+ kernel_size: int = 5,
+ ) -> None:
+ super().__init__()
+
+ total_scale = 1
+ for upsample_scale in upsample_scales:
+ total_scale *= upsample_scale
+ self.total_scale: int = total_scale
+
+ self.indent = (kernel_size - 1) // 2 * total_scale
+ self.resnet = MelResNet(n_res_block, n_freq, n_hidden, n_output, kernel_size)
+ self.resnet_stretch = Stretch2d(total_scale, 1)
+
+ up_layers = []
+ for scale in upsample_scales:
+ stretch = Stretch2d(scale, 1)
+ conv = nn.Conv2d(
+ in_channels=1, out_channels=1, kernel_size=(1, scale * 2 + 1), padding=(0, scale), bias=False
+ )
+ torch.nn.init.constant_(conv.weight, 1.0 / (scale * 2 + 1))
+ up_layers.append(stretch)
+ up_layers.append(conv)
+ self.upsample_layers = nn.Sequential(*up_layers)
+
+ def forward(self, specgram: Tensor) -> Tuple[Tensor, Tensor]:
+ r"""Pass the input through the UpsampleNetwork layer.
+
+ Args:
+ specgram (Tensor): the input sequence to the UpsampleNetwork layer (n_batch, n_freq, n_time)
+
+ Return:
+ Tensor shape: (n_batch, n_freq, (n_time - kernel_size + 1) * total_scale),
+ (n_batch, n_output, (n_time - kernel_size + 1) * total_scale)
+ where total_scale is the product of all elements in upsample_scales.
+ """
+
+ resnet_output = self.resnet(specgram).unsqueeze(1)
+ resnet_output = self.resnet_stretch(resnet_output)
+ resnet_output = resnet_output.squeeze(1)
+
+ specgram = specgram.unsqueeze(1)
+ upsampling_output = self.upsample_layers(specgram)
+ upsampling_output = upsampling_output.squeeze(1)[:, :, self.indent : -self.indent]
+
+ return upsampling_output, resnet_output
+
+
+class WaveRNN(nn.Module):
+ r"""WaveRNN model from *Efficient Neural Audio Synthesis* :cite:`wavernn`
+ based on the implementation from `fatchord/WaveRNN `_.
+
+ The original implementation was introduced in *Efficient Neural Audio Synthesis*
+ :cite:`kalchbrenner2018efficient`. The input channels of waveform and spectrogram have to be 1.
+ The product of `upsample_scales` must equal `hop_length`.
+
+ See Also:
+ * `Training example `__
+ * :class:`torchaudio.pipelines.Tacotron2TTSBundle`: TTS pipeline with pretrained model.
+
+ Args:
+ upsample_scales: the list of upsample scales.
+ n_classes: the number of output classes.
+ hop_length: the number of samples between the starts of consecutive frames.
+ n_res_block: the number of ResBlock in stack. (Default: ``10``)
+ n_rnn: the dimension of RNN layer. (Default: ``512``)
+ n_fc: the dimension of fully connected layer. (Default: ``512``)
+ kernel_size: the number of kernel size in the first Conv1d layer. (Default: ``5``)
+ n_freq: the number of bins in a spectrogram. (Default: ``128``)
+ n_hidden: the number of hidden dimensions of resblock. (Default: ``128``)
+ n_output: the number of output dimensions of melresnet. (Default: ``128``)
+
+ Example
+ >>> wavernn = WaveRNN(upsample_scales=[5,5,8], n_classes=512, hop_length=200)
+ >>> waveform, sample_rate = torchaudio.load(file)
+ >>> # waveform shape: (n_batch, n_channel, (n_time - kernel_size + 1) * hop_length)
+ >>> specgram = MelSpectrogram(sample_rate)(waveform) # shape: (n_batch, n_channel, n_freq, n_time)
+ >>> output = wavernn(waveform, specgram)
+ >>> # output shape: (n_batch, n_channel, (n_time - kernel_size + 1) * hop_length, n_classes)
+ """
+
+ def __init__(
+ self,
+ upsample_scales: List[int],
+ n_classes: int,
+ hop_length: int,
+ n_res_block: int = 10,
+ n_rnn: int = 512,
+ n_fc: int = 512,
+ kernel_size: int = 5,
+ n_freq: int = 128,
+ n_hidden: int = 128,
+ n_output: int = 128,
+ ) -> None:
+ super().__init__()
+
+ self.kernel_size = kernel_size
+ self._pad = (kernel_size - 1 if kernel_size % 2 else kernel_size) // 2
+ self.n_rnn = n_rnn
+ self.n_aux = n_output // 4
+ self.hop_length = hop_length
+ self.n_classes = n_classes
+ self.n_bits: int = int(math.log2(self.n_classes))
+
+ total_scale = 1
+ for upsample_scale in upsample_scales:
+ total_scale *= upsample_scale
+ if total_scale != self.hop_length:
+ raise ValueError(f"Expected: total_scale == hop_length, but found {total_scale} != {hop_length}")
+
+ self.upsample = UpsampleNetwork(upsample_scales, n_res_block, n_freq, n_hidden, n_output, kernel_size)
+ self.fc = nn.Linear(n_freq + self.n_aux + 1, n_rnn)
+
+ self.rnn1 = nn.GRU(n_rnn, n_rnn, batch_first=True)
+ self.rnn2 = nn.GRU(n_rnn + self.n_aux, n_rnn, batch_first=True)
+
+ self.relu1 = nn.ReLU(inplace=True)
+ self.relu2 = nn.ReLU(inplace=True)
+
+ self.fc1 = nn.Linear(n_rnn + self.n_aux, n_fc)
+ self.fc2 = nn.Linear(n_fc + self.n_aux, n_fc)
+ self.fc3 = nn.Linear(n_fc, self.n_classes)
+
+ def forward(self, waveform: Tensor, specgram: Tensor) -> Tensor:
+ r"""Pass the input through the WaveRNN model.
+
+ Args:
+ waveform: the input waveform to the WaveRNN layer (n_batch, 1, (n_time - kernel_size + 1) * hop_length)
+ specgram: the input spectrogram to the WaveRNN layer (n_batch, 1, n_freq, n_time)
+
+ Return:
+ Tensor: shape (n_batch, 1, (n_time - kernel_size + 1) * hop_length, n_classes)
+ """
+
+ if waveform.size(1) != 1:
+ raise ValueError("Require the input channel of waveform is 1")
+ if specgram.size(1) != 1:
+ raise ValueError("Require the input channel of specgram is 1")
+ # remove channel dimension until the end
+ waveform, specgram = waveform.squeeze(1), specgram.squeeze(1)
+
+ batch_size = waveform.size(0)
+ h1 = torch.zeros(1, batch_size, self.n_rnn, dtype=waveform.dtype, device=waveform.device)
+ h2 = torch.zeros(1, batch_size, self.n_rnn, dtype=waveform.dtype, device=waveform.device)
+ # output of upsample:
+ # specgram: (n_batch, n_freq, (n_time - kernel_size + 1) * total_scale)
+ # aux: (n_batch, n_output, (n_time - kernel_size + 1) * total_scale)
+ specgram, aux = self.upsample(specgram)
+ specgram = specgram.transpose(1, 2)
+ aux = aux.transpose(1, 2)
+
+ aux_idx = [self.n_aux * i for i in range(5)]
+ a1 = aux[:, :, aux_idx[0] : aux_idx[1]]
+ a2 = aux[:, :, aux_idx[1] : aux_idx[2]]
+ a3 = aux[:, :, aux_idx[2] : aux_idx[3]]
+ a4 = aux[:, :, aux_idx[3] : aux_idx[4]]
+
+ x = torch.cat([waveform.unsqueeze(-1), specgram, a1], dim=-1)
+ x = self.fc(x)
+ res = x
+ x, _ = self.rnn1(x, h1)
+
+ x = x + res
+ res = x
+ x = torch.cat([x, a2], dim=-1)
+ x, _ = self.rnn2(x, h2)
+
+ x = x + res
+ x = torch.cat([x, a3], dim=-1)
+ x = self.fc1(x)
+ x = self.relu1(x)
+
+ x = torch.cat([x, a4], dim=-1)
+ x = self.fc2(x)
+ x = self.relu2(x)
+ x = self.fc3(x)
+
+ # bring back channel dimension
+ return x.unsqueeze(1)
+
+ @torch.jit.export
+ def infer(self, specgram: Tensor, lengths: Optional[Tensor] = None) -> Tuple[Tensor, Optional[Tensor]]:
+ r"""Inference method of WaveRNN.
+
+ This function currently only supports multinomial sampling, which assumes the
+ network is trained on cross entropy loss.
+
+ Args:
+ specgram (Tensor):
+ Batch of spectrograms. Shape: `(n_batch, n_freq, n_time)`.
+ lengths (Tensor or None, optional):
+ Indicates the valid length of each audio in the batch.
+ Shape: `(batch, )`.
+ When the ``specgram`` contains spectrograms with different durations,
+ by providing ``lengths`` argument, the model will compute
+ the corresponding valid output lengths.
+ If ``None``, it is assumed that all the audio in ``waveforms``
+ have valid length. Default: ``None``.
+
+ Returns:
+ (Tensor, Optional[Tensor]):
+ Tensor
+ The inferred waveform of size `(n_batch, 1, n_time)`.
+ 1 stands for a single channel.
+ Tensor or None
+ If ``lengths`` argument was provided, a Tensor of shape `(batch, )`
+ is returned.
+ It indicates the valid length in time axis of the output Tensor.
+ """
+
+ device = specgram.device
+ dtype = specgram.dtype
+
+ specgram = torch.nn.functional.pad(specgram, (self._pad, self._pad))
+ specgram, aux = self.upsample(specgram)
+ if lengths is not None:
+ lengths = lengths * self.upsample.total_scale
+
+ output: List[Tensor] = []
+ b_size, _, seq_len = specgram.size()
+
+ h1 = torch.zeros((1, b_size, self.n_rnn), device=device, dtype=dtype)
+ h2 = torch.zeros((1, b_size, self.n_rnn), device=device, dtype=dtype)
+ x = torch.zeros((b_size, 1), device=device, dtype=dtype)
+
+ aux_split = [aux[:, self.n_aux * i : self.n_aux * (i + 1), :] for i in range(4)]
+
+ for i in range(seq_len):
+
+ m_t = specgram[:, :, i]
+
+ a1_t, a2_t, a3_t, a4_t = [a[:, :, i] for a in aux_split]
+
+ x = torch.cat([x, m_t, a1_t], dim=1)
+ x = self.fc(x)
+ _, h1 = self.rnn1(x.unsqueeze(1), h1)
+
+ x = x + h1[0]
+ inp = torch.cat([x, a2_t], dim=1)
+ _, h2 = self.rnn2(inp.unsqueeze(1), h2)
+
+ x = x + h2[0]
+ x = torch.cat([x, a3_t], dim=1)
+ x = F.relu(self.fc1(x))
+
+ x = torch.cat([x, a4_t], dim=1)
+ x = F.relu(self.fc2(x))
+
+ logits = self.fc3(x)
+
+ posterior = F.softmax(logits, dim=1)
+
+ x = torch.multinomial(posterior, 1).float()
+ # Transform label [0, 2 ** n_bits - 1] to waveform [-1, 1]
+ x = 2 * x / (2**self.n_bits - 1.0) - 1.0
+
+ output.append(x)
+
+ return torch.stack(output).permute(1, 2, 0), lengths
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cad3f14dfb5b27839d0954959428732acedb8a2a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/__init__.py
@@ -0,0 +1,102 @@
+from ._source_separation_pipeline import (
+ CONVTASNET_BASE_LIBRI2MIX,
+ HDEMUCS_HIGH_MUSDB,
+ HDEMUCS_HIGH_MUSDB_PLUS,
+ SourceSeparationBundle,
+)
+from ._squim_pipeline import SQUIM_OBJECTIVE, SQUIM_SUBJECTIVE, SquimObjectiveBundle, SquimSubjectiveBundle
+from ._tts import (
+ TACOTRON2_GRIFFINLIM_CHAR_LJSPEECH,
+ TACOTRON2_GRIFFINLIM_PHONE_LJSPEECH,
+ TACOTRON2_WAVERNN_CHAR_LJSPEECH,
+ TACOTRON2_WAVERNN_PHONE_LJSPEECH,
+ Tacotron2TTSBundle,
+)
+from ._wav2vec2.impl import (
+ HUBERT_ASR_LARGE,
+ HUBERT_ASR_XLARGE,
+ HUBERT_BASE,
+ HUBERT_LARGE,
+ HUBERT_XLARGE,
+ MMS_FA,
+ VOXPOPULI_ASR_BASE_10K_DE,
+ VOXPOPULI_ASR_BASE_10K_EN,
+ VOXPOPULI_ASR_BASE_10K_ES,
+ VOXPOPULI_ASR_BASE_10K_FR,
+ VOXPOPULI_ASR_BASE_10K_IT,
+ WAV2VEC2_ASR_BASE_100H,
+ WAV2VEC2_ASR_BASE_10M,
+ WAV2VEC2_ASR_BASE_960H,
+ WAV2VEC2_ASR_LARGE_100H,
+ WAV2VEC2_ASR_LARGE_10M,
+ WAV2VEC2_ASR_LARGE_960H,
+ WAV2VEC2_ASR_LARGE_LV60K_100H,
+ WAV2VEC2_ASR_LARGE_LV60K_10M,
+ WAV2VEC2_ASR_LARGE_LV60K_960H,
+ WAV2VEC2_BASE,
+ WAV2VEC2_LARGE,
+ WAV2VEC2_LARGE_LV60K,
+ WAV2VEC2_XLSR53,
+ WAV2VEC2_XLSR_1B,
+ WAV2VEC2_XLSR_2B,
+ WAV2VEC2_XLSR_300M,
+ Wav2Vec2ASRBundle,
+ Wav2Vec2Bundle,
+ Wav2Vec2FABundle,
+ WAVLM_BASE,
+ WAVLM_BASE_PLUS,
+ WAVLM_LARGE,
+)
+from .rnnt_pipeline import EMFORMER_RNNT_BASE_LIBRISPEECH, RNNTBundle
+
+
+__all__ = [
+ "Wav2Vec2Bundle",
+ "Wav2Vec2ASRBundle",
+ "Wav2Vec2FABundle",
+ "WAV2VEC2_BASE",
+ "WAV2VEC2_LARGE",
+ "WAV2VEC2_LARGE_LV60K",
+ "WAV2VEC2_ASR_BASE_10M",
+ "WAV2VEC2_ASR_BASE_100H",
+ "WAV2VEC2_ASR_BASE_960H",
+ "WAV2VEC2_ASR_LARGE_10M",
+ "WAV2VEC2_ASR_LARGE_100H",
+ "WAV2VEC2_ASR_LARGE_960H",
+ "WAV2VEC2_ASR_LARGE_LV60K_10M",
+ "WAV2VEC2_ASR_LARGE_LV60K_100H",
+ "WAV2VEC2_ASR_LARGE_LV60K_960H",
+ "WAV2VEC2_XLSR53",
+ "WAV2VEC2_XLSR_300M",
+ "WAV2VEC2_XLSR_1B",
+ "WAV2VEC2_XLSR_2B",
+ "VOXPOPULI_ASR_BASE_10K_EN",
+ "VOXPOPULI_ASR_BASE_10K_ES",
+ "VOXPOPULI_ASR_BASE_10K_DE",
+ "VOXPOPULI_ASR_BASE_10K_FR",
+ "VOXPOPULI_ASR_BASE_10K_IT",
+ "HUBERT_BASE",
+ "HUBERT_LARGE",
+ "HUBERT_XLARGE",
+ "HUBERT_ASR_LARGE",
+ "HUBERT_ASR_XLARGE",
+ "MMS_FA",
+ "WAVLM_BASE",
+ "WAVLM_BASE_PLUS",
+ "WAVLM_LARGE",
+ "Tacotron2TTSBundle",
+ "TACOTRON2_GRIFFINLIM_CHAR_LJSPEECH",
+ "TACOTRON2_GRIFFINLIM_PHONE_LJSPEECH",
+ "TACOTRON2_WAVERNN_CHAR_LJSPEECH",
+ "TACOTRON2_WAVERNN_PHONE_LJSPEECH",
+ "RNNTBundle",
+ "EMFORMER_RNNT_BASE_LIBRISPEECH",
+ "SourceSeparationBundle",
+ "CONVTASNET_BASE_LIBRI2MIX",
+ "HDEMUCS_HIGH_MUSDB_PLUS",
+ "HDEMUCS_HIGH_MUSDB",
+ "SQUIM_OBJECTIVE",
+ "SQUIM_SUBJECTIVE",
+ "SquimObjectiveBundle",
+ "SquimSubjectiveBundle",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/_source_separation_pipeline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/_source_separation_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..eebf190bd2233bd65143ba4b8b0da0ba5f1c6eba
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/_source_separation_pipeline.py
@@ -0,0 +1,109 @@
+from dataclasses import dataclass
+from functools import partial
+from typing import Callable
+
+import torch
+import torchaudio
+
+from torchaudio.models import conv_tasnet_base, hdemucs_high
+
+
+@dataclass
+class SourceSeparationBundle:
+ """Dataclass that bundles components for performing source separation.
+
+ Example
+ >>> import torchaudio
+ >>> from torchaudio.pipelines import CONVTASNET_BASE_LIBRI2MIX
+ >>> import torch
+ >>>
+ >>> # Build the separation model.
+ >>> model = CONVTASNET_BASE_LIBRI2MIX.get_model()
+ >>> 100%|███████████████████████████████|19.1M/19.1M [00:04<00:00, 4.93MB/s]
+ >>>
+ >>> # Instantiate the test set of Libri2Mix dataset.
+ >>> dataset = torchaudio.datasets.LibriMix("/home/datasets/", subset="test")
+ >>>
+ >>> # Apply source separation on mixture audio.
+ >>> for i, data in enumerate(dataset):
+ >>> sample_rate, mixture, clean_sources = data
+ >>> # Make sure the shape of input suits the model requirement.
+ >>> mixture = mixture.reshape(1, 1, -1)
+ >>> estimated_sources = model(mixture)
+ >>> score = si_snr_pit(estimated_sources, clean_sources) # for demonstration
+ >>> print(f"Si-SNR score is : {score}.)
+ >>> break
+ >>> Si-SNR score is : 16.24.
+ >>>
+ """
+
+ _model_path: str
+ _model_factory_func: Callable[[], torch.nn.Module]
+ _sample_rate: int
+
+ @property
+ def sample_rate(self) -> int:
+ """Sample rate of the audio that the model is trained on.
+
+ :type: int
+ """
+ return self._sample_rate
+
+ def get_model(self) -> torch.nn.Module:
+ """Construct the model and load the pretrained weight."""
+ model = self._model_factory_func()
+ path = torchaudio.utils.download_asset(self._model_path)
+ state_dict = torch.load(path)
+ model.load_state_dict(state_dict)
+ model.eval()
+ return model
+
+
+CONVTASNET_BASE_LIBRI2MIX = SourceSeparationBundle(
+ _model_path="models/conv_tasnet_base_libri2mix.pt",
+ _model_factory_func=partial(conv_tasnet_base, num_sources=2),
+ _sample_rate=8000,
+)
+CONVTASNET_BASE_LIBRI2MIX.__doc__ = """Pre-trained Source Separation pipeline with *ConvTasNet*
+:cite:`Luo_2019` trained on *Libri2Mix dataset* :cite:`cosentino2020librimix`.
+
+The source separation model is constructed by :func:`~torchaudio.models.conv_tasnet_base`
+and is trained using the training script ``lightning_train.py``
+`here `__
+with default arguments.
+
+Please refer to :class:`SourceSeparationBundle` for usage instructions.
+"""
+
+
+HDEMUCS_HIGH_MUSDB_PLUS = SourceSeparationBundle(
+ _model_path="models/hdemucs_high_trained.pt",
+ _model_factory_func=partial(hdemucs_high, sources=["drums", "bass", "other", "vocals"]),
+ _sample_rate=44100,
+)
+HDEMUCS_HIGH_MUSDB_PLUS.__doc__ = """Pre-trained music source separation pipeline with
+*Hybrid Demucs* :cite:`defossez2021hybrid` trained on both training and test sets of
+MUSDB-HQ :cite:`MUSDB18HQ` and an additional 150 extra songs from an internal database
+that was specifically produced for Meta.
+
+The model is constructed by :func:`~torchaudio.models.hdemucs_high`.
+
+Training was performed in the original HDemucs repository `here `__.
+
+Please refer to :class:`SourceSeparationBundle` for usage instructions.
+"""
+
+
+HDEMUCS_HIGH_MUSDB = SourceSeparationBundle(
+ _model_path="models/hdemucs_high_musdbhq_only.pt",
+ _model_factory_func=partial(hdemucs_high, sources=["drums", "bass", "other", "vocals"]),
+ _sample_rate=44100,
+)
+HDEMUCS_HIGH_MUSDB.__doc__ = """Pre-trained music source separation pipeline with
+*Hybrid Demucs* :cite:`defossez2021hybrid` trained on the training set of MUSDB-HQ :cite:`MUSDB18HQ`.
+
+The model is constructed by :func:`~torchaudio.models.hdemucs_high`.
+Training was performed in the original HDemucs repository `here `__.
+
+Please refer to :class:`SourceSeparationBundle` for usage instructions.
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/_squim_pipeline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/_squim_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..64b74449b0658ae5db47d1f7351ef448a1755d63
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/_squim_pipeline.py
@@ -0,0 +1,156 @@
+from dataclasses import dataclass
+
+import torch
+import torchaudio
+
+from torchaudio.models import squim_objective_base, squim_subjective_base, SquimObjective, SquimSubjective
+
+
+@dataclass
+class SquimObjectiveBundle:
+ """Data class that bundles associated information to use pretrained
+ :py:class:`~torchaudio.models.SquimObjective` model.
+
+ This class provides interfaces for instantiating the pretrained model along with
+ the information necessary to retrieve pretrained weights and additional data
+ to be used with the model.
+
+ Torchaudio library instantiates objects of this class, each of which represents
+ a different pretrained model. Client code should access pretrained models via these
+ instances.
+
+ This bundle can estimate objective metric scores for speech enhancement, such as STOI, PESQ, Si-SDR.
+ A typical use case would be a flow like `waveform -> list of scores`. Please see below for the code example.
+
+ Example: Estimate the objective metric scores for the input waveform.
+ >>> import torch
+ >>> import torchaudio
+ >>> from torchaudio.pipelines import SQUIM_OBJECTIVE as bundle
+ >>>
+ >>> # Load the SquimObjective bundle
+ >>> model = bundle.get_model()
+ Downloading: "https://download.pytorch.org/torchaudio/models/squim_objective_dns2020.pth"
+ 100%|████████████| 28.2M/28.2M [00:03<00:00, 9.24MB/s]
+ >>>
+ >>> # Resample audio to the expected sampling rate
+ >>> waveform = torchaudio.functional.resample(waveform, sample_rate, bundle.sample_rate)
+ >>>
+ >>> # Estimate objective metric scores
+ >>> scores = model(waveform)
+ >>> print(f"STOI: {scores[0].item()}, PESQ: {scores[1].item()}, SI-SDR: {scores[2].item()}.")
+ """ # noqa: E501
+
+ _path: str
+ _sample_rate: float
+
+ def get_model(self) -> SquimObjective:
+ """Construct the SquimObjective model, and load the pretrained weight.
+
+ Returns:
+ Variation of :py:class:`~torchaudio.models.SquimObjective`.
+ """
+ model = squim_objective_base()
+ path = torchaudio.utils.download_asset(f"models/{self._path}")
+ state_dict = torch.load(path, weights_only=True)
+ model.load_state_dict(state_dict)
+ model.eval()
+ return model
+
+ @property
+ def sample_rate(self):
+ """Sample rate of the audio that the model is trained on.
+
+ :type: float
+ """
+ return self._sample_rate
+
+
+SQUIM_OBJECTIVE = SquimObjectiveBundle(
+ "squim_objective_dns2020.pth",
+ _sample_rate=16000,
+)
+SQUIM_OBJECTIVE.__doc__ = """SquimObjective pipeline trained using approach described in
+ :cite:`kumar2023torchaudio` on the *DNS 2020 Dataset* :cite:`reddy2020interspeech`.
+
+ The underlying model is constructed by :py:func:`torchaudio.models.squim_objective_base`.
+ The weights are under `Creative Commons Attribution 4.0 International License
+ `__.
+
+ Please refer to :py:class:`SquimObjectiveBundle` for usage instructions.
+ """
+
+
+@dataclass
+class SquimSubjectiveBundle:
+ """Data class that bundles associated information to use pretrained
+ :py:class:`~torchaudio.models.SquimSubjective` model.
+
+ This class provides interfaces for instantiating the pretrained model along with
+ the information necessary to retrieve pretrained weights and additional data
+ to be used with the model.
+
+ Torchaudio library instantiates objects of this class, each of which represents
+ a different pretrained model. Client code should access pretrained models via these
+ instances.
+
+ This bundle can estimate subjective metric scores for speech enhancement, such as MOS.
+ A typical use case would be a flow like `waveform -> score`. Please see below for the code example.
+
+ Example: Estimate the subjective metric scores for the input waveform.
+ >>> import torch
+ >>> import torchaudio
+ >>> from torchaudio.pipelines import SQUIM_SUBJECTIVE as bundle
+ >>>
+ >>> # Load the SquimSubjective bundle
+ >>> model = bundle.get_model()
+ Downloading: "https://download.pytorch.org/torchaudio/models/squim_subjective_bvcc_daps.pth"
+ 100%|████████████| 360M/360M [00:09<00:00, 41.1MB/s]
+ >>>
+ >>> # Resample audio to the expected sampling rate
+ >>> waveform = torchaudio.functional.resample(waveform, sample_rate, bundle.sample_rate)
+ >>> # Use a clean reference (doesn't need to be the reference for the waveform) as the second input
+ >>> reference = torchaudio.functional.resample(reference, sample_rate, bundle.sample_rate)
+ >>>
+ >>> # Estimate subjective metric scores
+ >>> score = model(waveform, reference)
+ >>> print(f"MOS: {score}.")
+ """ # noqa: E501
+
+ _path: str
+ _sample_rate: float
+
+ def get_model(self) -> SquimSubjective:
+ """Construct the SquimSubjective model, and load the pretrained weight.
+ Returns:
+ Variation of :py:class:`~torchaudio.models.SquimObjective`.
+ """
+ model = squim_subjective_base()
+ path = torchaudio.utils.download_asset(f"models/{self._path}")
+ state_dict = torch.load(path, weights_only=True)
+ model.load_state_dict(state_dict)
+ model.eval()
+ return model
+
+ @property
+ def sample_rate(self):
+ """Sample rate of the audio that the model is trained on.
+
+ :type: float
+ """
+ return self._sample_rate
+
+
+SQUIM_SUBJECTIVE = SquimSubjectiveBundle(
+ "squim_subjective_bvcc_daps.pth",
+ _sample_rate=16000,
+)
+SQUIM_SUBJECTIVE.__doc__ = """SquimSubjective pipeline trained
+ as described in :cite:`manocha2022speech` and :cite:`kumar2023torchaudio`
+ on the *BVCC* :cite:`cooper2021voices` and *DAPS* :cite:`mysore2014can` datasets.
+
+ The underlying model is constructed by :py:func:`torchaudio.models.squim_subjective_base`.
+ The weights are under `Creative Commons Attribution Non Commercial 4.0 International
+ `__.
+
+ Please refer to :py:class:`SquimSubjectiveBundle` for usage instructions.
+ """
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/rnnt_pipeline.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/rnnt_pipeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a6f50941113d181e9950b3a3c7eadb9c1359a01
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/pipelines/rnnt_pipeline.py
@@ -0,0 +1,380 @@
+import json
+import math
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from functools import partial
+from typing import Callable, List, Tuple
+
+import torch
+import torchaudio
+from torchaudio._internal import module_utils
+from torchaudio.models import emformer_rnnt_base, RNNT, RNNTBeamSearch
+
+
+__all__ = []
+
+_decibel = 2 * 20 * math.log10(torch.iinfo(torch.int16).max)
+_gain = pow(10, 0.05 * _decibel)
+
+
+def _piecewise_linear_log(x):
+ x[x > math.e] = torch.log(x[x > math.e])
+ x[x <= math.e] = x[x <= math.e] / math.e
+ return x
+
+
+class _FunctionalModule(torch.nn.Module):
+ def __init__(self, functional):
+ super().__init__()
+ self.functional = functional
+
+ def forward(self, input):
+ return self.functional(input)
+
+
+class _GlobalStatsNormalization(torch.nn.Module):
+ def __init__(self, global_stats_path):
+ super().__init__()
+
+ with open(global_stats_path) as f:
+ blob = json.loads(f.read())
+
+ self.register_buffer("mean", torch.tensor(blob["mean"]))
+ self.register_buffer("invstddev", torch.tensor(blob["invstddev"]))
+
+ def forward(self, input):
+ return (input - self.mean) * self.invstddev
+
+
+class _FeatureExtractor(ABC):
+ @abstractmethod
+ def __call__(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Generates features and length output from the given input tensor.
+
+ Args:
+ input (torch.Tensor): input tensor.
+
+ Returns:
+ (torch.Tensor, torch.Tensor):
+ torch.Tensor:
+ Features, with shape `(length, *)`.
+ torch.Tensor:
+ Length, with shape `(1,)`.
+ """
+
+
+class _TokenProcessor(ABC):
+ @abstractmethod
+ def __call__(self, tokens: List[int], **kwargs) -> str:
+ """Decodes given list of tokens to text sequence.
+
+ Args:
+ tokens (List[int]): list of tokens to decode.
+
+ Returns:
+ str:
+ Decoded text sequence.
+ """
+
+
+class _ModuleFeatureExtractor(torch.nn.Module, _FeatureExtractor):
+ """``torch.nn.Module``-based feature extraction pipeline.
+
+ Args:
+ pipeline (torch.nn.Module): module that implements feature extraction logic.
+ """
+
+ def __init__(self, pipeline: torch.nn.Module) -> None:
+ super().__init__()
+ self.pipeline = pipeline
+
+ def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Generates features and length output from the given input tensor.
+
+ Args:
+ input (torch.Tensor): input tensor.
+
+ Returns:
+ (torch.Tensor, torch.Tensor):
+ torch.Tensor:
+ Features, with shape `(length, *)`.
+ torch.Tensor:
+ Length, with shape `(1,)`.
+ """
+ features = self.pipeline(input)
+ length = torch.tensor([features.shape[0]])
+ return features, length
+
+
+class _SentencePieceTokenProcessor(_TokenProcessor):
+ """SentencePiece-model-based token processor.
+
+ Args:
+ sp_model_path (str): path to SentencePiece model.
+ """
+
+ def __init__(self, sp_model_path: str) -> None:
+ if not module_utils.is_module_available("sentencepiece"):
+ raise RuntimeError("SentencePiece is not available. Please install it.")
+
+ import sentencepiece as spm
+
+ self.sp_model = spm.SentencePieceProcessor(model_file=sp_model_path)
+ self.post_process_remove_list = {
+ self.sp_model.unk_id(),
+ self.sp_model.eos_id(),
+ self.sp_model.pad_id(),
+ }
+
+ def __call__(self, tokens: List[int], lstrip: bool = True) -> str:
+ """Decodes given list of tokens to text sequence.
+
+ Args:
+ tokens (List[int]): list of tokens to decode.
+ lstrip (bool, optional): if ``True``, returns text sequence with leading whitespace
+ removed. (Default: ``True``).
+
+ Returns:
+ str:
+ Decoded text sequence.
+ """
+ filtered_hypo_tokens = [
+ token_index for token_index in tokens[1:] if token_index not in self.post_process_remove_list
+ ]
+ output_string = "".join(self.sp_model.id_to_piece(filtered_hypo_tokens)).replace("\u2581", " ")
+
+ if lstrip:
+ return output_string.lstrip()
+ else:
+ return output_string
+
+
+@dataclass
+class RNNTBundle:
+ """Dataclass that bundles components for performing automatic speech recognition (ASR, speech-to-text)
+ inference with an RNN-T model.
+
+ More specifically, the class provides methods that produce the featurization pipeline,
+ decoder wrapping the specified RNN-T model, and output token post-processor that together
+ constitute a complete end-to-end ASR inference pipeline that produces a text sequence
+ given a raw waveform.
+
+ It can support non-streaming (full-context) inference as well as streaming inference.
+
+ Users should not directly instantiate objects of this class; rather, users should use the
+ instances (representing pre-trained models) that exist within the module,
+ e.g. :data:`torchaudio.pipelines.EMFORMER_RNNT_BASE_LIBRISPEECH`.
+
+ Example
+ >>> import torchaudio
+ >>> from torchaudio.pipelines import EMFORMER_RNNT_BASE_LIBRISPEECH
+ >>> import torch
+ >>>
+ >>> # Non-streaming inference.
+ >>> # Build feature extractor, decoder with RNN-T model, and token processor.
+ >>> feature_extractor = EMFORMER_RNNT_BASE_LIBRISPEECH.get_feature_extractor()
+ 100%|███████████████████████████████| 3.81k/3.81k [00:00<00:00, 4.22MB/s]
+ >>> decoder = EMFORMER_RNNT_BASE_LIBRISPEECH.get_decoder()
+ Downloading: "https://download.pytorch.org/torchaudio/models/emformer_rnnt_base_librispeech.pt"
+ 100%|███████████████████████████████| 293M/293M [00:07<00:00, 42.1MB/s]
+ >>> token_processor = EMFORMER_RNNT_BASE_LIBRISPEECH.get_token_processor()
+ 100%|███████████████████████████████| 295k/295k [00:00<00:00, 25.4MB/s]
+ >>>
+ >>> # Instantiate LibriSpeech dataset; retrieve waveform for first sample.
+ >>> dataset = torchaudio.datasets.LIBRISPEECH("/home/librispeech", url="test-clean")
+ >>> waveform = next(iter(dataset))[0].squeeze()
+ >>>
+ >>> with torch.no_grad():
+ >>> # Produce mel-scale spectrogram features.
+ >>> features, length = feature_extractor(waveform)
+ >>>
+ >>> # Generate top-10 hypotheses.
+ >>> hypotheses = decoder(features, length, 10)
+ >>>
+ >>> # For top hypothesis, convert predicted tokens to text.
+ >>> text = token_processor(hypotheses[0][0])
+ >>> print(text)
+ he hoped there would be stew for dinner turnips and carrots and bruised potatoes and fat mutton pieces to [...]
+ >>>
+ >>>
+ >>> # Streaming inference.
+ >>> hop_length = EMFORMER_RNNT_BASE_LIBRISPEECH.hop_length
+ >>> num_samples_segment = EMFORMER_RNNT_BASE_LIBRISPEECH.segment_length * hop_length
+ >>> num_samples_segment_right_context = (
+ >>> num_samples_segment + EMFORMER_RNNT_BASE_LIBRISPEECH.right_context_length * hop_length
+ >>> )
+ >>>
+ >>> # Build streaming inference feature extractor.
+ >>> streaming_feature_extractor = EMFORMER_RNNT_BASE_LIBRISPEECH.get_streaming_feature_extractor()
+ >>>
+ >>> # Process same waveform as before, this time sequentially across overlapping segments
+ >>> # to simulate streaming inference. Note the usage of ``streaming_feature_extractor`` and ``decoder.infer``.
+ >>> state, hypothesis = None, None
+ >>> for idx in range(0, len(waveform), num_samples_segment):
+ >>> segment = waveform[idx: idx + num_samples_segment_right_context]
+ >>> segment = torch.nn.functional.pad(segment, (0, num_samples_segment_right_context - len(segment)))
+ >>> with torch.no_grad():
+ >>> features, length = streaming_feature_extractor(segment)
+ >>> hypotheses, state = decoder.infer(features, length, 10, state=state, hypothesis=hypothesis)
+ >>> hypothesis = hypotheses[0]
+ >>> transcript = token_processor(hypothesis[0])
+ >>> if transcript:
+ >>> print(transcript, end=" ", flush=True)
+ he hoped there would be stew for dinner turn ips and car rots and bru 'd oes and fat mut ton pieces to [...]
+ """
+
+ class FeatureExtractor(_FeatureExtractor):
+ """Interface of the feature extraction part of RNN-T pipeline"""
+
+ class TokenProcessor(_TokenProcessor):
+ """Interface of the token processor part of RNN-T pipeline"""
+
+ _rnnt_path: str
+ _rnnt_factory_func: Callable[[], RNNT]
+ _global_stats_path: str
+ _sp_model_path: str
+ _right_padding: int
+ _blank: int
+ _sample_rate: int
+ _n_fft: int
+ _n_mels: int
+ _hop_length: int
+ _segment_length: int
+ _right_context_length: int
+
+ def _get_model(self) -> RNNT:
+ model = self._rnnt_factory_func()
+ path = torchaudio.utils.download_asset(self._rnnt_path)
+ state_dict = torch.load(path)
+ model.load_state_dict(state_dict)
+ model.eval()
+ return model
+
+ @property
+ def sample_rate(self) -> int:
+ """Sample rate (in cycles per second) of input waveforms.
+
+ :type: int
+ """
+ return self._sample_rate
+
+ @property
+ def n_fft(self) -> int:
+ """Size of FFT window to use.
+
+ :type: int
+ """
+ return self._n_fft
+
+ @property
+ def n_mels(self) -> int:
+ """Number of mel spectrogram features to extract from input waveforms.
+
+ :type: int
+ """
+ return self._n_mels
+
+ @property
+ def hop_length(self) -> int:
+ """Number of samples between successive frames in input expected by model.
+
+ :type: int
+ """
+ return self._hop_length
+
+ @property
+ def segment_length(self) -> int:
+ """Number of frames in segment in input expected by model.
+
+ :type: int
+ """
+ return self._segment_length
+
+ @property
+ def right_context_length(self) -> int:
+ """Number of frames in right contextual block in input expected by model.
+
+ :type: int
+ """
+ return self._right_context_length
+
+ def get_decoder(self) -> RNNTBeamSearch:
+ """Constructs RNN-T decoder.
+
+ Returns:
+ RNNTBeamSearch
+ """
+ model = self._get_model()
+ return RNNTBeamSearch(model, self._blank)
+
+ def get_feature_extractor(self) -> FeatureExtractor:
+ """Constructs feature extractor for non-streaming (full-context) ASR.
+
+ Returns:
+ FeatureExtractor
+ """
+ local_path = torchaudio.utils.download_asset(self._global_stats_path)
+ return _ModuleFeatureExtractor(
+ torch.nn.Sequential(
+ torchaudio.transforms.MelSpectrogram(
+ sample_rate=self.sample_rate, n_fft=self.n_fft, n_mels=self.n_mels, hop_length=self.hop_length
+ ),
+ _FunctionalModule(lambda x: x.transpose(1, 0)),
+ _FunctionalModule(lambda x: _piecewise_linear_log(x * _gain)),
+ _GlobalStatsNormalization(local_path),
+ _FunctionalModule(lambda x: torch.nn.functional.pad(x, (0, 0, 0, self._right_padding))),
+ )
+ )
+
+ def get_streaming_feature_extractor(self) -> FeatureExtractor:
+ """Constructs feature extractor for streaming (simultaneous) ASR.
+
+ Returns:
+ FeatureExtractor
+ """
+ local_path = torchaudio.utils.download_asset(self._global_stats_path)
+ return _ModuleFeatureExtractor(
+ torch.nn.Sequential(
+ torchaudio.transforms.MelSpectrogram(
+ sample_rate=self.sample_rate, n_fft=self.n_fft, n_mels=self.n_mels, hop_length=self.hop_length
+ ),
+ _FunctionalModule(lambda x: x.transpose(1, 0)),
+ _FunctionalModule(lambda x: _piecewise_linear_log(x * _gain)),
+ _GlobalStatsNormalization(local_path),
+ )
+ )
+
+ def get_token_processor(self) -> TokenProcessor:
+ """Constructs token processor.
+
+ Returns:
+ TokenProcessor
+ """
+ local_path = torchaudio.utils.download_asset(self._sp_model_path)
+ return _SentencePieceTokenProcessor(local_path)
+
+
+EMFORMER_RNNT_BASE_LIBRISPEECH = RNNTBundle(
+ _rnnt_path="models/emformer_rnnt_base_librispeech.pt",
+ _rnnt_factory_func=partial(emformer_rnnt_base, num_symbols=4097),
+ _global_stats_path="pipeline-assets/global_stats_rnnt_librispeech.json",
+ _sp_model_path="pipeline-assets/spm_bpe_4096_librispeech.model",
+ _right_padding=4,
+ _blank=4096,
+ _sample_rate=16000,
+ _n_fft=400,
+ _n_mels=80,
+ _hop_length=160,
+ _segment_length=16,
+ _right_context_length=4,
+)
+EMFORMER_RNNT_BASE_LIBRISPEECH.__doc__ = """ASR pipeline based on Emformer-RNNT,
+pretrained on *LibriSpeech* dataset :cite:`7178964`,
+capable of performing both streaming and non-streaming inference.
+
+The underlying model is constructed by :py:func:`torchaudio.models.emformer_rnnt_base`
+and utilizes weights trained on LibriSpeech using training script ``train.py``
+`here `__ with default arguments.
+
+Please refer to :py:class:`RNNTBundle` for usage instructions.
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/datasets/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..66123a85ed4d8dd27e0eedaa8a0c8e5552da6348
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/datasets/__init__.py
@@ -0,0 +1,4 @@
+from .musan import Musan
+
+
+__all__ = ["Musan"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/datasets/musan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/datasets/musan.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e8fe3d6a1342378c70108cad7679d8fd64b7c7a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/datasets/musan.py
@@ -0,0 +1,67 @@
+from pathlib import Path
+from typing import Tuple, Union
+
+import torch
+from torch.utils.data import Dataset
+from torchaudio.datasets.utils import _load_waveform
+
+
+_SUBSETS = ["music", "noise", "speech"]
+_SAMPLE_RATE = 16_000
+
+
+class Musan(Dataset):
+ r"""*MUSAN* :cite:`musan2015` dataset.
+
+ Args:
+ root (str or Path): Root directory where the dataset's top-level directory exists.
+ subset (str): Subset of the dataset to use. Options: [``"music"``, ``"noise"``, ``"speech"``].
+ """
+
+ def __init__(self, root: Union[str, Path], subset: str):
+ if subset not in _SUBSETS:
+ raise ValueError(f"Invalid subset '{subset}' given. Please provide one of {_SUBSETS}")
+
+ subset_path = Path(root) / subset
+ self._walker = [str(p) for p in subset_path.glob("*/*.*")]
+
+ def get_metadata(self, n: int) -> Tuple[str, int, str]:
+ r"""Get metadata for the n-th sample in the dataset. Returns filepath instead of waveform,
+ but otherwise returns the same fields as :py:func:`__getitem__`.
+
+ Args:
+ n (int): Index of sample to be loaded.
+
+ Returns:
+ (str, int, str):
+ str
+ Path to audio.
+ int
+ Sample rate.
+ str
+ File name.
+ """
+ audio_path = self._walker[n]
+ return audio_path, _SAMPLE_RATE, Path(audio_path).name
+
+ def __getitem__(self, n: int) -> Tuple[torch.Tensor, int, str]:
+ r"""Return the n-th sample in the dataset.
+
+ Args:
+ n (int): Index of sample to be loaded.
+
+ Returns:
+ (torch.Tensor, int, str):
+ torch.Tensor
+ Waveform.
+ int
+ Sample rate.
+ str
+ File name.
+ """
+ audio_path, sample_rate, filename = self.get_metadata(n)
+ path = Path(audio_path)
+ return _load_waveform(path.parent, path.name, sample_rate), sample_rate, filename
+
+ def __len__(self) -> int:
+ return len(self._walker)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/functional/_dsp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/functional/_dsp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c590374b3fe8ce58479ed0c0388a551ad8765004
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/functional/_dsp.py
@@ -0,0 +1,433 @@
+import warnings
+from typing import List, Optional, Union
+
+import torch
+
+from torchaudio.functional import fftconvolve
+
+
+def oscillator_bank(
+ frequencies: torch.Tensor,
+ amplitudes: torch.Tensor,
+ sample_rate: float,
+ reduction: str = "sum",
+ dtype: Optional[torch.dtype] = torch.float64,
+) -> torch.Tensor:
+ """Synthesize waveform from the given instantaneous frequencies and amplitudes.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Note:
+ The phase information of the output waveform is found by taking the cumulative sum
+ of the given instantaneous frequencies (``frequencies``).
+ This incurs roundoff error when the data type does not have enough precision.
+ Using ``torch.float64`` can work around this.
+
+ The following figure shows the difference between ``torch.float32`` and
+ ``torch.float64`` when generating a sin wave of constant frequency and amplitude
+ with sample rate 8000 [Hz].
+ Notice that ``torch.float32`` version shows artifacts that are not seen in
+ ``torch.float64`` version.
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/oscillator_precision.png
+
+ Args:
+ frequencies (Tensor): Sample-wise oscillator frequencies (Hz). Shape `(..., time, N)`.
+ amplitudes (Tensor): Sample-wise oscillator amplitude. Shape: `(..., time, N)`.
+ sample_rate (float): Sample rate
+ reduction (str): Reduction to perform.
+ Valid values are ``"sum"``, ``"mean"`` or ``"none"``. Default: ``"sum"``
+ dtype (torch.dtype or None, optional): The data type on which cumulative sum operation is performed.
+ Default: ``torch.float64``. Pass ``None`` to disable the casting.
+
+ Returns:
+ Tensor:
+ The resulting waveform.
+
+ If ``reduction`` is ``"none"``, then the shape is
+ `(..., time, N)`, otherwise the shape is `(..., time)`.
+ """
+ if frequencies.shape != amplitudes.shape:
+ raise ValueError(
+ "The shapes of `frequencies` and `amplitudes` must match. "
+ f"Found: {frequencies.shape} and {amplitudes.shape} respectively."
+ )
+ reductions = ["sum", "mean", "none"]
+ if reduction not in reductions:
+ raise ValueError(f"The value of reduction must be either {reductions}. Found: {reduction}")
+
+ invalid = torch.abs(frequencies) >= sample_rate / 2
+ if torch.any(invalid):
+ warnings.warn(
+ "Some frequencies are above nyquist frequency. "
+ "Setting the corresponding amplitude to zero. "
+ "This might cause numerically unstable gradient."
+ )
+ amplitudes = torch.where(invalid, 0.0, amplitudes)
+
+ pi2 = 2.0 * torch.pi
+ freqs = frequencies * pi2 / sample_rate % pi2
+ phases = torch.cumsum(freqs, dim=-2, dtype=dtype)
+ if dtype is not None and freqs.dtype != dtype:
+ phases = phases.to(freqs.dtype)
+
+ waveform = amplitudes * torch.sin(phases)
+ if reduction == "sum":
+ return waveform.sum(-1)
+ if reduction == "mean":
+ return waveform.mean(-1)
+ return waveform
+
+
+def adsr_envelope(
+ num_frames: int,
+ *,
+ attack: float = 0.0,
+ hold: float = 0.0,
+ decay: float = 0.0,
+ sustain: float = 1.0,
+ release: float = 0.0,
+ n_decay: int = 2,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+):
+ """Generate ADSR Envelope
+
+ .. devices:: CPU CUDA
+
+ Args:
+ num_frames (int): The number of output frames.
+ attack (float, optional):
+ The relative *time* it takes to reach the maximum level from
+ the start. (Default: ``0.0``)
+ hold (float, optional):
+ The relative *time* the maximum level is held before
+ it starts to decay. (Default: ``0.0``)
+ decay (float, optional):
+ The relative *time* it takes to sustain from
+ the maximum level. (Default: ``0.0``)
+ sustain (float, optional): The relative *level* at which
+ the sound should sustain. (Default: ``1.0``)
+
+ .. Note::
+ The duration of sustain is derived as `1.0 - (The sum of attack, hold, decay and release)`.
+
+ release (float, optional): The relative *time* it takes for the sound level to
+ reach zero after the sustain. (Default: ``0.0``)
+ n_decay (int, optional): The degree of polynomial decay. Default: ``2``.
+ dtype (torch.dtype, optional): the desired data type of returned tensor.
+ Default: if ``None``, uses a global default
+ (see :py:func:`torch.set_default_tensor_type`).
+ device (torch.device, optional): the desired device of returned tensor.
+ Default: if ``None``, uses the current device for the default tensor type
+ (see :py:func:`torch.set_default_tensor_type`).
+ device will be the CPU for CPU tensor types and the current CUDA
+ device for CUDA tensor types.
+
+ Returns:
+ Tensor: ADSR Envelope. Shape: `(num_frames, )`
+
+ Example
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/adsr_examples.png
+
+ """
+ if not 0 <= attack <= 1:
+ raise ValueError(f"The value of `attack` must be within [0, 1]. Found: {attack}")
+ if not 0 <= decay <= 1:
+ raise ValueError(f"The value of `decay` must be within [0, 1]. Found: {decay}")
+ if not 0 <= sustain <= 1:
+ raise ValueError(f"The value of `sustain` must be within [0, 1]. Found: {sustain}")
+ if not 0 <= hold <= 1:
+ raise ValueError(f"The value of `hold` must be within [0, 1]. Found: {hold}")
+ if not 0 <= release <= 1:
+ raise ValueError(f"The value of `release` must be within [0, 1]. Found: {release}")
+ if attack + decay + release + hold > 1:
+ raise ValueError("The sum of `attack`, `hold`, `decay` and `release` must not exceed 1.")
+
+ nframes = num_frames - 1
+ num_a = int(nframes * attack)
+ num_h = int(nframes * hold)
+ num_d = int(nframes * decay)
+ num_r = int(nframes * release)
+
+ # Initialize with sustain
+ out = torch.full((num_frames,), float(sustain), device=device, dtype=dtype)
+
+ # attack
+ if num_a > 0:
+ torch.linspace(0.0, 1.0, num_a + 1, out=out[: num_a + 1])
+
+ # hold
+ if num_h > 0:
+ out[num_a : num_a + num_h + 1] = 1.0
+
+ # decay
+ if num_d > 0:
+ # Compute: sustain + (1.0 - sustain) * (linspace[1, 0] ** n_decay)
+ i = num_a + num_h
+ decay = out[i : i + num_d + 1]
+ torch.linspace(1.0, 0.0, num_d + 1, out=decay)
+ decay **= n_decay
+ decay *= 1.0 - sustain
+ decay += sustain
+
+ # sustain is handled by initialization
+
+ # release
+ if num_r > 0:
+ torch.linspace(sustain, 0, num_r + 1, out=out[-num_r - 1 :])
+
+ return out
+
+
+def extend_pitch(
+ base: torch.Tensor,
+ pattern: Union[int, List[float], torch.Tensor],
+):
+ """Extend the given time series values with multipliers of them.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Given a series of fundamental frequencies (pitch), this function appends
+ its harmonic overtones or inharmonic partials.
+
+ Args:
+ base (torch.Tensor):
+ Base time series, like fundamental frequencies (Hz). Shape: `(..., time, 1)`.
+ pattern (int, list of floats or torch.Tensor):
+ If ``int``, the number of pitch series after the operation.
+ `pattern - 1` tones are added, so that the resulting Tensor contains
+ up to `pattern`-th overtones of the given series.
+
+ If list of float or ``torch.Tensor``, it must be one dimensional,
+ representing the custom multiplier of the fundamental frequency.
+
+ Returns:
+ Tensor: Oscillator frequencies (Hz). Shape: `(..., time, num_tones)`.
+
+ Example
+ >>> # fundamental frequency
+ >>> f0 = torch.linspace(1, 5, 5).unsqueeze(-1)
+ >>> f0
+ tensor([[1.],
+ [2.],
+ [3.],
+ [4.],
+ [5.]])
+ >>> # Add harmonic overtones, up to 3rd.
+ >>> f = extend_pitch(f0, 3)
+ >>> f.shape
+ torch.Size([5, 3])
+ >>> f
+ tensor([[ 1., 2., 3.],
+ [ 2., 4., 6.],
+ [ 3., 6., 9.],
+ [ 4., 8., 12.],
+ [ 5., 10., 15.]])
+ >>> # Add custom (inharmonic) partials.
+ >>> f = extend_pitch(f0, torch.tensor([1, 2.1, 3.3, 4.5]))
+ >>> f.shape
+ torch.Size([5, 4])
+ >>> f
+ tensor([[ 1.0000, 2.1000, 3.3000, 4.5000],
+ [ 2.0000, 4.2000, 6.6000, 9.0000],
+ [ 3.0000, 6.3000, 9.9000, 13.5000],
+ [ 4.0000, 8.4000, 13.2000, 18.0000],
+ [ 5.0000, 10.5000, 16.5000, 22.5000]])
+ """
+ if isinstance(pattern, torch.Tensor):
+ mult = pattern
+ elif isinstance(pattern, int):
+ mult = torch.linspace(1.0, float(pattern), pattern, device=base.device, dtype=base.dtype)
+ else:
+ mult = torch.tensor(pattern, dtype=base.dtype, device=base.device)
+ h_freq = base @ mult.unsqueeze(0)
+ return h_freq
+
+
+def sinc_impulse_response(cutoff: torch.Tensor, window_size: int = 513, high_pass: bool = False):
+ """Create windowed-sinc impulse response for given cutoff frequencies.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ cutoff (Tensor): Cutoff frequencies for low-pass sinc filter.
+
+ window_size (int, optional): Size of the Hamming window to apply. Must be odd.
+ (Default: 513)
+
+ high_pass (bool, optional):
+ If ``True``, convert the resulting filter to high-pass.
+ Otherwise low-pass filter is returned. Default: ``False``.
+
+ Returns:
+ Tensor: A series of impulse responses. Shape: `(..., window_size)`.
+ """
+ if window_size % 2 == 0:
+ raise ValueError(f"`window_size` must be odd. Given: {window_size}")
+
+ half = window_size // 2
+ device, dtype = cutoff.device, cutoff.dtype
+ idx = torch.linspace(-half, half, window_size, device=device, dtype=dtype)
+
+ filt = torch.special.sinc(cutoff.unsqueeze(-1) * idx.unsqueeze(0))
+ filt = filt * torch.hamming_window(window_size, device=device, dtype=dtype, periodic=False).unsqueeze(0)
+ filt = filt / filt.sum(dim=-1, keepdim=True).abs()
+
+ # High pass IR is obtained by subtracting low_pass IR from delta function.
+ # https://courses.engr.illinois.edu/ece401/fa2020/slides/lec10.pdf
+ if high_pass:
+ filt = -filt
+ filt[..., half] = 1.0 + filt[..., half]
+ return filt
+
+
+def frequency_impulse_response(magnitudes):
+ """Create filter from desired frequency response
+
+ Args:
+ magnitudes: The desired frequency responses. Shape: `(..., num_fft_bins)`
+
+ Returns:
+ Tensor: Impulse response. Shape `(..., 2 * (num_fft_bins - 1))`
+ """
+ if magnitudes.min() < 0.0:
+ # Negative magnitude does not make sense but allowing so that autograd works
+ # around 0.
+ # Should we raise error?
+ warnings.warn("The input frequency response should not contain negative values.")
+ ir = torch.fft.fftshift(torch.fft.irfft(magnitudes), dim=-1)
+ device, dtype = magnitudes.device, magnitudes.dtype
+ window = torch.hann_window(ir.size(-1), periodic=False, device=device, dtype=dtype).expand_as(ir)
+ return ir * window
+
+
+def _overlap_and_add(waveform, stride):
+ num_frames, frame_size = waveform.shape[-2:]
+ numel = (num_frames - 1) * stride + frame_size
+ buffer = torch.zeros(waveform.shape[:-2] + (numel,), device=waveform.device, dtype=waveform.dtype)
+ for i in range(num_frames):
+ start = i * stride
+ end = start + frame_size
+ buffer[..., start:end] += waveform[..., i, :]
+ return buffer
+
+
+def filter_waveform(waveform: torch.Tensor, kernels: torch.Tensor, delay_compensation: int = -1):
+ """Applies filters along time axis of the given waveform.
+
+ This function applies the given filters along time axis in the following manner:
+
+ 1. Split the given waveform into chunks. The number of chunks is equal to the number of given filters.
+ 2. Filter each chunk with corresponding filter.
+ 3. Place the filtered chunks at the original indices while adding up the overlapping parts.
+ 4. Crop the resulting waveform so that delay introduced by the filter is removed and its length
+ matches that of the input waveform.
+
+ The following figure illustrates this.
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/filter_waveform.png
+
+ .. note::
+
+ If the number of filters is one, then the operation becomes stationary.
+ i.e. the same filtering is applied across the time axis.
+
+ Args:
+ waveform (Tensor): Shape `(..., time)`.
+ kernels (Tensor): Impulse responses.
+ Valid inputs are 2D tensor with shape `(num_filters, filter_length)` or
+ `(N+1)`-D tensor with shape `(..., num_filters, filter_length)`, where `N` is
+ the dimension of waveform.
+
+ In case of 2D input, the same set of filters is used across channels and batches.
+ Otherwise, different sets of filters are applied. In this case, the shape of
+ the first `N-1` dimensions of filters must match (or be broadcastable to) that of waveform.
+
+ delay_compensation (int): Control how the waveform is cropped after full convolution.
+ If the value is zero or positive, it is interpreted as the length of crop at the
+ beginning of the waveform. The value cannot be larger than the size of filter kernel.
+ Otherwise the initial crop is ``filter_size // 2``.
+ When cropping happens, the waveform is also cropped from the end so that the
+ length of the resulting waveform matches the input waveform.
+
+ Returns:
+ Tensor: `(..., time)`.
+ """
+ if kernels.ndim not in [2, waveform.ndim + 1]:
+ raise ValueError(
+ "`kernels` must be 2 or N+1 dimension where "
+ f"N is the dimension of waveform. Found: {kernels.ndim} (N={waveform.ndim})"
+ )
+
+ num_filters, filter_size = kernels.shape[-2:]
+ num_frames = waveform.size(-1)
+
+ if delay_compensation > filter_size:
+ raise ValueError(
+ "When `delay_compenstation` is provided, it cannot be larger than the size of filters."
+ f"Found: delay_compensation={delay_compensation}, filter_size={filter_size}"
+ )
+
+ # Transform waveform's time axis into (num_filters x chunk_length) with optional padding
+ chunk_length = num_frames // num_filters
+ if num_frames % num_filters > 0:
+ chunk_length += 1
+ num_pad = chunk_length * num_filters - num_frames
+ waveform = torch.nn.functional.pad(waveform, [0, num_pad], "constant", 0)
+ chunked = waveform.unfold(-1, chunk_length, chunk_length)
+ assert chunked.numel() >= waveform.numel()
+
+ # Broadcast kernels
+ if waveform.ndim + 1 > kernels.ndim:
+ expand_shape = waveform.shape[:-1] + kernels.shape
+ kernels = kernels.expand(expand_shape)
+
+ convolved = fftconvolve(chunked, kernels)
+ restored = _overlap_and_add(convolved, chunk_length)
+
+ # Trim in a way that the number of samples are same as input,
+ # and the filter delay is compensated
+ if delay_compensation >= 0:
+ start = delay_compensation
+ else:
+ start = filter_size // 2
+ num_crops = restored.size(-1) - num_frames
+ end = num_crops - start
+ result = restored[..., start:-end]
+ return result
+
+
+def exp_sigmoid(
+ input: torch.Tensor, exponent: float = 10.0, max_value: float = 2.0, threshold: float = 1e-7
+) -> torch.Tensor:
+ """Exponential Sigmoid pointwise nonlinearity.
+ Implements the equation:
+ ``max_value`` * sigmoid(``input``) ** (log(``exponent``)) + ``threshold``
+
+ The output has a range of [``threshold``, ``max_value``].
+ ``exponent`` controls the slope of the output.
+
+ .. devices:: CPU CUDA
+
+ Args:
+ input (Tensor): Input Tensor
+ exponent (float, optional): Exponent. Controls the slope of the output
+ max_value (float, optional): Maximum value of the output
+ threshold (float, optional): Minimum value of the output
+
+ Returns:
+ Tensor: Exponential Sigmoid output. Shape: same as input
+
+ """
+
+ return max_value * torch.pow(
+ torch.nn.functional.sigmoid(input),
+ torch.log(torch.tensor(exponent, device=input.device, dtype=input.dtype)),
+ ) + torch.tensor(threshold, device=input.device, dtype=input.dtype)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/functional/functional.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/functional/functional.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d14d7af29c5b72249a4b015e6bf6609a6acba78
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/prototype/functional/functional.py
@@ -0,0 +1,190 @@
+import math
+import warnings
+from typing import Optional
+
+import torch
+from torchaudio.functional.functional import _create_triangular_filterbank
+
+
+def _hz_to_bark(freqs: float, bark_scale: str = "traunmuller") -> float:
+ r"""Convert Hz to Barks.
+
+ Args:
+ freqs (float): Frequencies in Hz
+ bark_scale (str, optional): Scale to use: ``traunmuller``, ``schroeder`` or ``wang``. (Default: ``traunmuller``)
+
+ Returns:
+ barks (float): Frequency in Barks
+ """
+
+ if bark_scale not in ["schroeder", "traunmuller", "wang"]:
+ raise ValueError('bark_scale should be one of "schroeder", "traunmuller" or "wang".')
+
+ if bark_scale == "wang":
+ return 6.0 * math.asinh(freqs / 600.0)
+ elif bark_scale == "schroeder":
+ return 7.0 * math.asinh(freqs / 650.0)
+ # Traunmuller Bark scale
+ barks = ((26.81 * freqs) / (1960.0 + freqs)) - 0.53
+ # Bark value correction
+ if barks < 2:
+ barks += 0.15 * (2 - barks)
+ elif barks > 20.1:
+ barks += 0.22 * (barks - 20.1)
+
+ return barks
+
+
+def _bark_to_hz(barks: torch.Tensor, bark_scale: str = "traunmuller") -> torch.Tensor:
+ """Convert bark bin numbers to frequencies.
+
+ Args:
+ barks (torch.Tensor): Bark frequencies
+ bark_scale (str, optional): Scale to use: ``traunmuller``,``schroeder`` or ``wang``. (Default: ``traunmuller``)
+
+ Returns:
+ freqs (torch.Tensor): Barks converted in Hz
+ """
+
+ if bark_scale not in ["schroeder", "traunmuller", "wang"]:
+ raise ValueError('bark_scale should be one of "traunmuller", "schroeder" or "wang".')
+
+ if bark_scale == "wang":
+ return 600.0 * torch.sinh(barks / 6.0)
+ elif bark_scale == "schroeder":
+ return 650.0 * torch.sinh(barks / 7.0)
+ # Bark value correction
+ if any(barks < 2):
+ idx = barks < 2
+ barks[idx] = (barks[idx] - 0.3) / 0.85
+ elif any(barks > 20.1):
+ idx = barks > 20.1
+ barks[idx] = (barks[idx] + 4.422) / 1.22
+
+ # Traunmuller Bark scale
+ freqs = 1960 * ((barks + 0.53) / (26.28 - barks))
+
+ return freqs
+
+
+def _hz_to_octs(freqs, tuning=0.0, bins_per_octave=12):
+ a440 = 440.0 * 2.0 ** (tuning / bins_per_octave)
+ return torch.log2(freqs / (a440 / 16))
+
+
+def barkscale_fbanks(
+ n_freqs: int,
+ f_min: float,
+ f_max: float,
+ n_barks: int,
+ sample_rate: int,
+ bark_scale: str = "traunmuller",
+) -> torch.Tensor:
+ r"""Create a frequency bin conversion matrix.
+
+ .. devices:: CPU
+
+ .. properties:: TorchScript
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/bark_fbanks.png
+ :alt: Visualization of generated filter bank
+
+ Args:
+ n_freqs (int): Number of frequencies to highlight/apply
+ f_min (float): Minimum frequency (Hz)
+ f_max (float): Maximum frequency (Hz)
+ n_barks (int): Number of mel filterbanks
+ sample_rate (int): Sample rate of the audio waveform
+ bark_scale (str, optional): Scale to use: ``traunmuller``,``schroeder`` or ``wang``. (Default: ``traunmuller``)
+
+ Returns:
+ torch.Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_barks``)
+ meaning number of frequencies to highlight/apply to x the number of filterbanks.
+ Each column is a filterbank so that assuming there is a matrix A of
+ size (..., ``n_freqs``), the applied result would be
+ ``A * barkscale_fbanks(A.size(-1), ...)``.
+
+ """
+
+ # freq bins
+ all_freqs = torch.linspace(0, sample_rate // 2, n_freqs)
+
+ # calculate bark freq bins
+ m_min = _hz_to_bark(f_min, bark_scale=bark_scale)
+ m_max = _hz_to_bark(f_max, bark_scale=bark_scale)
+
+ m_pts = torch.linspace(m_min, m_max, n_barks + 2)
+ f_pts = _bark_to_hz(m_pts, bark_scale=bark_scale)
+
+ # create filterbank
+ fb = _create_triangular_filterbank(all_freqs, f_pts)
+
+ if (fb.max(dim=0).values == 0.0).any():
+ warnings.warn(
+ "At least one bark filterbank has all zero values. "
+ f"The value for `n_barks` ({n_barks}) may be set too high. "
+ f"Or, the value for `n_freqs` ({n_freqs}) may be set too low."
+ )
+
+ return fb
+
+
+def chroma_filterbank(
+ sample_rate: int,
+ n_freqs: int,
+ n_chroma: int,
+ *,
+ tuning: float = 0.0,
+ ctroct: float = 5.0,
+ octwidth: Optional[float] = 2.0,
+ norm: int = 2,
+ base_c: bool = True,
+):
+ """Create a frequency-to-chroma conversion matrix. Implementation adapted from librosa.
+
+ Args:
+ sample_rate (int): Sample rate.
+ n_freqs (int): Number of input frequencies.
+ n_chroma (int): Number of output chroma.
+ tuning (float, optional): Tuning deviation from A440 in fractions of a chroma bin. (Default: 0.0)
+ ctroct (float, optional): Center of Gaussian dominance window to weight filters by, in octaves. (Default: 5.0)
+ octwidth (float or None, optional): Width of Gaussian dominance window to weight filters by, in octaves.
+ If ``None``, then disable weighting altogether. (Default: 2.0)
+ norm (int, optional): order of norm to normalize filter bank by. (Default: 2)
+ base_c (bool, optional): If True, then start filter bank at C. Otherwise, start at A. (Default: True)
+
+ Returns:
+ torch.Tensor: Chroma filter bank, with shape `(n_freqs, n_chroma)`.
+ """
+ # Skip redundant upper half of frequency range.
+ freqs = torch.linspace(0, sample_rate // 2, n_freqs)[1:]
+ freq_bins = n_chroma * _hz_to_octs(freqs, bins_per_octave=n_chroma, tuning=tuning)
+ freq_bins = torch.cat((torch.tensor([freq_bins[0] - 1.5 * n_chroma]), freq_bins))
+ freq_bin_widths = torch.cat(
+ (
+ torch.maximum(freq_bins[1:] - freq_bins[:-1], torch.tensor(1.0)),
+ torch.tensor([1]),
+ )
+ )
+
+ # (n_freqs, n_chroma)
+ D = freq_bins.unsqueeze(1) - torch.arange(0, n_chroma)
+
+ n_chroma2 = round(n_chroma / 2)
+
+ # Project to range [-n_chroma/2, n_chroma/2 - 1]
+ D = torch.remainder(D + n_chroma2, n_chroma) - n_chroma2
+
+ fb = torch.exp(-0.5 * (2 * D / torch.tile(freq_bin_widths.unsqueeze(1), (1, n_chroma))) ** 2)
+ fb = torch.nn.functional.normalize(fb, p=norm, dim=1)
+
+ if octwidth is not None:
+ fb *= torch.tile(
+ torch.exp(-0.5 * (((freq_bins.unsqueeze(1) / n_chroma - ctroct) / octwidth) ** 2)),
+ (1, n_chroma),
+ )
+
+ if base_c:
+ fb = torch.roll(fb, -3 * (n_chroma // 12), dims=1)
+
+ return fb
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c65a49b277c25c36273b888c1ac2861cb3ce9a0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__init__.py
@@ -0,0 +1,10 @@
+from .sox_effects import apply_effects_file, apply_effects_tensor, effect_names, init_sox_effects, shutdown_sox_effects
+
+
+__all__ = [
+ "init_sox_effects",
+ "shutdown_sox_effects",
+ "effect_names",
+ "apply_effects_tensor",
+ "apply_effects_file",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..035a799dc1087ddde226c735fcf45f40a3ce9d71
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__pycache__/sox_effects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__pycache__/sox_effects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d24687faf135c90fe2927733b1e2c37cb0e759e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/__pycache__/sox_effects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/sox_effects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/sox_effects.py
new file mode 100644
index 0000000000000000000000000000000000000000..b80e4bfad689925ba4a08503ebaeddcbe5cc6a5d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/sox_effects/sox_effects.py
@@ -0,0 +1,272 @@
+import os
+from typing import List, Optional, Tuple
+
+import torch
+import torchaudio
+from torchaudio._internal.module_utils import deprecated
+from torchaudio.utils.sox_utils import list_effects
+
+
+sox_ext = torchaudio._extension.lazy_import_sox_ext()
+
+
+@deprecated("Please remove the call. This function is called automatically.")
+def init_sox_effects():
+ """Initialize resources required to use sox effects.
+
+ Note:
+ You do not need to call this function manually. It is called automatically.
+
+ Once initialized, you do not need to call this function again across the multiple uses of
+ sox effects though it is safe to do so as long as :func:`shutdown_sox_effects` is not called yet.
+ Once :func:`shutdown_sox_effects` is called, you can no longer use SoX effects and initializing
+ again will result in error.
+ """
+ pass
+
+
+@deprecated("Please remove the call. This function is called automatically.")
+def shutdown_sox_effects():
+ """Clean up resources required to use sox effects.
+
+ Note:
+ You do not need to call this function manually. It is called automatically.
+
+ It is safe to call this function multiple times.
+ Once :py:func:`shutdown_sox_effects` is called, you can no longer use SoX effects and
+ initializing again will result in error.
+ """
+ pass
+
+
+def effect_names() -> List[str]:
+ """Gets list of valid sox effect names
+
+ Returns:
+ List[str]: list of available effect names.
+
+ Example
+ >>> torchaudio.sox_effects.effect_names()
+ ['allpass', 'band', 'bandpass', ... ]
+ """
+ return list(list_effects().keys())
+
+
+def apply_effects_tensor(
+ tensor: torch.Tensor,
+ sample_rate: int,
+ effects: List[List[str]],
+ channels_first: bool = True,
+) -> Tuple[torch.Tensor, int]:
+ """Apply sox effects to given Tensor
+
+ .. devices:: CPU
+
+ .. properties:: TorchScript
+
+ Note:
+ This function only works on CPU Tensors.
+ This function works in the way very similar to ``sox`` command, however there are slight
+ differences. For example, ``sox`` command adds certain effects automatically (such as
+ ``rate`` effect after ``speed`` and ``pitch`` and other effects), but this function does
+ only applies the given effects. (Therefore, to actually apply ``speed`` effect, you also
+ need to give ``rate`` effect with desired sampling rate.).
+
+ Args:
+ tensor (torch.Tensor): Input 2D CPU Tensor.
+ sample_rate (int): Sample rate
+ effects (List[List[str]]): List of effects.
+ channels_first (bool, optional): Indicates if the input Tensor's dimension is
+ `[channels, time]` or `[time, channels]`
+
+ Returns:
+ (Tensor, int): Resulting Tensor and sample rate.
+ The resulting Tensor has the same ``dtype`` as the input Tensor, and
+ the same channels order. The shape of the Tensor can be different based on the
+ effects applied. Sample rate can also be different based on the effects applied.
+
+ Example - Basic usage
+ >>>
+ >>> # Defines the effects to apply
+ >>> effects = [
+ ... ['gain', '-n'], # normalises to 0dB
+ ... ['pitch', '5'], # 5 cent pitch shift
+ ... ['rate', '8000'], # resample to 8000 Hz
+ ... ]
+ >>>
+ >>> # Generate pseudo wave:
+ >>> # normalized, channels first, 2ch, sampling rate 16000, 1 second
+ >>> sample_rate = 16000
+ >>> waveform = 2 * torch.rand([2, sample_rate * 1]) - 1
+ >>> waveform.shape
+ torch.Size([2, 16000])
+ >>> waveform
+ tensor([[ 0.3138, 0.7620, -0.9019, ..., -0.7495, -0.4935, 0.5442],
+ [-0.0832, 0.0061, 0.8233, ..., -0.5176, -0.9140, -0.2434]])
+ >>>
+ >>> # Apply effects
+ >>> waveform, sample_rate = apply_effects_tensor(
+ ... wave_form, sample_rate, effects, channels_first=True)
+ >>>
+ >>> # Check the result
+ >>> # The new waveform is sampling rate 8000, 1 second.
+ >>> # normalization and channel order are preserved
+ >>> waveform.shape
+ torch.Size([2, 8000])
+ >>> waveform
+ tensor([[ 0.5054, -0.5518, -0.4800, ..., -0.0076, 0.0096, -0.0110],
+ [ 0.1331, 0.0436, -0.3783, ..., -0.0035, 0.0012, 0.0008]])
+ >>> sample_rate
+ 8000
+
+ Example - Torchscript-able transform
+ >>>
+ >>> # Use `apply_effects_tensor` in `torch.nn.Module` and dump it to file,
+ >>> # then run sox effect via Torchscript runtime.
+ >>>
+ >>> class SoxEffectTransform(torch.nn.Module):
+ ... effects: List[List[str]]
+ ...
+ ... def __init__(self, effects: List[List[str]]):
+ ... super().__init__()
+ ... self.effects = effects
+ ...
+ ... def forward(self, tensor: torch.Tensor, sample_rate: int):
+ ... return sox_effects.apply_effects_tensor(
+ ... tensor, sample_rate, self.effects)
+ ...
+ ...
+ >>> # Create transform object
+ >>> effects = [
+ ... ["lowpass", "-1", "300"], # apply single-pole lowpass filter
+ ... ["rate", "8000"], # change sample rate to 8000
+ ... ]
+ >>> transform = SoxEffectTensorTransform(effects, input_sample_rate)
+ >>>
+ >>> # Dump it to file and load
+ >>> path = 'sox_effect.zip'
+ >>> torch.jit.script(trans).save(path)
+ >>> transform = torch.jit.load(path)
+ >>>
+ >>>> # Run transform
+ >>> waveform, input_sample_rate = torchaudio.load("input.wav")
+ >>> waveform, sample_rate = transform(waveform, input_sample_rate)
+ >>> assert sample_rate == 8000
+ """
+ return sox_ext.apply_effects_tensor(tensor, sample_rate, effects, channels_first)
+
+
+def apply_effects_file(
+ path: str,
+ effects: List[List[str]],
+ normalize: bool = True,
+ channels_first: bool = True,
+ format: Optional[str] = None,
+) -> Tuple[torch.Tensor, int]:
+ """Apply sox effects to the audio file and load the resulting data as Tensor
+
+ .. devices:: CPU
+
+ .. properties:: TorchScript
+
+ Note:
+ This function works in the way very similar to ``sox`` command, however there are slight
+ differences. For example, ``sox`` commnad adds certain effects automatically (such as
+ ``rate`` effect after ``speed``, ``pitch`` etc), but this function only applies the given
+ effects. Therefore, to actually apply ``speed`` effect, you also need to give ``rate``
+ effect with desired sampling rate, because internally, ``speed`` effects only alter sampling
+ rate and leave samples untouched.
+
+ Args:
+ path (path-like object):
+ Source of audio data.
+ effects (List[List[str]]): List of effects.
+ normalize (bool, optional):
+ When ``True``, this function converts the native sample type to ``float32``.
+ Default: ``True``.
+
+ If input file is integer WAV, giving ``False`` will change the resulting Tensor type to
+ integer type.
+ This argument has no effect for formats other than integer WAV type.
+
+ channels_first (bool, optional): When True, the returned Tensor has dimension `[channel, time]`.
+ Otherwise, the returned Tensor's dimension is `[time, channel]`.
+ format (str or None, optional):
+ Override the format detection with the given format.
+ Providing the argument might help when libsox can not infer the format
+ from header or extension,
+
+ Returns:
+ (Tensor, int): Resulting Tensor and sample rate.
+ If ``normalize=True``, the resulting Tensor is always ``float32`` type.
+ If ``normalize=False`` and the input audio file is of integer WAV file, then the
+ resulting Tensor has corresponding integer type. (Note 24 bit integer type is not supported)
+ If ``channels_first=True``, the resulting Tensor has dimension `[channel, time]`,
+ otherwise `[time, channel]`.
+
+ Example - Basic usage
+ >>>
+ >>> # Defines the effects to apply
+ >>> effects = [
+ ... ['gain', '-n'], # normalises to 0dB
+ ... ['pitch', '5'], # 5 cent pitch shift
+ ... ['rate', '8000'], # resample to 8000 Hz
+ ... ]
+ >>>
+ >>> # Apply effects and load data with channels_first=True
+ >>> waveform, sample_rate = apply_effects_file("data.wav", effects, channels_first=True)
+ >>>
+ >>> # Check the result
+ >>> waveform.shape
+ torch.Size([2, 8000])
+ >>> waveform
+ tensor([[ 5.1151e-03, 1.8073e-02, 2.2188e-02, ..., 1.0431e-07,
+ -1.4761e-07, 1.8114e-07],
+ [-2.6924e-03, 2.1860e-03, 1.0650e-02, ..., 6.4122e-07,
+ -5.6159e-07, 4.8103e-07]])
+ >>> sample_rate
+ 8000
+
+ Example - Apply random speed perturbation to dataset
+ >>>
+ >>> # Load data from file, apply random speed perturbation
+ >>> class RandomPerturbationFile(torch.utils.data.Dataset):
+ ... \"\"\"Given flist, apply random speed perturbation
+ ...
+ ... Suppose all the input files are at least one second long.
+ ... \"\"\"
+ ... def __init__(self, flist: List[str], sample_rate: int):
+ ... super().__init__()
+ ... self.flist = flist
+ ... self.sample_rate = sample_rate
+ ...
+ ... def __getitem__(self, index):
+ ... speed = 0.5 + 1.5 * random.randn()
+ ... effects = [
+ ... ['gain', '-n', '-10'], # apply 10 db attenuation
+ ... ['remix', '-'], # merge all the channels
+ ... ['speed', f'{speed:.5f}'], # duration is now 0.5 ~ 2.0 seconds.
+ ... ['rate', f'{self.sample_rate}'],
+ ... ['pad', '0', '1.5'], # add 1.5 seconds silence at the end
+ ... ['trim', '0', '2'], # get the first 2 seconds
+ ... ]
+ ... waveform, _ = torchaudio.sox_effects.apply_effects_file(
+ ... self.flist[index], effects)
+ ... return waveform
+ ...
+ ... def __len__(self):
+ ... return len(self.flist)
+ ...
+ >>> dataset = RandomPerturbationFile(file_list, sample_rate=8000)
+ >>> loader = torch.utils.data.DataLoader(dataset, batch_size=32)
+ >>> for batch in loader:
+ >>> pass
+ """
+ if not torch.jit.is_scripting():
+ if hasattr(path, "read"):
+ raise RuntimeError(
+ "apply_effects_file function does not support file-like object. "
+ "Please use torchaudio.io.AudioEffector."
+ )
+ path = os.fspath(path)
+ return sox_ext.apply_effects_file(path, effects, normalize, channels_first, format)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd84516a001e93db4085229354b57a64b5213f3d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__init__.py
@@ -0,0 +1,75 @@
+from ._multi_channel import MVDR, PSD, RTFMVDR, SoudenMVDR
+from ._transforms import (
+ AddNoise,
+ AmplitudeToDB,
+ ComputeDeltas,
+ Convolve,
+ Deemphasis,
+ Fade,
+ FFTConvolve,
+ FrequencyMasking,
+ GriffinLim,
+ InverseMelScale,
+ InverseSpectrogram,
+ LFCC,
+ Loudness,
+ MelScale,
+ MelSpectrogram,
+ MFCC,
+ MuLawDecoding,
+ MuLawEncoding,
+ PitchShift,
+ Preemphasis,
+ Resample,
+ RNNTLoss,
+ SlidingWindowCmn,
+ SpecAugment,
+ SpectralCentroid,
+ Spectrogram,
+ Speed,
+ SpeedPerturbation,
+ TimeMasking,
+ TimeStretch,
+ Vad,
+ Vol,
+)
+
+
+__all__ = [
+ "AddNoise",
+ "AmplitudeToDB",
+ "ComputeDeltas",
+ "Convolve",
+ "Deemphasis",
+ "Fade",
+ "FFTConvolve",
+ "FrequencyMasking",
+ "GriffinLim",
+ "InverseMelScale",
+ "InverseSpectrogram",
+ "LFCC",
+ "Loudness",
+ "MFCC",
+ "MVDR",
+ "MelScale",
+ "MelSpectrogram",
+ "MuLawDecoding",
+ "MuLawEncoding",
+ "PSD",
+ "PitchShift",
+ "Preemphasis",
+ "RNNTLoss",
+ "RTFMVDR",
+ "Resample",
+ "SlidingWindowCmn",
+ "SoudenMVDR",
+ "SpecAugment",
+ "SpectralCentroid",
+ "Spectrogram",
+ "Speed",
+ "SpeedPerturbation",
+ "TimeMasking",
+ "TimeStretch",
+ "Vad",
+ "Vol",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15acb3a0cbbccbaedb0bd052a0d153f90d19a325
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__pycache__/_multi_channel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__pycache__/_multi_channel.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1afe6eaa1d5e7f70f49fff395aaa4e6b5f311de3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/__pycache__/_multi_channel.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/_multi_channel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/_multi_channel.py
new file mode 100644
index 0000000000000000000000000000000000000000..956ccd2ee1526e56f647872a07a5f55957ce2381
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/_multi_channel.py
@@ -0,0 +1,467 @@
+# -*- coding: utf-8 -*-
+
+import warnings
+from typing import Optional, Union
+
+import torch
+from torch import Tensor
+from torchaudio import functional as F
+
+
+__all__ = []
+
+
+def _get_mvdr_vector(
+ psd_s: torch.Tensor,
+ psd_n: torch.Tensor,
+ reference_vector: torch.Tensor,
+ solution: str = "ref_channel",
+ diagonal_loading: bool = True,
+ diag_eps: float = 1e-7,
+ eps: float = 1e-8,
+) -> torch.Tensor:
+ r"""Compute the MVDR beamforming weights with ``solution`` argument.
+
+ Args:
+ psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ reference_vector (torch.Tensor): one-hot reference channel matrix.
+ solution (str, optional): Solution to compute the MVDR beamforming weights.
+ Options: [``ref_channel``, ``stv_evd``, ``stv_power``]. (Default: ``ref_channel``)
+ diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
+ (Default: ``True``)
+ diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
+ It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
+ eps (float, optional): Value to add to the denominator in the beamforming weight formula.
+ (Default: ``1e-8``)
+
+ Returns:
+ torch.Tensor: the mvdr beamforming weight matrix
+ """
+ if solution == "ref_channel":
+ beamform_vector = F.mvdr_weights_souden(psd_s, psd_n, reference_vector, diagonal_loading, diag_eps, eps)
+ else:
+ if solution == "stv_evd":
+ stv = F.rtf_evd(psd_s)
+ else:
+ stv = F.rtf_power(psd_s, psd_n, reference_vector, diagonal_loading=diagonal_loading, diag_eps=diag_eps)
+ beamform_vector = F.mvdr_weights_rtf(stv, psd_n, reference_vector, diagonal_loading, diag_eps, eps)
+
+ return beamform_vector
+
+
+class PSD(torch.nn.Module):
+ r"""Compute cross-channel power spectral density (PSD) matrix.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ multi_mask (bool, optional): If ``True``, only accepts multi-channel Time-Frequency masks. (Default: ``False``)
+ normalize (bool, optional): If ``True``, normalize the mask along the time dimension. (Default: ``True``)
+ eps (float, optional): Value to add to the denominator in mask normalization. (Default: ``1e-15``)
+ """
+
+ def __init__(self, multi_mask: bool = False, normalize: bool = True, eps: float = 1e-15):
+ super().__init__()
+ self.multi_mask = multi_mask
+ self.normalize = normalize
+ self.eps = eps
+
+ def forward(self, specgram: torch.Tensor, mask: Optional[torch.Tensor] = None):
+ """
+ Args:
+ specgram (torch.Tensor): Multi-channel complex-valued spectrum.
+ Tensor with dimensions `(..., channel, freq, time)`.
+ mask (torch.Tensor or None, optional): Time-Frequency mask for normalization.
+ Tensor with dimensions `(..., freq, time)` if multi_mask is ``False`` or
+ with dimensions `(..., channel, freq, time)` if multi_mask is ``True``.
+ (Default: ``None``)
+
+ Returns:
+ torch.Tensor: The complex-valued PSD matrix of the input spectrum.
+ Tensor with dimensions `(..., freq, channel, channel)`
+ """
+ if mask is not None:
+ if self.multi_mask:
+ # Averaging mask along channel dimension
+ mask = mask.mean(dim=-3) # (..., freq, time)
+ psd = F.psd(specgram, mask, self.normalize, self.eps)
+
+ return psd
+
+
+class MVDR(torch.nn.Module):
+ """Minimum Variance Distortionless Response (MVDR) module that performs MVDR beamforming with Time-Frequency masks.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Based on https://github.com/espnet/espnet/blob/master/espnet2/enh/layers/beamformer.py
+
+ We provide three solutions of MVDR beamforming. One is based on *reference channel selection*
+ :cite:`souden2009optimal` (``solution=ref_channel``).
+
+ .. math::
+ \\textbf{w}_{\\text{MVDR}}(f) =\
+ \\frac{{{\\bf{\\Phi}_{\\textbf{NN}}^{-1}}(f){\\bf{\\Phi}_{\\textbf{SS}}}}(f)}\
+ {\\text{Trace}({{{\\bf{\\Phi}_{\\textbf{NN}}^{-1}}(f) \\bf{\\Phi}_{\\textbf{SS}}}(f))}}\\bm{u}
+
+ where :math:`\\bf{\\Phi}_{\\textbf{SS}}` and :math:`\\bf{\\Phi}_{\\textbf{NN}}` are the covariance\
+ matrices of speech and noise, respectively. :math:`\\bf{u}` is an one-hot vector to determine the\
+ reference channel.
+
+ The other two solutions are based on the steering vector (``solution=stv_evd`` or ``solution=stv_power``).
+
+ .. math::
+ \\textbf{w}_{\\text{MVDR}}(f) =\
+ \\frac{{{\\bf{\\Phi}_{\\textbf{NN}}^{-1}}(f){\\bm{v}}(f)}}\
+ {{\\bm{v}^{\\mathsf{H}}}(f){\\bf{\\Phi}_{\\textbf{NN}}^{-1}}(f){\\bm{v}}(f)}
+
+ where :math:`\\bm{v}` is the acoustic transfer function or the steering vector.\
+ :math:`.^{\\mathsf{H}}` denotes the Hermitian Conjugate operation.
+
+ We apply either *eigenvalue decomposition*
+ :cite:`higuchi2016robust` or the *power method* :cite:`mises1929praktische` to get the
+ steering vector from the PSD matrix of speech.
+
+ After estimating the beamforming weight, the enhanced Short-time Fourier Transform (STFT) is obtained by
+
+ .. math::
+ \\hat{\\bf{S}} = {\\bf{w}^\\mathsf{H}}{\\bf{Y}}, {\\bf{w}} \\in \\mathbb{C}^{M \\times F}
+
+ where :math:`\\bf{Y}` and :math:`\\hat{\\bf{S}}` are the STFT of the multi-channel noisy speech and\
+ the single-channel enhanced speech, respectively.
+
+ For online streaming audio, we provide a *recursive method* :cite:`higuchi2017online` to update the
+ PSD matrices of speech and noise, respectively.
+
+ Args:
+ ref_channel (int, optional): Reference channel for beamforming. (Default: ``0``)
+ solution (str, optional): Solution to compute the MVDR beamforming weights.
+ Options: [``ref_channel``, ``stv_evd``, ``stv_power``]. (Default: ``ref_channel``)
+ multi_mask (bool, optional): If ``True``, only accepts multi-channel Time-Frequency masks. (Default: ``False``)
+ diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to the covariance matrix
+ of the noise. (Default: ``True``)
+ diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
+ It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
+ online (bool, optional): If ``True``, updates the MVDR beamforming weights based on
+ the previous covarience matrices. (Default: ``False``)
+
+ Note:
+ To improve the numerical stability, the input spectrogram will be converted to double precision
+ (``torch.complex128`` or ``torch.cdouble``) dtype for internal computation. The output spectrogram
+ is converted to the dtype of the input spectrogram to be compatible with other modules.
+
+ Note:
+ If you use ``stv_evd`` solution, the gradient of the same input may not be identical if the
+ eigenvalues of the PSD matrix are not distinct (i.e. some eigenvalues are close or identical).
+ """
+
+ def __init__(
+ self,
+ ref_channel: int = 0,
+ solution: str = "ref_channel",
+ multi_mask: bool = False,
+ diag_loading: bool = True,
+ diag_eps: float = 1e-7,
+ online: bool = False,
+ ):
+ super().__init__()
+ if solution not in [
+ "ref_channel",
+ "stv_evd",
+ "stv_power",
+ ]:
+ raise ValueError(
+ '`solution` must be one of ["ref_channel", "stv_evd", "stv_power"]. Given {}'.format(solution)
+ )
+ self.ref_channel = ref_channel
+ self.solution = solution
+ self.multi_mask = multi_mask
+ self.diag_loading = diag_loading
+ self.diag_eps = diag_eps
+ self.online = online
+ self.psd = PSD(multi_mask)
+
+ psd_s: torch.Tensor = torch.zeros(1)
+ psd_n: torch.Tensor = torch.zeros(1)
+ mask_sum_s: torch.Tensor = torch.zeros(1)
+ mask_sum_n: torch.Tensor = torch.zeros(1)
+ self.register_buffer("psd_s", psd_s)
+ self.register_buffer("psd_n", psd_n)
+ self.register_buffer("mask_sum_s", mask_sum_s)
+ self.register_buffer("mask_sum_n", mask_sum_n)
+
+ def _get_updated_mvdr_vector(
+ self,
+ psd_s: torch.Tensor,
+ psd_n: torch.Tensor,
+ mask_s: torch.Tensor,
+ mask_n: torch.Tensor,
+ reference_vector: torch.Tensor,
+ solution: str = "ref_channel",
+ diagonal_loading: bool = True,
+ diag_eps: float = 1e-7,
+ eps: float = 1e-8,
+ ) -> torch.Tensor:
+ r"""Recursively update the MVDR beamforming vector.
+
+ Args:
+ psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ mask_s (torch.Tensor): Time-Frequency mask of the target speech.
+ Tensor with dimensions `(..., freq, time)` if multi_mask is ``False``
+ or with dimensions `(..., channel, freq, time)` if multi_mask is ``True``.
+ mask_n (torch.Tensor or None, optional): Time-Frequency mask of the noise.
+ Tensor with dimensions `(..., freq, time)` if multi_mask is ``False``
+ or with dimensions `(..., channel, freq, time)` if multi_mask is ``True``.
+ reference_vector (torch.Tensor): One-hot reference channel matrix.
+ solution (str, optional): Solution to compute the MVDR beamforming weights.
+ Options: [``ref_channel``, ``stv_evd``, ``stv_power``]. (Default: ``ref_channel``)
+ diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
+ (Default: ``True``)
+ diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
+ It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
+ eps (float, optional): Value to add to the denominator in the beamforming weight formula.
+ (Default: ``1e-8``)
+
+ Returns:
+ torch.Tensor: The MVDR beamforming weight matrix.
+ """
+ if self.multi_mask:
+ # Averaging mask along channel dimension
+ mask_s = mask_s.mean(dim=-3) # (..., freq, time)
+ mask_n = mask_n.mean(dim=-3) # (..., freq, time)
+ if self.psd_s.ndim == 1:
+ self.psd_s = psd_s
+ self.psd_n = psd_n
+ self.mask_sum_s = mask_s.sum(dim=-1)
+ self.mask_sum_n = mask_n.sum(dim=-1)
+ return _get_mvdr_vector(psd_s, psd_n, reference_vector, solution, diagonal_loading, diag_eps, eps)
+ else:
+ psd_s = self._get_updated_psd_speech(psd_s, mask_s)
+ psd_n = self._get_updated_psd_noise(psd_n, mask_n)
+ self.psd_s = psd_s
+ self.psd_n = psd_n
+ self.mask_sum_s = self.mask_sum_s + mask_s.sum(dim=-1)
+ self.mask_sum_n = self.mask_sum_n + mask_n.sum(dim=-1)
+ return _get_mvdr_vector(psd_s, psd_n, reference_vector, solution, diagonal_loading, diag_eps, eps)
+
+ def _get_updated_psd_speech(self, psd_s: torch.Tensor, mask_s: torch.Tensor) -> torch.Tensor:
+ r"""Update psd of speech recursively.
+
+ Args:
+ psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ mask_s (torch.Tensor): Time-Frequency mask of the target speech.
+ Tensor with dimensions `(..., freq, time)`.
+
+ Returns:
+ torch.Tensor: The updated PSD matrix of target speech.
+ """
+ numerator = self.mask_sum_s / (self.mask_sum_s + mask_s.sum(dim=-1))
+ denominator = 1 / (self.mask_sum_s + mask_s.sum(dim=-1))
+ psd_s = self.psd_s * numerator[..., None, None] + psd_s * denominator[..., None, None]
+ return psd_s
+
+ def _get_updated_psd_noise(self, psd_n: torch.Tensor, mask_n: torch.Tensor) -> torch.Tensor:
+ r"""Update psd of noise recursively.
+
+ Args:
+ psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ mask_n (torch.Tensor or None, optional): Time-Frequency mask of the noise.
+ Tensor with dimensions `(..., freq, time)`.
+
+ Returns:
+ torch.Tensor: The updated PSD matrix of noise.
+ """
+ numerator = self.mask_sum_n / (self.mask_sum_n + mask_n.sum(dim=-1))
+ denominator = 1 / (self.mask_sum_n + mask_n.sum(dim=-1))
+ psd_n = self.psd_n * numerator[..., None, None] + psd_n * denominator[..., None, None]
+ return psd_n
+
+ def forward(
+ self, specgram: torch.Tensor, mask_s: torch.Tensor, mask_n: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ """Perform MVDR beamforming.
+
+ Args:
+ specgram (torch.Tensor): Multi-channel complex-valued spectrum.
+ Tensor with dimensions `(..., channel, freq, time)`
+ mask_s (torch.Tensor): Time-Frequency mask of target speech.
+ Tensor with dimensions `(..., freq, time)` if multi_mask is ``False``
+ or with dimensions `(..., channel, freq, time)` if multi_mask is ``True``.
+ mask_n (torch.Tensor or None, optional): Time-Frequency mask of noise.
+ Tensor with dimensions `(..., freq, time)` if multi_mask is ``False``
+ or with dimensions `(..., channel, freq, time)` if multi_mask is ``True``.
+ (Default: None)
+
+ Returns:
+ torch.Tensor: Single-channel complex-valued enhanced spectrum with dimensions `(..., freq, time)`.
+ """
+ dtype = specgram.dtype
+ if specgram.ndim < 3:
+ raise ValueError(f"Expected at least 3D tensor (..., channel, freq, time). Found: {specgram.shape}")
+ if not specgram.is_complex():
+ raise ValueError(
+ f"The type of ``specgram`` tensor must be ``torch.cfloat`` or ``torch.cdouble``.\
+ Found: {specgram.dtype}"
+ )
+ if specgram.dtype == torch.cfloat:
+ specgram = specgram.cdouble() # Convert specgram to ``torch.cdouble``.
+
+ if mask_n is None:
+ warnings.warn("``mask_n`` is not provided, use ``1 - mask_s`` as ``mask_n``.")
+ mask_n = 1 - mask_s
+
+ psd_s = self.psd(specgram, mask_s) # (..., freq, time, channel, channel)
+ psd_n = self.psd(specgram, mask_n) # (..., freq, time, channel, channel)
+
+ u = torch.zeros(specgram.size()[:-2], device=specgram.device, dtype=torch.cdouble) # (..., channel)
+ u[..., self.ref_channel].fill_(1)
+
+ if self.online:
+ w_mvdr = self._get_updated_mvdr_vector(
+ psd_s, psd_n, mask_s, mask_n, u, self.solution, self.diag_loading, self.diag_eps
+ )
+ else:
+ w_mvdr = _get_mvdr_vector(psd_s, psd_n, u, self.solution, self.diag_loading, self.diag_eps)
+
+ specgram_enhanced = F.apply_beamforming(w_mvdr, specgram)
+
+ return specgram_enhanced.to(dtype)
+
+
+class RTFMVDR(torch.nn.Module):
+ r"""Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) module
+ based on the relative transfer function (RTF) and power spectral density (PSD) matrix of noise.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Given the multi-channel complex-valued spectrum :math:`\textbf{Y}`, the relative transfer function (RTF) matrix
+ or the steering vector of target speech :math:`\bm{v}`, the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and
+ a one-hot vector that represents the reference channel :math:`\bf{u}`, the module computes the single-channel
+ complex-valued spectrum of the enhanced speech :math:`\hat{\textbf{S}}`. The formula is defined as:
+
+ .. math::
+ \hat{\textbf{S}}(f) = \textbf{w}_{\text{bf}}(f)^{\mathsf{H}} \textbf{Y}(f)
+
+ where :math:`\textbf{w}_{\text{bf}}(f)` is the MVDR beamforming weight for the :math:`f`-th frequency bin,
+ :math:`(.)^{\mathsf{H}}` denotes the Hermitian Conjugate operation.
+
+ The beamforming weight is computed by:
+
+ .. math::
+ \textbf{w}_{\text{MVDR}}(f) =
+ \frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}}
+ {{\bm{v}^{\mathsf{H}}}(f){\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}
+ """
+
+ def forward(
+ self,
+ specgram: Tensor,
+ rtf: Tensor,
+ psd_n: Tensor,
+ reference_channel: Union[int, Tensor],
+ diagonal_loading: bool = True,
+ diag_eps: float = 1e-7,
+ eps: float = 1e-8,
+ ) -> Tensor:
+ """
+ Args:
+ specgram (torch.Tensor): Multi-channel complex-valued spectrum.
+ Tensor with dimensions `(..., channel, freq, time)`
+ rtf (torch.Tensor): The complex-valued RTF vector of target speech.
+ Tensor with dimensions `(..., freq, channel)`.
+ psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ reference_channel (int or torch.Tensor): Specifies the reference channel.
+ If the dtype is ``int``, it represents the reference channel index.
+ If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
+ is one-hot.
+ diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
+ (Default: ``True``)
+ diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
+ It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
+ eps (float, optional): Value to add to the denominator in the beamforming weight formula.
+ (Default: ``1e-8``)
+
+ Returns:
+ torch.Tensor: Single-channel complex-valued enhanced spectrum with dimensions `(..., freq, time)`.
+ """
+ w_mvdr = F.mvdr_weights_rtf(rtf, psd_n, reference_channel, diagonal_loading, diag_eps, eps)
+ spectrum_enhanced = F.apply_beamforming(w_mvdr, specgram)
+ return spectrum_enhanced
+
+
+class SoudenMVDR(torch.nn.Module):
+ r"""Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) module
+ based on the method proposed by *Souden et, al.* :cite:`souden2009optimal`.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Given the multi-channel complex-valued spectrum :math:`\textbf{Y}`, the power spectral density (PSD) matrix
+ of target speech :math:`\bf{\Phi}_{\textbf{SS}}`, the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and
+ a one-hot vector that represents the reference channel :math:`\bf{u}`, the module computes the single-channel
+ complex-valued spectrum of the enhanced speech :math:`\hat{\textbf{S}}`. The formula is defined as:
+
+ .. math::
+ \hat{\textbf{S}}(f) = \textbf{w}_{\text{bf}}(f)^{\mathsf{H}} \textbf{Y}(f)
+
+ where :math:`\textbf{w}_{\text{bf}}(f)` is the MVDR beamforming weight for the :math:`f`-th frequency bin.
+
+ The beamforming weight is computed by:
+
+ .. math::
+ \textbf{w}_{\text{MVDR}}(f) =
+ \frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bf{\Phi}_{\textbf{SS}}}}(f)}
+ {\text{Trace}({{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f) \bf{\Phi}_{\textbf{SS}}}(f))}}\bm{u}
+ """
+
+ def forward(
+ self,
+ specgram: Tensor,
+ psd_s: Tensor,
+ psd_n: Tensor,
+ reference_channel: Union[int, Tensor],
+ diagonal_loading: bool = True,
+ diag_eps: float = 1e-7,
+ eps: float = 1e-8,
+ ) -> torch.Tensor:
+ """
+ Args:
+ specgram (torch.Tensor): Multi-channel complex-valued spectrum.
+ Tensor with dimensions `(..., channel, freq, time)`.
+ psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
+ Tensor with dimensions `(..., freq, channel, channel)`.
+ reference_channel (int or torch.Tensor): Specifies the reference channel.
+ If the dtype is ``int``, it represents the reference channel index.
+ If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
+ is one-hot.
+ diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
+ (Default: ``True``)
+ diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
+ It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
+ eps (float, optional): Value to add to the denominator in the beamforming weight formula.
+ (Default: ``1e-8``)
+
+ Returns:
+ torch.Tensor: Single-channel complex-valued enhanced spectrum with dimensions `(..., freq, time)`.
+ """
+ w_mvdr = F.mvdr_weights_souden(psd_s, psd_n, reference_channel, diagonal_loading, diag_eps, eps)
+ spectrum_enhanced = F.apply_beamforming(w_mvdr, specgram)
+ return spectrum_enhanced
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/_transforms.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..242fd971a8d1efabb485a4cdbda2a8f1dbf59f02
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/transforms/_transforms.py
@@ -0,0 +1,2137 @@
+# -*- coding: utf-8 -*-
+
+import math
+import warnings
+from typing import Callable, Optional, Sequence, Tuple, Union
+
+import torch
+from torch import Tensor
+from torch.nn.modules.lazy import LazyModuleMixin
+from torch.nn.parameter import UninitializedParameter
+
+from torchaudio import functional as F
+from torchaudio.functional.functional import (
+ _apply_sinc_resample_kernel,
+ _check_convolve_mode,
+ _fix_waveform_shape,
+ _get_sinc_resample_kernel,
+ _stretch_waveform,
+)
+
+__all__ = []
+
+
+class Spectrogram(torch.nn.Module):
+ r"""Create a spectrogram from a audio signal.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
+ power (float or None, optional): Exponent for the magnitude spectrogram,
+ (must be > 0) e.g., 1 for magnitude, 2 for power, etc.
+ If None, then the complex spectrum is returned instead. (Default: ``2``)
+ normalized (bool or str, optional): Whether to normalize by magnitude after stft. If input is str, choices are
+ ``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to
+ ``"window"``. (Default: ``False``)
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
+ center (bool, optional): whether to pad :attr:`waveform` on both sides so
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
+ (Default: ``True``)
+ pad_mode (string, optional): controls the padding method used when
+ :attr:`center` is ``True``. (Default: ``"reflect"``)
+ onesided (bool, optional): controls whether to return half of results to
+ avoid redundancy (Default: ``True``)
+ return_complex (bool, optional):
+ Deprecated and not used.
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = torchaudio.transforms.Spectrogram(n_fft=800)
+ >>> spectrogram = transform(waveform)
+
+ """
+ __constants__ = ["n_fft", "win_length", "hop_length", "pad", "power", "normalized"]
+
+ def __init__(
+ self,
+ n_fft: int = 400,
+ win_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ pad: int = 0,
+ window_fn: Callable[..., Tensor] = torch.hann_window,
+ power: Optional[float] = 2.0,
+ normalized: Union[bool, str] = False,
+ wkwargs: Optional[dict] = None,
+ center: bool = True,
+ pad_mode: str = "reflect",
+ onesided: bool = True,
+ return_complex: Optional[bool] = None,
+ ) -> None:
+ super(Spectrogram, self).__init__()
+ torch._C._log_api_usage_once("torchaudio.transforms.Spectrogram")
+ self.n_fft = n_fft
+ # number of FFT bins. the returned STFT result will have n_fft // 2 + 1
+ # number of frequencies due to onesided=True in torch.stft
+ self.win_length = win_length if win_length is not None else n_fft
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
+ self.register_buffer("window", window)
+ self.pad = pad
+ self.power = power
+ self.normalized = normalized
+ self.center = center
+ self.pad_mode = pad_mode
+ self.onesided = onesided
+ if return_complex is not None:
+ warnings.warn(
+ "`return_complex` argument is now deprecated and is not effective."
+ "`torchaudio.transforms.Spectrogram(power=None)` always returns a tensor with "
+ "complex dtype. Please remove the argument in the function call."
+ )
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension (..., time).
+
+ Returns:
+ Tensor: Dimension (..., freq, time), where freq is
+ ``n_fft // 2 + 1`` where ``n_fft`` is the number of
+ Fourier bins, and time is the number of window hops (n_frame).
+ """
+ return F.spectrogram(
+ waveform,
+ self.pad,
+ self.window,
+ self.n_fft,
+ self.hop_length,
+ self.win_length,
+ self.power,
+ self.normalized,
+ self.center,
+ self.pad_mode,
+ self.onesided,
+ )
+
+
+class InverseSpectrogram(torch.nn.Module):
+ r"""Create an inverse spectrogram to recover an audio signal from a spectrogram.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
+ normalized (bool or str, optional): Whether the stft output was normalized by magnitude. If input is str,
+ choices are ``"window"`` and ``"frame_length"``, dependent on normalization mode. ``True`` maps to
+ ``"window"``. (Default: ``False``)
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
+ center (bool, optional): whether the signal in spectrogram was padded on both sides so
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
+ (Default: ``True``)
+ pad_mode (string, optional): controls the padding method used when
+ :attr:`center` is ``True``. (Default: ``"reflect"``)
+ onesided (bool, optional): controls whether spectrogram was used to return half of results to
+ avoid redundancy (Default: ``True``)
+
+ Example
+ >>> batch, freq, time = 2, 257, 100
+ >>> length = 25344
+ >>> spectrogram = torch.randn(batch, freq, time, dtype=torch.cdouble)
+ >>> transform = transforms.InverseSpectrogram(n_fft=512)
+ >>> waveform = transform(spectrogram, length)
+ """
+ __constants__ = ["n_fft", "win_length", "hop_length", "pad", "power", "normalized"]
+
+ def __init__(
+ self,
+ n_fft: int = 400,
+ win_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ pad: int = 0,
+ window_fn: Callable[..., Tensor] = torch.hann_window,
+ normalized: Union[bool, str] = False,
+ wkwargs: Optional[dict] = None,
+ center: bool = True,
+ pad_mode: str = "reflect",
+ onesided: bool = True,
+ ) -> None:
+ super(InverseSpectrogram, self).__init__()
+ self.n_fft = n_fft
+ # number of FFT bins. the returned STFT result will have n_fft // 2 + 1
+ # number of frequencies due to onesided=True in torch.stft
+ self.win_length = win_length if win_length is not None else n_fft
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
+ self.register_buffer("window", window)
+ self.pad = pad
+ self.normalized = normalized
+ self.center = center
+ self.pad_mode = pad_mode
+ self.onesided = onesided
+
+ def forward(self, spectrogram: Tensor, length: Optional[int] = None) -> Tensor:
+ r"""
+ Args:
+ spectrogram (Tensor): Complex tensor of audio of dimension (..., freq, time).
+ length (int or None, optional): The output length of the waveform.
+
+ Returns:
+ Tensor: Dimension (..., time), Least squares estimation of the original signal.
+ """
+ return F.inverse_spectrogram(
+ spectrogram,
+ length,
+ self.pad,
+ self.window,
+ self.n_fft,
+ self.hop_length,
+ self.win_length,
+ self.normalized,
+ self.center,
+ self.pad_mode,
+ self.onesided,
+ )
+
+
+class GriffinLim(torch.nn.Module):
+ r"""Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Implementation ported from
+ *librosa* :cite:`brian_mcfee-proc-scipy-2015`, *A fast Griffin-Lim algorithm* :cite:`6701851`
+ and *Signal estimation from modified short-time Fourier transform* :cite:`1172092`.
+
+ Args:
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
+ n_iter (int, optional): Number of iteration for phase recovery process. (Default: ``32``)
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
+ power (float, optional): Exponent for the magnitude spectrogram,
+ (must be > 0) e.g., 1 for magnitude, 2 for power, etc. (Default: ``2``)
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
+ momentum (float, optional): The momentum parameter for fast Griffin-Lim.
+ Setting this to 0 recovers the original Griffin-Lim method.
+ Values near 1 can lead to faster convergence, but above 1 may not converge. (Default: ``0.99``)
+ length (int, optional): Array length of the expected output. (Default: ``None``)
+ rand_init (bool, optional): Initializes phase randomly if True and to zero otherwise. (Default: ``True``)
+
+ Example
+ >>> batch, freq, time = 2, 257, 100
+ >>> spectrogram = torch.randn(batch, freq, time)
+ >>> transform = transforms.GriffinLim(n_fft=512)
+ >>> waveform = transform(spectrogram)
+ """
+ __constants__ = ["n_fft", "n_iter", "win_length", "hop_length", "power", "length", "momentum", "rand_init"]
+
+ def __init__(
+ self,
+ n_fft: int = 400,
+ n_iter: int = 32,
+ win_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ window_fn: Callable[..., Tensor] = torch.hann_window,
+ power: float = 2.0,
+ wkwargs: Optional[dict] = None,
+ momentum: float = 0.99,
+ length: Optional[int] = None,
+ rand_init: bool = True,
+ ) -> None:
+ super(GriffinLim, self).__init__()
+
+ if not (0 <= momentum < 1):
+ raise ValueError("momentum must be in the range [0, 1). Found: {}".format(momentum))
+
+ self.n_fft = n_fft
+ self.n_iter = n_iter
+ self.win_length = win_length if win_length is not None else n_fft
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
+ self.register_buffer("window", window)
+ self.length = length
+ self.power = power
+ self.momentum = momentum
+ self.rand_init = rand_init
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""
+ Args:
+ specgram (Tensor):
+ A magnitude-only STFT spectrogram of dimension (..., freq, frames)
+ where freq is ``n_fft // 2 + 1``.
+
+ Returns:
+ Tensor: waveform of (..., time), where time equals the ``length`` parameter if given.
+ """
+ return F.griffinlim(
+ specgram,
+ self.window,
+ self.n_fft,
+ self.hop_length,
+ self.win_length,
+ self.power,
+ self.n_iter,
+ self.momentum,
+ self.length,
+ self.rand_init,
+ )
+
+
+class AmplitudeToDB(torch.nn.Module):
+ r"""Turn a tensor from the power/amplitude scale to the decibel scale.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ This output depends on the maximum value in the input tensor, and so
+ may return different values for an audio clip split into snippets vs. a
+ a full clip.
+
+ Args:
+ stype (str, optional): scale of input tensor (``"power"`` or ``"magnitude"``). The
+ power being the elementwise square of the magnitude. (Default: ``"power"``)
+ top_db (float or None, optional): minimum negative cut-off in decibels. A reasonable
+ number is 80. (Default: ``None``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.AmplitudeToDB(stype="amplitude", top_db=80)
+ >>> waveform_db = transform(waveform)
+ """
+ __constants__ = ["multiplier", "amin", "ref_value", "db_multiplier"]
+
+ def __init__(self, stype: str = "power", top_db: Optional[float] = None) -> None:
+ super(AmplitudeToDB, self).__init__()
+ self.stype = stype
+ if top_db is not None and top_db < 0:
+ raise ValueError("top_db must be positive value")
+ self.top_db = top_db
+ self.multiplier = 10.0 if stype == "power" else 20.0
+ self.amin = 1e-10
+ self.ref_value = 1.0
+ self.db_multiplier = math.log10(max(self.amin, self.ref_value))
+
+ def forward(self, x: Tensor) -> Tensor:
+ r"""Numerically stable implementation from Librosa.
+
+ https://librosa.org/doc/latest/generated/librosa.amplitude_to_db.html
+
+ Args:
+ x (Tensor): Input tensor before being converted to decibel scale.
+
+ Returns:
+ Tensor: Output tensor in decibel scale.
+ """
+ return F.amplitude_to_DB(x, self.multiplier, self.amin, self.db_multiplier, self.top_db)
+
+
+class MelScale(torch.nn.Module):
+ r"""Turn a normal STFT into a mel frequency STFT with triangular filter banks.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
+ f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``)
+ n_stft (int, optional): Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`. (Default: ``201``)
+ norm (str or None, optional): If ``"slaney"``, divide the triangular mel weights by the width of the mel band
+ (area normalization). (Default: ``None``)
+ mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> spectrogram_transform = transforms.Spectrogram(n_fft=1024)
+ >>> spectrogram = spectrogram_transform(waveform)
+ >>> melscale_transform = transforms.MelScale(sample_rate=sample_rate, n_stft=1024 // 2 + 1)
+ >>> melscale_spectrogram = melscale_transform(spectrogram)
+
+ See also:
+ :py:func:`torchaudio.functional.melscale_fbanks` - The function used to
+ generate the filter banks.
+ """
+ __constants__ = ["n_mels", "sample_rate", "f_min", "f_max"]
+
+ def __init__(
+ self,
+ n_mels: int = 128,
+ sample_rate: int = 16000,
+ f_min: float = 0.0,
+ f_max: Optional[float] = None,
+ n_stft: int = 201,
+ norm: Optional[str] = None,
+ mel_scale: str = "htk",
+ ) -> None:
+ super(MelScale, self).__init__()
+ self.n_mels = n_mels
+ self.sample_rate = sample_rate
+ self.f_max = f_max if f_max is not None else float(sample_rate // 2)
+ self.f_min = f_min
+ self.norm = norm
+ self.mel_scale = mel_scale
+
+ if f_min > self.f_max:
+ raise ValueError("Require f_min: {} <= f_max: {}".format(f_min, self.f_max))
+
+ fb = F.melscale_fbanks(n_stft, self.f_min, self.f_max, self.n_mels, self.sample_rate, self.norm, self.mel_scale)
+ self.register_buffer("fb", fb)
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""
+ Args:
+ specgram (Tensor): A spectrogram STFT of dimension (..., freq, time).
+
+ Returns:
+ Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time).
+ """
+
+ # (..., time, freq) dot (freq, n_mels) -> (..., n_mels, time)
+ mel_specgram = torch.matmul(specgram.transpose(-1, -2), self.fb).transpose(-1, -2)
+
+ return mel_specgram
+
+
+class InverseMelScale(torch.nn.Module):
+ r"""Estimate a STFT in normal frequency domain from mel frequency domain.
+
+ .. devices:: CPU CUDA
+
+ It minimizes the euclidian norm between the input mel-spectrogram and the product between
+ the estimated spectrogram and the filter banks using `torch.linalg.lstsq`.
+
+ Args:
+ n_stft (int): Number of bins in STFT. See ``n_fft`` in :class:`Spectrogram`.
+ n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
+ f_max (float or None, optional): Maximum frequency. (Default: ``sample_rate // 2``)
+ norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band
+ (area normalization). (Default: ``None``)
+ mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
+ driver (str, optional): Name of the LAPACK/MAGMA method to be used for `torch.lstsq`.
+ For CPU inputs the valid values are ``"gels"``, ``"gelsy"``, ``"gelsd"``, ``"gelss"``.
+ For CUDA input, the only valid driver is ``"gels"``, which assumes that A is full-rank.
+ (Default: ``"gels``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> mel_spectrogram_transform = transforms.MelSpectrogram(sample_rate, n_fft=1024)
+ >>> mel_spectrogram = mel_spectrogram_transform(waveform)
+ >>> inverse_melscale_transform = transforms.InverseMelScale(n_stft=1024 // 2 + 1)
+ >>> spectrogram = inverse_melscale_transform(mel_spectrogram)
+ """
+ __constants__ = [
+ "n_stft",
+ "n_mels",
+ "sample_rate",
+ "f_min",
+ "f_max",
+ ]
+
+ def __init__(
+ self,
+ n_stft: int,
+ n_mels: int = 128,
+ sample_rate: int = 16000,
+ f_min: float = 0.0,
+ f_max: Optional[float] = None,
+ norm: Optional[str] = None,
+ mel_scale: str = "htk",
+ driver: str = "gels",
+ ) -> None:
+ super(InverseMelScale, self).__init__()
+ self.n_mels = n_mels
+ self.sample_rate = sample_rate
+ self.f_max = f_max or float(sample_rate // 2)
+ self.f_min = f_min
+ self.driver = driver
+
+ if f_min > self.f_max:
+ raise ValueError("Require f_min: {} <= f_max: {}".format(f_min, self.f_max))
+
+ if driver not in ["gels", "gelsy", "gelsd", "gelss"]:
+ raise ValueError(f'driver must be one of ["gels", "gelsy", "gelsd", "gelss"]. Found {driver}.')
+
+ fb = F.melscale_fbanks(n_stft, self.f_min, self.f_max, self.n_mels, self.sample_rate, norm, mel_scale)
+ self.register_buffer("fb", fb)
+
+ def forward(self, melspec: Tensor) -> Tensor:
+ r"""
+ Args:
+ melspec (Tensor): A Mel frequency spectrogram of dimension (..., ``n_mels``, time)
+
+ Returns:
+ Tensor: Linear scale spectrogram of size (..., freq, time)
+ """
+ # pack batch
+ shape = melspec.size()
+ melspec = melspec.view(-1, shape[-2], shape[-1])
+
+ n_mels, time = shape[-2], shape[-1]
+ freq, _ = self.fb.size() # (freq, n_mels)
+ if self.n_mels != n_mels:
+ raise ValueError("Expected an input with {} mel bins. Found: {}".format(self.n_mels, n_mels))
+
+ specgram = torch.relu(torch.linalg.lstsq(self.fb.transpose(-1, -2)[None], melspec, driver=self.driver).solution)
+
+ # unpack batch
+ specgram = specgram.view(shape[:-2] + (freq, time))
+ return specgram
+
+
+class MelSpectrogram(torch.nn.Module):
+ r"""Create MelSpectrogram for a raw audio signal.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ This is a composition of :py:func:`torchaudio.transforms.Spectrogram`
+ and :py:func:`torchaudio.transforms.MelScale`.
+
+ Sources
+ * https://gist.github.com/kastnerkyle/179d6e9a88202ab0a2fe
+ * https://timsainb.github.io/spectrograms-mfccs-and-inversion-in-python.html
+ * http://haythamfayek.com/2016/04/21/speech-processing-for-machine-learning.html
+
+ Args:
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
+ f_max (float or None, optional): Maximum frequency. (Default: ``None``)
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
+ n_mels (int, optional): Number of mel filterbanks. (Default: ``128``)
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
+ power (float, optional): Exponent for the magnitude spectrogram,
+ (must be > 0) e.g., 1 for magnitude, 2 for power, etc. (Default: ``2``)
+ normalized (bool, optional): Whether to normalize by magnitude after stft. (Default: ``False``)
+ wkwargs (Dict[..., ...] or None, optional): Arguments for window function. (Default: ``None``)
+ center (bool, optional): whether to pad :attr:`waveform` on both sides so
+ that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
+ (Default: ``True``)
+ pad_mode (string, optional): controls the padding method used when
+ :attr:`center` is ``True``. (Default: ``"reflect"``)
+ onesided: Deprecated and unused.
+ norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band
+ (area normalization). (Default: ``None``)
+ mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.MelSpectrogram(sample_rate)
+ >>> mel_specgram = transform(waveform) # (channel, n_mels, time)
+
+ See also:
+ :py:func:`torchaudio.functional.melscale_fbanks` - The function used to
+ generate the filter banks.
+ """
+ __constants__ = ["sample_rate", "n_fft", "win_length", "hop_length", "pad", "n_mels", "f_min"]
+
+ def __init__(
+ self,
+ sample_rate: int = 16000,
+ n_fft: int = 400,
+ win_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ f_min: float = 0.0,
+ f_max: Optional[float] = None,
+ pad: int = 0,
+ n_mels: int = 128,
+ window_fn: Callable[..., Tensor] = torch.hann_window,
+ power: float = 2.0,
+ normalized: bool = False,
+ wkwargs: Optional[dict] = None,
+ center: bool = True,
+ pad_mode: str = "reflect",
+ onesided: Optional[bool] = None,
+ norm: Optional[str] = None,
+ mel_scale: str = "htk",
+ ) -> None:
+ super(MelSpectrogram, self).__init__()
+ torch._C._log_api_usage_once("torchaudio.transforms.MelSpectrogram")
+
+ if onesided is not None:
+ warnings.warn(
+ "Argument 'onesided' has been deprecated and has no influence on the behavior of this module."
+ )
+
+ self.sample_rate = sample_rate
+ self.n_fft = n_fft
+ self.win_length = win_length if win_length is not None else n_fft
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
+ self.pad = pad
+ self.power = power
+ self.normalized = normalized
+ self.n_mels = n_mels # number of mel frequency bins
+ self.f_max = f_max
+ self.f_min = f_min
+ self.spectrogram = Spectrogram(
+ n_fft=self.n_fft,
+ win_length=self.win_length,
+ hop_length=self.hop_length,
+ pad=self.pad,
+ window_fn=window_fn,
+ power=self.power,
+ normalized=self.normalized,
+ wkwargs=wkwargs,
+ center=center,
+ pad_mode=pad_mode,
+ onesided=True,
+ )
+ self.mel_scale = MelScale(
+ self.n_mels, self.sample_rate, self.f_min, self.f_max, self.n_fft // 2 + 1, norm, mel_scale
+ )
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension (..., time).
+
+ Returns:
+ Tensor: Mel frequency spectrogram of size (..., ``n_mels``, time).
+ """
+ specgram = self.spectrogram(waveform)
+ mel_specgram = self.mel_scale(specgram)
+ return mel_specgram
+
+
+class MFCC(torch.nn.Module):
+ r"""Create the Mel-frequency cepstrum coefficients from an audio signal.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ By default, this calculates the MFCC on the DB-scaled Mel spectrogram.
+ This is not the textbook implementation, but is implemented here to
+ give consistency with librosa.
+
+ This output depends on the maximum value in the input spectrogram, and so
+ may return different values for an audio clip split into snippets vs. a
+ a full clip.
+
+ Args:
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
+ n_mfcc (int, optional): Number of mfc coefficients to retain. (Default: ``40``)
+ dct_type (int, optional): type of DCT (discrete cosine transform) to use. (Default: ``2``)
+ norm (str, optional): norm to use. (Default: ``"ortho"``)
+ log_mels (bool, optional): whether to use log-mel spectrograms instead of db-scaled. (Default: ``False``)
+ melkwargs (dict or None, optional): arguments for MelSpectrogram. (Default: ``None``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.MFCC(
+ >>> sample_rate=sample_rate,
+ >>> n_mfcc=13,
+ >>> melkwargs={"n_fft": 400, "hop_length": 160, "n_mels": 23, "center": False},
+ >>> )
+ >>> mfcc = transform(waveform)
+
+ See also:
+ :py:func:`torchaudio.functional.melscale_fbanks` - The function used to
+ generate the filter banks.
+ """
+ __constants__ = ["sample_rate", "n_mfcc", "dct_type", "top_db", "log_mels"]
+
+ def __init__(
+ self,
+ sample_rate: int = 16000,
+ n_mfcc: int = 40,
+ dct_type: int = 2,
+ norm: str = "ortho",
+ log_mels: bool = False,
+ melkwargs: Optional[dict] = None,
+ ) -> None:
+ super(MFCC, self).__init__()
+ supported_dct_types = [2]
+ if dct_type not in supported_dct_types:
+ raise ValueError("DCT type not supported: {}".format(dct_type))
+ self.sample_rate = sample_rate
+ self.n_mfcc = n_mfcc
+ self.dct_type = dct_type
+ self.norm = norm
+ self.top_db = 80.0
+ self.amplitude_to_DB = AmplitudeToDB("power", self.top_db)
+
+ melkwargs = melkwargs or {}
+ self.MelSpectrogram = MelSpectrogram(sample_rate=self.sample_rate, **melkwargs)
+
+ if self.n_mfcc > self.MelSpectrogram.n_mels:
+ raise ValueError("Cannot select more MFCC coefficients than # mel bins")
+ dct_mat = F.create_dct(self.n_mfcc, self.MelSpectrogram.n_mels, self.norm)
+ self.register_buffer("dct_mat", dct_mat)
+ self.log_mels = log_mels
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension (..., time).
+
+ Returns:
+ Tensor: specgram_mel_db of size (..., ``n_mfcc``, time).
+ """
+ mel_specgram = self.MelSpectrogram(waveform)
+ if self.log_mels:
+ log_offset = 1e-6
+ mel_specgram = torch.log(mel_specgram + log_offset)
+ else:
+ mel_specgram = self.amplitude_to_DB(mel_specgram)
+
+ # (..., time, n_mels) dot (n_mels, n_mfcc) -> (..., n_nfcc, time)
+ mfcc = torch.matmul(mel_specgram.transpose(-1, -2), self.dct_mat).transpose(-1, -2)
+ return mfcc
+
+
+class LFCC(torch.nn.Module):
+ r"""Create the linear-frequency cepstrum coefficients from an audio signal.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ By default, this calculates the LFCC on the DB-scaled linear filtered spectrogram.
+ This is not the textbook implementation, but is implemented here to
+ give consistency with librosa.
+
+ This output depends on the maximum value in the input spectrogram, and so
+ may return different values for an audio clip split into snippets vs. a
+ a full clip.
+
+ Args:
+ sample_rate (int, optional): Sample rate of audio signal. (Default: ``16000``)
+ n_filter (int, optional): Number of linear filters to apply. (Default: ``128``)
+ n_lfcc (int, optional): Number of lfc coefficients to retain. (Default: ``40``)
+ f_min (float, optional): Minimum frequency. (Default: ``0.``)
+ f_max (float or None, optional): Maximum frequency. (Default: ``None``)
+ dct_type (int, optional): type of DCT (discrete cosine transform) to use. (Default: ``2``)
+ norm (str, optional): norm to use. (Default: ``"ortho"``)
+ log_lf (bool, optional): whether to use log-lf spectrograms instead of db-scaled. (Default: ``False``)
+ speckwargs (dict or None, optional): arguments for Spectrogram. (Default: ``None``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.LFCC(
+ >>> sample_rate=sample_rate,
+ >>> n_lfcc=13,
+ >>> speckwargs={"n_fft": 400, "hop_length": 160, "center": False},
+ >>> )
+ >>> lfcc = transform(waveform)
+
+ See also:
+ :py:func:`torchaudio.functional.linear_fbanks` - The function used to
+ generate the filter banks.
+ """
+ __constants__ = ["sample_rate", "n_filter", "n_lfcc", "dct_type", "top_db", "log_lf"]
+
+ def __init__(
+ self,
+ sample_rate: int = 16000,
+ n_filter: int = 128,
+ f_min: float = 0.0,
+ f_max: Optional[float] = None,
+ n_lfcc: int = 40,
+ dct_type: int = 2,
+ norm: str = "ortho",
+ log_lf: bool = False,
+ speckwargs: Optional[dict] = None,
+ ) -> None:
+ super(LFCC, self).__init__()
+ supported_dct_types = [2]
+ if dct_type not in supported_dct_types:
+ raise ValueError("DCT type not supported: {}".format(dct_type))
+ self.sample_rate = sample_rate
+ self.f_min = f_min
+ self.f_max = f_max if f_max is not None else float(sample_rate // 2)
+ self.n_filter = n_filter
+ self.n_lfcc = n_lfcc
+ self.dct_type = dct_type
+ self.norm = norm
+ self.top_db = 80.0
+ self.amplitude_to_DB = AmplitudeToDB("power", self.top_db)
+
+ speckwargs = speckwargs or {}
+ self.Spectrogram = Spectrogram(**speckwargs)
+
+ if self.n_lfcc > self.Spectrogram.n_fft:
+ raise ValueError("Cannot select more LFCC coefficients than # fft bins")
+
+ filter_mat = F.linear_fbanks(
+ n_freqs=self.Spectrogram.n_fft // 2 + 1,
+ f_min=self.f_min,
+ f_max=self.f_max,
+ n_filter=self.n_filter,
+ sample_rate=self.sample_rate,
+ )
+ self.register_buffer("filter_mat", filter_mat)
+
+ dct_mat = F.create_dct(self.n_lfcc, self.n_filter, self.norm)
+ self.register_buffer("dct_mat", dct_mat)
+ self.log_lf = log_lf
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension (..., time).
+
+ Returns:
+ Tensor: Linear Frequency Cepstral Coefficients of size (..., ``n_lfcc``, time).
+ """
+ specgram = self.Spectrogram(waveform)
+
+ # (..., time, freq) dot (freq, n_filter) -> (..., n_filter, time)
+ specgram = torch.matmul(specgram.transpose(-1, -2), self.filter_mat).transpose(-1, -2)
+
+ if self.log_lf:
+ log_offset = 1e-6
+ specgram = torch.log(specgram + log_offset)
+ else:
+ specgram = self.amplitude_to_DB(specgram)
+
+ # (..., time, n_filter) dot (n_filter, n_lfcc) -> (..., n_lfcc, time)
+ lfcc = torch.matmul(specgram.transpose(-1, -2), self.dct_mat).transpose(-1, -2)
+ return lfcc
+
+
+class MuLawEncoding(torch.nn.Module):
+ r"""Encode signal based on mu-law companding.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: TorchScript
+
+ For more info see the
+ `Wikipedia Entry `_
+
+ This algorithm assumes the signal has been scaled to between -1 and 1 and
+ returns a signal encoded with values from 0 to quantization_channels - 1
+
+ Args:
+ quantization_channels (int, optional): Number of channels. (Default: ``256``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = torchaudio.transforms.MuLawEncoding(quantization_channels=512)
+ >>> mulawtrans = transform(waveform)
+
+ """
+ __constants__ = ["quantization_channels"]
+
+ def __init__(self, quantization_channels: int = 256) -> None:
+ super(MuLawEncoding, self).__init__()
+ self.quantization_channels = quantization_channels
+
+ def forward(self, x: Tensor) -> Tensor:
+ r"""
+ Args:
+ x (Tensor): A signal to be encoded.
+
+ Returns:
+ Tensor: An encoded signal.
+ """
+ return F.mu_law_encoding(x, self.quantization_channels)
+
+
+class MuLawDecoding(torch.nn.Module):
+ r"""Decode mu-law encoded signal.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: TorchScript
+
+ For more info see the
+ `Wikipedia Entry `_
+
+ This expects an input with values between 0 and ``quantization_channels - 1``
+ and returns a signal scaled between -1 and 1.
+
+ Args:
+ quantization_channels (int, optional): Number of channels. (Default: ``256``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = torchaudio.transforms.MuLawDecoding(quantization_channels=512)
+ >>> mulawtrans = transform(waveform)
+ """
+ __constants__ = ["quantization_channels"]
+
+ def __init__(self, quantization_channels: int = 256) -> None:
+ super(MuLawDecoding, self).__init__()
+ self.quantization_channels = quantization_channels
+
+ def forward(self, x_mu: Tensor) -> Tensor:
+ r"""
+ Args:
+ x_mu (Tensor): A mu-law encoded signal which needs to be decoded.
+
+ Returns:
+ Tensor: The signal decoded.
+ """
+ return F.mu_law_decoding(x_mu, self.quantization_channels)
+
+
+class Resample(torch.nn.Module):
+ r"""Resample a signal from one frequency to another. A resampling method can be given.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Note:
+ If resampling on waveforms of higher precision than float32, there may be a small loss of precision
+ because the kernel is cached once as float32. If high precision resampling is important for your application,
+ the functional form will retain higher precision, but run slower because it does not cache the kernel.
+ Alternatively, you could rewrite a transform that caches a higher precision kernel.
+
+ Args:
+ orig_freq (int, optional): The original frequency of the signal. (Default: ``16000``)
+ new_freq (int, optional): The desired frequency. (Default: ``16000``)
+ resampling_method (str, optional): The resampling method to use.
+ Options: [``sinc_interp_hann``, ``sinc_interp_kaiser``] (Default: ``"sinc_interp_hann"``)
+ lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper
+ but less efficient. (Default: ``6``)
+ rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist.
+ Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``)
+ beta (float or None, optional): The shape parameter used for kaiser window.
+ dtype (torch.device, optional):
+ Determnines the precision that resampling kernel is pre-computed and cached. If not provided,
+ kernel is computed with ``torch.float64`` then cached as ``torch.float32``.
+ If you need higher precision, provide ``torch.float64``, and the pre-computed kernel is computed and
+ cached as ``torch.float64``. If you use resample with lower precision, then instead of providing this
+ providing this argument, please use ``Resample.to(dtype)``, so that the kernel generation is still
+ carried out on ``torch.float64``.
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.Resample(sample_rate, sample_rate/10)
+ >>> waveform = transform(waveform)
+ """
+
+ def __init__(
+ self,
+ orig_freq: int = 16000,
+ new_freq: int = 16000,
+ resampling_method: str = "sinc_interp_hann",
+ lowpass_filter_width: int = 6,
+ rolloff: float = 0.99,
+ beta: Optional[float] = None,
+ *,
+ dtype: Optional[torch.dtype] = None,
+ ) -> None:
+ super().__init__()
+
+ self.orig_freq = orig_freq
+ self.new_freq = new_freq
+ self.gcd = math.gcd(int(self.orig_freq), int(self.new_freq))
+ self.resampling_method = resampling_method
+ self.lowpass_filter_width = lowpass_filter_width
+ self.rolloff = rolloff
+ self.beta = beta
+
+ if self.orig_freq != self.new_freq:
+ kernel, self.width = _get_sinc_resample_kernel(
+ self.orig_freq,
+ self.new_freq,
+ self.gcd,
+ self.lowpass_filter_width,
+ self.rolloff,
+ self.resampling_method,
+ beta,
+ dtype=dtype,
+ )
+ self.register_buffer("kernel", kernel)
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension (..., time).
+
+ Returns:
+ Tensor: Output signal of dimension (..., time).
+ """
+ if self.orig_freq == self.new_freq:
+ return waveform
+ return _apply_sinc_resample_kernel(waveform, self.orig_freq, self.new_freq, self.gcd, self.kernel, self.width)
+
+
+class ComputeDeltas(torch.nn.Module):
+ r"""Compute delta coefficients of a tensor, usually a spectrogram.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ See `torchaudio.functional.compute_deltas` for more details.
+
+ Args:
+ win_length (int, optional): The window length used for computing delta. (Default: ``5``)
+ mode (str, optional): Mode parameter passed to padding. (Default: ``"replicate"``)
+ """
+ __constants__ = ["win_length"]
+
+ def __init__(self, win_length: int = 5, mode: str = "replicate") -> None:
+ super(ComputeDeltas, self).__init__()
+ self.win_length = win_length
+ self.mode = mode
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""
+ Args:
+ specgram (Tensor): Tensor of audio of dimension (..., freq, time).
+
+ Returns:
+ Tensor: Tensor of deltas of dimension (..., freq, time).
+ """
+ return F.compute_deltas(specgram, win_length=self.win_length, mode=self.mode)
+
+
+class TimeStretch(torch.nn.Module):
+ r"""Stretch stft in time without modifying pitch for a given rate.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Proposed in *SpecAugment* :cite:`specaugment`.
+
+ Args:
+ hop_length (int or None, optional): Length of hop between STFT windows.
+ (Default: ``n_fft // 2``, where ``n_fft == (n_freq - 1) * 2``)
+ n_freq (int, optional): number of filter banks from stft. (Default: ``201``)
+ fixed_rate (float or None, optional): rate to speed up or slow down by.
+ If None is provided, rate must be passed to the forward method. (Default: ``None``)
+
+ .. note::
+
+ The expected input is raw, complex-valued spectrogram.
+
+ Example
+ >>> spectrogram = torchaudio.transforms.Spectrogram(power=None)
+ >>> stretch = torchaudio.transforms.TimeStretch()
+ >>>
+ >>> original = spectrogram(waveform)
+ >>> stretched_1_2 = stretch(original, 1.2)
+ >>> stretched_0_9 = stretch(original, 0.9)
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_time_stretch.png
+ :width: 600
+ :alt: The visualization of stretched spectrograms.
+ """
+ __constants__ = ["fixed_rate"]
+
+ def __init__(self, hop_length: Optional[int] = None, n_freq: int = 201, fixed_rate: Optional[float] = None) -> None:
+ super(TimeStretch, self).__init__()
+
+ self.fixed_rate = fixed_rate
+
+ n_fft = (n_freq - 1) * 2
+ hop_length = hop_length if hop_length is not None else n_fft // 2
+ self.register_buffer("phase_advance", torch.linspace(0, math.pi * hop_length, n_freq)[..., None])
+
+ def forward(self, complex_specgrams: Tensor, overriding_rate: Optional[float] = None) -> Tensor:
+ r"""
+ Args:
+ complex_specgrams (Tensor):
+ A tensor of dimension `(..., freq, num_frame)` with complex dtype.
+ overriding_rate (float or None, optional): speed up to apply to this batch.
+ If no rate is passed, use ``self.fixed_rate``. (Default: ``None``)
+
+ Returns:
+ Tensor:
+ Stretched spectrogram. The resulting tensor is of the corresponding complex dtype
+ as the input spectrogram, and the number of frames is changed to ``ceil(num_frame / rate)``.
+ """
+ if not torch.is_complex(complex_specgrams):
+ warnings.warn(
+ "The input to TimeStretch must be complex type. "
+ "Providing non-complex tensor produces invalid results.",
+ stacklevel=4,
+ )
+
+ if overriding_rate is None:
+ if self.fixed_rate is None:
+ raise ValueError("If no fixed_rate is specified, must pass a valid rate to the forward method.")
+ rate = self.fixed_rate
+ else:
+ rate = overriding_rate
+ return F.phase_vocoder(complex_specgrams, rate, self.phase_advance)
+
+
+class Fade(torch.nn.Module):
+ r"""Add a fade in and/or fade out to an waveform.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ fade_in_len (int, optional): Length of fade-in (time frames). (Default: ``0``)
+ fade_out_len (int, optional): Length of fade-out (time frames). (Default: ``0``)
+ fade_shape (str, optional): Shape of fade. Must be one of: "quarter_sine",
+ ``"half_sine"``, ``"linear"``, ``"logarithmic"``, ``"exponential"``.
+ (Default: ``"linear"``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.Fade(fade_in_len=sample_rate, fade_out_len=2 * sample_rate, fade_shape="linear")
+ >>> faded_waveform = transform(waveform)
+ """
+
+ def __init__(self, fade_in_len: int = 0, fade_out_len: int = 0, fade_shape: str = "linear") -> None:
+ super(Fade, self).__init__()
+ self.fade_in_len = fade_in_len
+ self.fade_out_len = fade_out_len
+ self.fade_shape = fade_shape
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
+
+ Returns:
+ Tensor: Tensor of audio of dimension `(..., time)`.
+ """
+ waveform_length = waveform.size()[-1]
+ device = waveform.device
+ return self._fade_in(waveform_length, device) * self._fade_out(waveform_length, device) * waveform
+
+ def _fade_in(self, waveform_length: int, device: torch.device) -> Tensor:
+ fade = torch.linspace(0, 1, self.fade_in_len, device=device)
+ ones = torch.ones(waveform_length - self.fade_in_len, device=device)
+
+ if self.fade_shape == "linear":
+ fade = fade
+
+ if self.fade_shape == "exponential":
+ fade = torch.pow(2, (fade - 1)) * fade
+
+ if self.fade_shape == "logarithmic":
+ fade = torch.log10(0.1 + fade) + 1
+
+ if self.fade_shape == "quarter_sine":
+ fade = torch.sin(fade * math.pi / 2)
+
+ if self.fade_shape == "half_sine":
+ fade = torch.sin(fade * math.pi - math.pi / 2) / 2 + 0.5
+
+ return torch.cat((fade, ones)).clamp_(0, 1)
+
+ def _fade_out(self, waveform_length: int, device: torch.device) -> Tensor:
+ fade = torch.linspace(0, 1, self.fade_out_len, device=device)
+ ones = torch.ones(waveform_length - self.fade_out_len, device=device)
+
+ if self.fade_shape == "linear":
+ fade = -fade + 1
+
+ if self.fade_shape == "exponential":
+ fade = torch.pow(2, -fade) * (1 - fade)
+
+ if self.fade_shape == "logarithmic":
+ fade = torch.log10(1.1 - fade) + 1
+
+ if self.fade_shape == "quarter_sine":
+ fade = torch.sin(fade * math.pi / 2 + math.pi / 2)
+
+ if self.fade_shape == "half_sine":
+ fade = torch.sin(fade * math.pi + math.pi / 2) / 2 + 0.5
+
+ return torch.cat((ones, fade)).clamp_(0, 1)
+
+
+class _AxisMasking(torch.nn.Module):
+ r"""Apply masking to a spectrogram.
+
+ Args:
+ mask_param (int): Maximum possible length of the mask.
+ axis (int): What dimension the mask is applied on (assuming the tensor is 3D).
+ For frequency masking, axis = 1.
+ For time masking, axis = 2.
+ iid_masks (bool): Applies iid masks to each of the examples in the batch dimension.
+ This option is applicable only when the dimension of the input tensor is >= 3.
+ p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0)
+ """
+ __constants__ = ["mask_param", "axis", "iid_masks", "p"]
+
+ def __init__(self, mask_param: int, axis: int, iid_masks: bool, p: float = 1.0) -> None:
+ super(_AxisMasking, self).__init__()
+ self.mask_param = mask_param
+ self.axis = axis
+ self.iid_masks = iid_masks
+ self.p = p
+
+ def forward(self, specgram: Tensor, mask_value: float = 0.0) -> Tensor:
+ r"""
+ Args:
+ specgram (Tensor): Tensor of dimension `(..., freq, time)`.
+ mask_value (float): Value to assign to the masked columns.
+
+ Returns:
+ Tensor: Masked spectrogram of dimensions `(..., freq, time)`.
+ """
+ # if iid_masks flag marked and specgram has a batch dimension
+ # self.axis + specgram.dim() - 3 gives the time/frequency dimension (last two dimensions)
+ # for input tensor for which the dimension is not 3.
+ if self.iid_masks:
+ return F.mask_along_axis_iid(
+ specgram, self.mask_param, mask_value, self.axis + specgram.dim() - 3, p=self.p
+ )
+ else:
+ return F.mask_along_axis(specgram, self.mask_param, mask_value, self.axis + specgram.dim() - 3, p=self.p)
+
+
+class FrequencyMasking(_AxisMasking):
+ r"""Apply masking to a spectrogram in the frequency domain.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Proposed in *SpecAugment* :cite:`specaugment`.
+
+ Args:
+ freq_mask_param (int): maximum possible length of the mask.
+ Indices uniformly sampled from [0, freq_mask_param).
+ iid_masks (bool, optional): whether to apply different masks to each
+ example/channel in the batch. (Default: ``False``)
+ This option is applicable only when the input tensor >= 3D.
+
+ Example
+ >>> spectrogram = torchaudio.transforms.Spectrogram()
+ >>> masking = torchaudio.transforms.FrequencyMasking(freq_mask_param=80)
+ >>>
+ >>> original = spectrogram(waveform)
+ >>> masked = masking(original)
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_freq_masking1.png
+ :alt: The original spectrogram
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_freq_masking2.png
+ :alt: The spectrogram masked along frequency axis
+ """
+
+ def __init__(self, freq_mask_param: int, iid_masks: bool = False) -> None:
+ super(FrequencyMasking, self).__init__(freq_mask_param, 1, iid_masks)
+
+
+class TimeMasking(_AxisMasking):
+ r"""Apply masking to a spectrogram in the time domain.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Proposed in *SpecAugment* :cite:`specaugment`.
+
+ Args:
+ time_mask_param (int): maximum possible length of the mask.
+ Indices uniformly sampled from [0, time_mask_param).
+ iid_masks (bool, optional): whether to apply different masks to each
+ example/channel in the batch. (Default: ``False``)
+ This option is applicable only when the input tensor >= 3D.
+ p (float, optional): maximum proportion of time steps that can be masked.
+ Must be within range [0.0, 1.0]. (Default: 1.0)
+
+ Example
+ >>> spectrogram = torchaudio.transforms.Spectrogram()
+ >>> masking = torchaudio.transforms.TimeMasking(time_mask_param=80)
+ >>>
+ >>> original = spectrogram(waveform)
+ >>> masked = masking(original)
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_time_masking1.png
+ :alt: The original spectrogram
+
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/specaugment_time_masking2.png
+ :alt: The spectrogram masked along time axis
+ """
+
+ def __init__(self, time_mask_param: int, iid_masks: bool = False, p: float = 1.0) -> None:
+ if not 0.0 <= p <= 1.0:
+ raise ValueError(f"The value of p must be between 0.0 and 1.0 ({p} given).")
+ super(TimeMasking, self).__init__(time_mask_param, 2, iid_masks, p=p)
+
+
+class SpecAugment(torch.nn.Module):
+ r"""Apply time and frequency masking to a spectrogram.
+ Args:
+ n_time_masks (int): Number of time masks. If its value is zero, no time masking will be applied.
+ time_mask_param (int): Maximum possible length of the time mask.
+ n_freq_masks (int): Number of frequency masks. If its value is zero, no frequency masking will be applied.
+ freq_mask_param (int): Maximum possible length of the frequency mask.
+ iid_masks (bool, optional): Applies iid masks to each of the examples in the batch dimension.
+ This option is applicable only when the input tensor is 4D. (Default: ``True``)
+ p (float, optional): maximum proportion of time steps that can be masked.
+ Must be within range [0.0, 1.0]. (Default: 1.0)
+ zero_masking (bool, optional): If ``True``, use 0 as the mask value,
+ else use mean of the input tensor. (Default: ``False``)
+ """
+ __constants__ = [
+ "n_time_masks",
+ "time_mask_param",
+ "n_freq_masks",
+ "freq_mask_param",
+ "iid_masks",
+ "p",
+ "zero_masking",
+ ]
+
+ def __init__(
+ self,
+ n_time_masks: int,
+ time_mask_param: int,
+ n_freq_masks: int,
+ freq_mask_param: int,
+ iid_masks: bool = True,
+ p: float = 1.0,
+ zero_masking: bool = False,
+ ) -> None:
+ super(SpecAugment, self).__init__()
+ self.n_time_masks = n_time_masks
+ self.time_mask_param = time_mask_param
+ self.n_freq_masks = n_freq_masks
+ self.freq_mask_param = freq_mask_param
+ self.iid_masks = iid_masks
+ self.p = p
+ self.zero_masking = zero_masking
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""
+ Args:
+ specgram (Tensor): Tensor of shape `(..., freq, time)`.
+ Returns:
+ Tensor: Masked spectrogram of shape `(..., freq, time)`.
+ """
+ if self.zero_masking:
+ mask_value = 0.0
+ else:
+ mask_value = specgram.mean()
+ time_dim = specgram.dim() - 1
+ freq_dim = time_dim - 1
+
+ if specgram.dim() > 2 and self.iid_masks is True:
+ for _ in range(self.n_time_masks):
+ specgram = F.mask_along_axis_iid(specgram, self.time_mask_param, mask_value, time_dim, p=self.p)
+ for _ in range(self.n_freq_masks):
+ specgram = F.mask_along_axis_iid(specgram, self.freq_mask_param, mask_value, freq_dim, p=self.p)
+ else:
+ for _ in range(self.n_time_masks):
+ specgram = F.mask_along_axis(specgram, self.time_mask_param, mask_value, time_dim, p=self.p)
+ for _ in range(self.n_freq_masks):
+ specgram = F.mask_along_axis(specgram, self.freq_mask_param, mask_value, freq_dim, p=self.p)
+
+ return specgram
+
+
+class Loudness(torch.nn.Module):
+ r"""Measure audio loudness according to the ITU-R BS.1770-4 recommendation.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: TorchScript
+
+ Args:
+ sample_rate (int): Sample rate of audio signal.
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.Loudness(sample_rate)
+ >>> loudness = transform(waveform)
+
+ Reference:
+ - https://www.itu.int/rec/R-REC-BS.1770-4-201510-I/en
+ """
+ __constants__ = ["sample_rate"]
+
+ def __init__(self, sample_rate: int):
+ super(Loudness, self).__init__()
+ self.sample_rate = sample_rate
+
+ def forward(self, wavefrom: Tensor):
+ r"""
+ Args:
+ waveform(torch.Tensor): audio waveform of dimension `(..., channels, time)`
+
+ Returns:
+ Tensor: loudness estimates (LKFS)
+ """
+ return F.loudness(wavefrom, self.sample_rate)
+
+
+class Vol(torch.nn.Module):
+ r"""Adjust volume of waveform.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ gain (float): Interpreted according to the given gain_type:
+ If ``gain_type`` = ``amplitude``, ``gain`` is a positive amplitude ratio.
+ If ``gain_type`` = ``power``, ``gain`` is a power (voltage squared).
+ If ``gain_type`` = ``db``, ``gain`` is in decibels.
+ gain_type (str, optional): Type of gain. One of: ``amplitude``, ``power``, ``db`` (Default: ``amplitude``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.Vol(gain=0.5, gain_type="amplitude")
+ >>> quieter_waveform = transform(waveform)
+ """
+
+ def __init__(self, gain: float, gain_type: str = "amplitude"):
+ super(Vol, self).__init__()
+ self.gain = gain
+ self.gain_type = gain_type
+
+ if gain_type in ["amplitude", "power"] and gain < 0:
+ raise ValueError("If gain_type = amplitude or power, gain must be positive.")
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
+
+ Returns:
+ Tensor: Tensor of audio of dimension `(..., time)`.
+ """
+ if self.gain_type == "amplitude":
+ waveform = waveform * self.gain
+
+ if self.gain_type == "db":
+ waveform = F.gain(waveform, self.gain)
+
+ if self.gain_type == "power":
+ waveform = F.gain(waveform, 10 * math.log10(self.gain))
+
+ return torch.clamp(waveform, -1, 1)
+
+
+class SlidingWindowCmn(torch.nn.Module):
+ r"""
+ Apply sliding-window cepstral mean (and optionally variance) normalization per utterance.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ cmn_window (int, optional): Window in frames for running average CMN computation (int, default = 600)
+ min_cmn_window (int, optional): Minimum CMN window used at start of decoding (adds latency only at start).
+ Only applicable if center == false, ignored if center==true (int, default = 100)
+ center (bool, optional): If true, use a window centered on the current frame
+ (to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false)
+ norm_vars (bool, optional): If true, normalize variance to one. (bool, default = false)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.SlidingWindowCmn(cmn_window=1000)
+ >>> cmn_waveform = transform(waveform)
+ """
+
+ def __init__(
+ self, cmn_window: int = 600, min_cmn_window: int = 100, center: bool = False, norm_vars: bool = False
+ ) -> None:
+ super().__init__()
+ self.cmn_window = cmn_window
+ self.min_cmn_window = min_cmn_window
+ self.center = center
+ self.norm_vars = norm_vars
+
+ def forward(self, specgram: Tensor) -> Tensor:
+ r"""
+ Args:
+ specgram (Tensor): Tensor of spectrogram of dimension `(..., time, freq)`.
+
+ Returns:
+ Tensor: Tensor of spectrogram of dimension `(..., time, freq)`.
+ """
+ cmn_specgram = F.sliding_window_cmn(specgram, self.cmn_window, self.min_cmn_window, self.center, self.norm_vars)
+ return cmn_specgram
+
+
+class Vad(torch.nn.Module):
+ r"""Voice Activity Detector. Similar to SoX implementation.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: TorchScript
+
+ Attempts to trim silence and quiet background sounds from the ends of recordings of speech.
+ The algorithm currently uses a simple cepstral power measurement to detect voice,
+ so may be fooled by other things, especially music.
+
+ The effect can trim only from the front of the audio,
+ so in order to trim from the back, the reverse effect must also be used.
+
+ Args:
+ sample_rate (int): Sample rate of audio signal.
+ trigger_level (float, optional): The measurement level used to trigger activity detection.
+ This may need to be changed depending on the noise level, signal level,
+ and other characteristics of the input audio. (Default: 7.0)
+ trigger_time (float, optional): The time constant (in seconds)
+ used to help ignore short bursts of sound. (Default: 0.25)
+ search_time (float, optional): The amount of audio (in seconds)
+ to search for quieter/shorter bursts of audio to include prior
+ to the detected trigger point. (Default: 1.0)
+ allowed_gap (float, optional): The allowed gap (in seconds) between
+ quiteter/shorter bursts of audio to include prior
+ to the detected trigger point. (Default: 0.25)
+ pre_trigger_time (float, optional): The amount of audio (in seconds) to preserve
+ before the trigger point and any found quieter/shorter bursts. (Default: 0.0)
+ boot_time (float, optional) The algorithm (internally) uses adaptive noise
+ estimation/reduction in order to detect the start of the wanted audio.
+ This option sets the time for the initial noise estimate. (Default: 0.35)
+ noise_up_time (float, optional) Time constant used by the adaptive noise estimator
+ for when the noise level is increasing. (Default: 0.1)
+ noise_down_time (float, optional) Time constant used by the adaptive noise estimator
+ for when the noise level is decreasing. (Default: 0.01)
+ noise_reduction_amount (float, optional) Amount of noise reduction to use in
+ the detection algorithm (e.g. 0, 0.5, ...). (Default: 1.35)
+ measure_freq (float, optional) Frequency of the algorithm’s
+ processing/measurements. (Default: 20.0)
+ measure_duration: (float or None, optional) Measurement duration.
+ (Default: Twice the measurement period; i.e. with overlap.)
+ measure_smooth_time (float, optional) Time constant used to smooth
+ spectral measurements. (Default: 0.4)
+ hp_filter_freq (float, optional) "Brick-wall" frequency of high-pass filter applied
+ at the input to the detector algorithm. (Default: 50.0)
+ lp_filter_freq (float, optional) "Brick-wall" frequency of low-pass filter applied
+ at the input to the detector algorithm. (Default: 6000.0)
+ hp_lifter_freq (float, optional) "Brick-wall" frequency of high-pass lifter used
+ in the detector algorithm. (Default: 150.0)
+ lp_lifter_freq (float, optional) "Brick-wall" frequency of low-pass lifter used
+ in the detector algorithm. (Default: 2000.0)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> waveform_reversed, sample_rate = apply_effects_tensor(waveform, sample_rate, [["reverse"]])
+ >>> transform = transforms.Vad(sample_rate=sample_rate, trigger_level=7.5)
+ >>> waveform_reversed_front_trim = transform(waveform_reversed)
+ >>> waveform_end_trim, sample_rate = apply_effects_tensor(
+ >>> waveform_reversed_front_trim, sample_rate, [["reverse"]]
+ >>> )
+
+ Reference:
+ - http://sox.sourceforge.net/sox.html
+ """
+
+ def __init__(
+ self,
+ sample_rate: int,
+ trigger_level: float = 7.0,
+ trigger_time: float = 0.25,
+ search_time: float = 1.0,
+ allowed_gap: float = 0.25,
+ pre_trigger_time: float = 0.0,
+ boot_time: float = 0.35,
+ noise_up_time: float = 0.1,
+ noise_down_time: float = 0.01,
+ noise_reduction_amount: float = 1.35,
+ measure_freq: float = 20.0,
+ measure_duration: Optional[float] = None,
+ measure_smooth_time: float = 0.4,
+ hp_filter_freq: float = 50.0,
+ lp_filter_freq: float = 6000.0,
+ hp_lifter_freq: float = 150.0,
+ lp_lifter_freq: float = 2000.0,
+ ) -> None:
+ super().__init__()
+
+ self.sample_rate = sample_rate
+ self.trigger_level = trigger_level
+ self.trigger_time = trigger_time
+ self.search_time = search_time
+ self.allowed_gap = allowed_gap
+ self.pre_trigger_time = pre_trigger_time
+ self.boot_time = boot_time
+ self.noise_up_time = noise_up_time
+ self.noise_down_time = noise_down_time
+ self.noise_reduction_amount = noise_reduction_amount
+ self.measure_freq = measure_freq
+ self.measure_duration = measure_duration
+ self.measure_smooth_time = measure_smooth_time
+ self.hp_filter_freq = hp_filter_freq
+ self.lp_filter_freq = lp_filter_freq
+ self.hp_lifter_freq = hp_lifter_freq
+ self.lp_lifter_freq = lp_lifter_freq
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension `(channels, time)` or `(time)`
+ Tensor of shape `(channels, time)` is treated as a multi-channel recording
+ of the same event and the resulting output will be trimmed to the earliest
+ voice activity in any channel.
+ """
+ return F.vad(
+ waveform=waveform,
+ sample_rate=self.sample_rate,
+ trigger_level=self.trigger_level,
+ trigger_time=self.trigger_time,
+ search_time=self.search_time,
+ allowed_gap=self.allowed_gap,
+ pre_trigger_time=self.pre_trigger_time,
+ boot_time=self.boot_time,
+ noise_up_time=self.noise_up_time,
+ noise_down_time=self.noise_down_time,
+ noise_reduction_amount=self.noise_reduction_amount,
+ measure_freq=self.measure_freq,
+ measure_duration=self.measure_duration,
+ measure_smooth_time=self.measure_smooth_time,
+ hp_filter_freq=self.hp_filter_freq,
+ lp_filter_freq=self.lp_filter_freq,
+ hp_lifter_freq=self.hp_lifter_freq,
+ lp_lifter_freq=self.lp_lifter_freq,
+ )
+
+
+class SpectralCentroid(torch.nn.Module):
+ r"""Compute the spectral centroid for each channel along the time axis.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ The spectral centroid is defined as the weighted average of the
+ frequency values, weighted by their magnitude.
+
+ Args:
+ sample_rate (int): Sample rate of audio signal.
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins. (Default: ``400``)
+ win_length (int or None, optional): Window size. (Default: ``n_fft``)
+ hop_length (int or None, optional): Length of hop between STFT windows. (Default: ``win_length // 2``)
+ pad (int, optional): Two sided padding of signal. (Default: ``0``)
+ window_fn (Callable[..., Tensor], optional): A function to create a window tensor
+ that is applied/multiplied to each frame/window. (Default: ``torch.hann_window``)
+ wkwargs (dict or None, optional): Arguments for window function. (Default: ``None``)
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.SpectralCentroid(sample_rate)
+ >>> spectral_centroid = transform(waveform) # (channel, time)
+ """
+ __constants__ = ["sample_rate", "n_fft", "win_length", "hop_length", "pad"]
+
+ def __init__(
+ self,
+ sample_rate: int,
+ n_fft: int = 400,
+ win_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ pad: int = 0,
+ window_fn: Callable[..., Tensor] = torch.hann_window,
+ wkwargs: Optional[dict] = None,
+ ) -> None:
+ super(SpectralCentroid, self).__init__()
+ self.sample_rate = sample_rate
+ self.n_fft = n_fft
+ self.win_length = win_length if win_length is not None else n_fft
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 2
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
+ self.register_buffer("window", window)
+ self.pad = pad
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
+
+ Returns:
+ Tensor: Spectral Centroid of size `(..., time)`.
+ """
+
+ return F.spectral_centroid(
+ waveform, self.sample_rate, self.pad, self.window, self.n_fft, self.hop_length, self.win_length
+ )
+
+
+class PitchShift(LazyModuleMixin, torch.nn.Module):
+ r"""Shift the pitch of a waveform by ``n_steps`` steps.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: TorchScript
+
+ Args:
+ waveform (Tensor): The input waveform of shape `(..., time)`.
+ sample_rate (int): Sample rate of `waveform`.
+ n_steps (int): The (fractional) steps to shift `waveform`.
+ bins_per_octave (int, optional): The number of steps per octave (Default : ``12``).
+ n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins (Default: ``512``).
+ win_length (int or None, optional): Window size. If None, then ``n_fft`` is used. (Default: ``None``).
+ hop_length (int or None, optional): Length of hop between STFT windows. If None, then ``win_length // 4``
+ is used (Default: ``None``).
+ window (Tensor or None, optional): Window tensor that is applied/multiplied to each frame/window.
+ If None, then ``torch.hann_window(win_length)`` is used (Default: ``None``).
+
+ Example
+ >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
+ >>> transform = transforms.PitchShift(sample_rate, 4)
+ >>> waveform_shift = transform(waveform) # (channel, time)
+ """
+ __constants__ = ["sample_rate", "n_steps", "bins_per_octave", "n_fft", "win_length", "hop_length"]
+
+ kernel: UninitializedParameter
+ width: int
+
+ def __init__(
+ self,
+ sample_rate: int,
+ n_steps: int,
+ bins_per_octave: int = 12,
+ n_fft: int = 512,
+ win_length: Optional[int] = None,
+ hop_length: Optional[int] = None,
+ window_fn: Callable[..., Tensor] = torch.hann_window,
+ wkwargs: Optional[dict] = None,
+ ) -> None:
+ super().__init__()
+ self.n_steps = n_steps
+ self.bins_per_octave = bins_per_octave
+ self.sample_rate = sample_rate
+ self.n_fft = n_fft
+ self.win_length = win_length if win_length is not None else n_fft
+ self.hop_length = hop_length if hop_length is not None else self.win_length // 4
+ window = window_fn(self.win_length) if wkwargs is None else window_fn(self.win_length, **wkwargs)
+ self.register_buffer("window", window)
+ rate = 2.0 ** (-float(n_steps) / bins_per_octave)
+ self.orig_freq = int(sample_rate / rate)
+ self.gcd = math.gcd(int(self.orig_freq), int(sample_rate))
+
+ if self.orig_freq != sample_rate:
+ self.width = -1
+ self.kernel = UninitializedParameter(device=None, dtype=None)
+
+ def initialize_parameters(self, input):
+ if self.has_uninitialized_params():
+ if self.orig_freq != self.sample_rate:
+ with torch.no_grad():
+ kernel, self.width = _get_sinc_resample_kernel(
+ self.orig_freq,
+ self.sample_rate,
+ self.gcd,
+ dtype=input.dtype,
+ device=input.device,
+ )
+ self.kernel.materialize(kernel.shape)
+ self.kernel.copy_(kernel)
+
+ def forward(self, waveform: Tensor) -> Tensor:
+ r"""
+ Args:
+ waveform (Tensor): Tensor of audio of dimension `(..., time)`.
+
+ Returns:
+ Tensor: The pitch-shifted audio of shape `(..., time)`.
+ """
+ shape = waveform.size()
+
+ waveform_stretch = _stretch_waveform(
+ waveform,
+ self.n_steps,
+ self.bins_per_octave,
+ self.n_fft,
+ self.win_length,
+ self.hop_length,
+ self.window,
+ )
+
+ if self.orig_freq != self.sample_rate:
+ waveform_shift = _apply_sinc_resample_kernel(
+ waveform_stretch,
+ self.orig_freq,
+ self.sample_rate,
+ self.gcd,
+ self.kernel,
+ self.width,
+ )
+ else:
+ waveform_shift = waveform_stretch
+
+ return _fix_waveform_shape(
+ waveform_shift,
+ shape,
+ )
+
+
+class RNNTLoss(torch.nn.Module):
+ """Compute the RNN Transducer loss from *Sequence Transduction with Recurrent Neural Networks*
+ :cite:`graves2012sequence`.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ The RNN Transducer loss extends the CTC loss by defining a distribution over output
+ sequences of all lengths, and by jointly modelling both input-output and output-output
+ dependencies.
+
+ Args:
+ blank (int, optional): blank label (Default: ``-1``)
+ clamp (float, optional): clamp for gradients (Default: ``-1``)
+ reduction (string, optional): Specifies the reduction to apply to the output:
+ ``"none"`` | ``"mean"`` | ``"sum"``. (Default: ``"mean"``)
+ fused_log_softmax (bool): set to False if calling log_softmax outside of loss (Default: ``True``)
+
+ Example
+ >>> # Hypothetical values
+ >>> logits = torch.tensor([[[[0.1, 0.6, 0.1, 0.1, 0.1],
+ >>> [0.1, 0.1, 0.6, 0.1, 0.1],
+ >>> [0.1, 0.1, 0.2, 0.8, 0.1]],
+ >>> [[0.1, 0.6, 0.1, 0.1, 0.1],
+ >>> [0.1, 0.1, 0.2, 0.1, 0.1],
+ >>> [0.7, 0.1, 0.2, 0.1, 0.1]]]],
+ >>> dtype=torch.float32,
+ >>> requires_grad=True)
+ >>> targets = torch.tensor([[1, 2]], dtype=torch.int)
+ >>> logit_lengths = torch.tensor([2], dtype=torch.int)
+ >>> target_lengths = torch.tensor([2], dtype=torch.int)
+ >>> transform = transforms.RNNTLoss(blank=0)
+ >>> loss = transform(logits, targets, logit_lengths, target_lengths)
+ >>> loss.backward()
+ """
+
+ def __init__(
+ self,
+ blank: int = -1,
+ clamp: float = -1.0,
+ reduction: str = "mean",
+ fused_log_softmax: bool = True,
+ ):
+ super().__init__()
+ self.blank = blank
+ self.clamp = clamp
+ self.reduction = reduction
+ self.fused_log_softmax = fused_log_softmax
+
+ def forward(
+ self,
+ logits: Tensor,
+ targets: Tensor,
+ logit_lengths: Tensor,
+ target_lengths: Tensor,
+ ):
+ """
+ Args:
+ logits (Tensor): Tensor of dimension `(batch, max seq length, max target length + 1, class)`
+ containing output from joiner
+ targets (Tensor): Tensor of dimension `(batch, max target length)` containing targets with zero padded
+ logit_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of each sequence from encoder
+ target_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of targets for each sequence
+ Returns:
+ Tensor: Loss with the reduction option applied. If ``reduction`` is ``"none"``, then size (batch),
+ otherwise scalar.
+ """
+ return F.rnnt_loss(
+ logits,
+ targets,
+ logit_lengths,
+ target_lengths,
+ self.blank,
+ self.clamp,
+ self.reduction,
+ self.fused_log_softmax,
+ )
+
+
+class Convolve(torch.nn.Module):
+ r"""
+ Convolves inputs along their last dimension using the direct method.
+ Note that, in contrast to :class:`torch.nn.Conv1d`, which actually applies the valid cross-correlation
+ operator, this module applies the true `convolution`_ operator.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ mode (str, optional): Must be one of ("full", "valid", "same").
+
+ * "full": Returns the full convolution result, with shape `(..., N + M - 1)`, where
+ `N` and `M` are the trailing dimensions of the two inputs. (Default)
+ * "valid": Returns the segment of the full convolution result corresponding to where
+ the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
+ * "same": Returns the center segment of the full convolution result, with shape `(..., N)`.
+
+ .. _convolution:
+ https://en.wikipedia.org/wiki/Convolution
+ """
+
+ def __init__(self, mode: str = "full") -> None:
+ _check_convolve_mode(mode)
+
+ super().__init__()
+ self.mode = mode
+
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+ r"""
+ Args:
+ x (torch.Tensor): First convolution operand, with shape `(..., N)`.
+ y (torch.Tensor): Second convolution operand, with shape `(..., M)`
+ (leading dimensions must be broadcast-able with those of ``x``).
+
+ Returns:
+ torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
+ the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.
+ """
+ return F.convolve(x, y, mode=self.mode)
+
+
+class FFTConvolve(torch.nn.Module):
+ r"""
+ Convolves inputs along their last dimension using FFT. For inputs with large last dimensions, this module
+ is generally much faster than :class:`Convolve`.
+ Note that, in contrast to :class:`torch.nn.Conv1d`, which actually applies the valid cross-correlation
+ operator, this module applies the true `convolution`_ operator.
+ Also note that this module can only output float tensors (int tensor inputs will be cast to float).
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ mode (str, optional): Must be one of ("full", "valid", "same").
+
+ * "full": Returns the full convolution result, with shape `(..., N + M - 1)`, where
+ `N` and `M` are the trailing dimensions of the two inputs. (Default)
+ * "valid": Returns the segment of the full convolution result corresponding to where
+ the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
+ * "same": Returns the center segment of the full convolution result, with shape `(..., N)`.
+
+ .. _convolution:
+ https://en.wikipedia.org/wiki/Convolution
+ """
+
+ def __init__(self, mode: str = "full") -> None:
+ _check_convolve_mode(mode)
+
+ super().__init__()
+ self.mode = mode
+
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+ r"""
+ Args:
+ x (torch.Tensor): First convolution operand, with shape `(..., N)`.
+ y (torch.Tensor): Second convolution operand, with shape `(..., M)`
+ (leading dimensions must be broadcast-able with those of ``x``).
+
+ Returns:
+ torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
+ the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.
+ """
+ return F.fftconvolve(x, y, mode=self.mode)
+
+
+def _source_target_sample_rate(orig_freq: int, speed: float) -> Tuple[int, int]:
+ source_sample_rate = int(speed * orig_freq)
+ target_sample_rate = int(orig_freq)
+ gcd = math.gcd(source_sample_rate, target_sample_rate)
+ return source_sample_rate // gcd, target_sample_rate // gcd
+
+
+class Speed(torch.nn.Module):
+ r"""Adjusts waveform speed.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ orig_freq (int): Original frequency of the signals in ``waveform``.
+ factor (float): Factor by which to adjust speed of input. Values greater than 1.0
+ compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time.
+ """
+
+ def __init__(self, orig_freq, factor) -> None:
+ super().__init__()
+
+ self.orig_freq = orig_freq
+ self.factor = factor
+
+ self.source_sample_rate, self.target_sample_rate = _source_target_sample_rate(orig_freq, factor)
+ self.resampler = Resample(orig_freq=self.source_sample_rate, new_freq=self.target_sample_rate)
+
+ def forward(self, waveform, lengths: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ r"""
+ Args:
+ waveform (torch.Tensor): Input signals, with shape `(..., time)`.
+ lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`.
+ If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``)
+
+ Returns:
+ (torch.Tensor, torch.Tensor or None):
+ torch.Tensor
+ Speed-adjusted waveform, with shape `(..., new_time).`
+ torch.Tensor or None
+ If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform,
+ with shape `(...)`; otherwise, ``None``.
+ """
+
+ if lengths is None:
+ out_lengths = None
+ else:
+ out_lengths = torch.ceil(lengths * self.target_sample_rate / self.source_sample_rate).to(lengths.dtype)
+
+ return self.resampler(waveform), out_lengths
+
+
+class SpeedPerturbation(torch.nn.Module):
+ r"""Applies the speed perturbation augmentation introduced in
+ *Audio augmentation for speech recognition* :cite:`ko15_interspeech`. For a given input,
+ the module samples a speed-up factor from ``factors`` uniformly at random and adjusts
+ the speed of the input by that factor.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ orig_freq (int): Original frequency of the signals in ``waveform``.
+ factors (Sequence[float]): Factors by which to adjust speed of input. Values greater than 1.0
+ compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time.
+
+ Example
+ >>> speed_perturb = SpeedPerturbation(16000, [0.9, 1.1, 1.0, 1.0, 1.0])
+ >>> # waveform speed will be adjusted by factor 0.9 with 20% probability,
+ >>> # 1.1 with 20% probability, and 1.0 (i.e. kept the same) with 60% probability.
+ >>> speed_perturbed_waveform = speed_perturb(waveform, lengths)
+ """
+
+ def __init__(self, orig_freq: int, factors: Sequence[float]) -> None:
+ super().__init__()
+
+ self.speeders = torch.nn.ModuleList([Speed(orig_freq=orig_freq, factor=factor) for factor in factors])
+
+ def forward(
+ self, waveform: torch.Tensor, lengths: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ r"""
+ Args:
+ waveform (torch.Tensor): Input signals, with shape `(..., time)`.
+ lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`.
+ If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``)
+
+ Returns:
+ (torch.Tensor, torch.Tensor or None):
+ torch.Tensor
+ Speed-adjusted waveform, with shape `(..., new_time).`
+ torch.Tensor or None
+ If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform,
+ with shape `(...)`; otherwise, ``None``.
+ """
+
+ idx = int(torch.randint(len(self.speeders), ()))
+ # NOTE: we do this because TorchScript doesn't allow for
+ # indexing ModuleList instances with non-literals.
+ for speeder_idx, speeder in enumerate(self.speeders):
+ if idx == speeder_idx:
+ return speeder(waveform, lengths)
+ raise RuntimeError("Speeder not found; execution should have never reached here.")
+
+
+class AddNoise(torch.nn.Module):
+ r"""Scales and adds noise to waveform per signal-to-noise ratio.
+ See :meth:`torchaudio.functional.add_noise` for more details.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+ """
+
+ def forward(
+ self, waveform: torch.Tensor, noise: torch.Tensor, snr: torch.Tensor, lengths: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ r"""
+ Args:
+ waveform (torch.Tensor): Input waveform, with shape `(..., L)`.
+ noise (torch.Tensor): Noise, with shape `(..., L)` (same shape as ``waveform``).
+ snr (torch.Tensor): Signal-to-noise ratios in dB, with shape `(...,)`.
+ lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform`` and ``noise``,
+ with shape `(...,)` (leading dimensions must match those of ``waveform``). If ``None``, all
+ elements in ``waveform`` and ``noise`` are treated as valid. (Default: ``None``)
+
+ Returns:
+ torch.Tensor: Result of scaling and adding ``noise`` to ``waveform``, with shape `(..., L)`
+ (same shape as ``waveform``).
+ """
+ return F.add_noise(waveform, noise, snr, lengths)
+
+
+class Preemphasis(torch.nn.Module):
+ r"""Pre-emphasizes a waveform along its last dimension.
+ See :meth:`torchaudio.functional.preemphasis` for more details.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ coeff (float, optional): Pre-emphasis coefficient. Typically between 0.0 and 1.0.
+ (Default: 0.97)
+ """
+
+ def __init__(self, coeff: float = 0.97) -> None:
+ super().__init__()
+ self.coeff = coeff
+
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
+ r"""
+ Args:
+ waveform (torch.Tensor): Waveform, with shape `(..., N)`.
+
+ Returns:
+ torch.Tensor: Pre-emphasized waveform, with shape `(..., N)`.
+ """
+ return F.preemphasis(waveform, coeff=self.coeff)
+
+
+class Deemphasis(torch.nn.Module):
+ r"""De-emphasizes a waveform along its last dimension.
+ See :meth:`torchaudio.functional.deemphasis` for more details.
+
+ .. devices:: CPU CUDA
+
+ .. properties:: Autograd TorchScript
+
+ Args:
+ coeff (float, optional): De-emphasis coefficient. Typically between 0.0 and 1.0.
+ (Default: 0.97)
+ """
+
+ def __init__(self, coeff: float = 0.97) -> None:
+ super().__init__()
+ self.coeff = coeff
+
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
+ r"""
+ Args:
+ waveform (torch.Tensor): Waveform, with shape `(..., N)`.
+
+ Returns:
+ torch.Tensor: De-emphasized waveform, with shape `(..., N)`.
+ """
+ return F.deemphasis(waveform, coeff=self.coeff)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aff17a50e2fb49176c884e5d4b11970ae76cbab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__init__.py
@@ -0,0 +1,11 @@
+from torio.utils import ffmpeg_utils
+
+from . import sox_utils
+from .download import download_asset
+
+
+__all__ = [
+ "download_asset",
+ "sox_utils",
+ "ffmpeg_utils",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7aa1550fae6787905e0f4b365c1332cb8ed205b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/download.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/download.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cf95bae4594f84da05ec5f74f798dcc90b05623
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/download.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/ffmpeg_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/ffmpeg_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..978920f13b0a87a4c80c3000ba91865f0d0010ca
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/ffmpeg_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/sox_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/sox_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9cac7a1e7bdd9dc5cf861a64592876d2feae51a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/__pycache__/sox_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/download.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/download.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f62c7ef1f56ba0ee25888e5fc14dcb2c665ba6a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/download.py
@@ -0,0 +1,89 @@
+import hashlib
+import logging
+from os import PathLike
+from pathlib import Path
+from typing import Union
+
+import torch
+from torchaudio._internal import download_url_to_file
+
+_LG = logging.getLogger(__name__)
+
+
+def _get_local_path(key):
+ path = Path(torch.hub.get_dir()) / "torchaudio" / Path(key)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def _download(key, path, progress):
+ url = f"https://download.pytorch.org/torchaudio/{key}"
+ download_url_to_file(url, path, progress=progress)
+
+
+def _get_hash(path, hash, chunk_size=1028):
+ m = hashlib.sha256()
+ with open(path, "rb") as file:
+ data = file.read(chunk_size)
+ while data:
+ m.update(data)
+ data = file.read(chunk_size)
+ return m.hexdigest()
+
+
+def download_asset(
+ key: str,
+ hash: str = "",
+ path: Union[str, PathLike] = "",
+ *,
+ progress: bool = True,
+) -> str:
+ """Download and store torchaudio assets to local file system.
+
+ If a file exists at the download path, then that path is returned with or without
+ hash validation.
+
+ Args:
+ key (str): The asset identifier.
+ hash (str, optional):
+ The value of SHA256 hash of the asset. If provided, it is used to verify
+ the downloaded / cached object. If not provided, then no hash validation
+ is performed. This means if a file exists at the download path, then the path
+ is returned as-is without verifying the identity of the file.
+ path (path-like object, optional):
+ By default, the downloaded asset is saved in a directory under
+ :py:func:`torch.hub.get_dir` and intermediate directories based on the given `key`
+ are created.
+ This argument can be used to overwrite the target location.
+ When this argument is provided, all the intermediate directories have to be
+ created beforehand.
+ progress (bool): Whether to show progress bar for downloading. Default: ``True``.
+
+ Note:
+ Currently the valid key values are the route on ``download.pytorch.org/torchaudio``,
+ but this is an implementation detail.
+
+ Returns:
+ str: The path to the asset on the local file system.
+ """
+ path = path or _get_local_path(key)
+
+ if path.exists():
+ _LG.info("The local file (%s) exists. Skipping the download.", path)
+ else:
+ _LG.info("Downloading %s to %s", key, path)
+ _download(key, path, progress=progress)
+
+ if hash:
+ _LG.info("Verifying the hash value.")
+ digest = _get_hash(path, hash)
+
+ if digest != hash:
+ raise ValueError(
+ f"The hash value of the downloaded file ({path}), '{digest}' does not match "
+ f"the provided hash value, '{hash}'."
+ )
+
+ _LG.info("Hash validated.")
+
+ return str(path)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/ffmpeg_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/ffmpeg_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4bb3c4e3b621ff7b48062d1c4d3374a4459c90
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/ffmpeg_utils.py
@@ -0,0 +1,11 @@
+"""Module to change the configuration of FFmpeg libraries (such as libavformat).
+
+It affects functionalities in :py:mod:`torchaudio.io` (and indirectly :py:func:`torchaudio.load`).
+"""
+
+
+# This file is just for BC.
+def __getattr__(item):
+ from torio.utils import ffmpeg_utils
+
+ return getattr(ffmpeg_utils, item)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/sox_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/sox_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8975b4216f54e3ece63483bf91b49f10385f5785
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchaudio/utils/sox_utils.py
@@ -0,0 +1,99 @@
+"""Module to change the configuration of libsox, which is used by I/O functions like
+:py:mod:`~torchaudio.backend.sox_io_backend` and :py:mod:`~torchaudio.sox_effects`.
+"""
+
+from typing import Dict, List
+
+import torchaudio
+
+sox_ext = torchaudio._extension.lazy_import_sox_ext()
+
+
+def set_seed(seed: int):
+ """Set libsox's PRNG
+
+ Args:
+ seed (int): seed value. valid range is int32.
+
+ See Also:
+ http://sox.sourceforge.net/sox.html
+ """
+ sox_ext.set_seed(seed)
+
+
+def set_verbosity(verbosity: int):
+ """Set libsox's verbosity
+
+ Args:
+ verbosity (int): Set verbosity level of libsox.
+
+ * ``1`` failure messages
+ * ``2`` warnings
+ * ``3`` details of processing
+ * ``4``-``6`` increasing levels of debug messages
+
+ See Also:
+ http://sox.sourceforge.net/sox.html
+ """
+ sox_ext.set_verbosity(verbosity)
+
+
+def set_buffer_size(buffer_size: int):
+ """Set buffer size for sox effect chain
+
+ Args:
+ buffer_size (int): Set the size in bytes of the buffers used for processing audio.
+
+ See Also:
+ http://sox.sourceforge.net/sox.html
+ """
+ sox_ext.set_buffer_size(buffer_size)
+
+
+def set_use_threads(use_threads: bool):
+ """Set multithread option for sox effect chain
+
+ Args:
+ use_threads (bool): When ``True``, enables ``libsox``'s parallel effects channels processing.
+ To use mutlithread, the underlying ``libsox`` has to be compiled with OpenMP support.
+
+ See Also:
+ http://sox.sourceforge.net/sox.html
+ """
+ sox_ext.set_use_threads(use_threads)
+
+
+def list_effects() -> Dict[str, str]:
+ """List the available sox effect names
+
+ Returns:
+ Dict[str, str]: Mapping from ``effect name`` to ``usage``
+ """
+ return dict(sox_ext.list_effects())
+
+
+def list_read_formats() -> List[str]:
+ """List the supported audio formats for read
+
+ Returns:
+ List[str]: List of supported audio formats
+ """
+ return sox_ext.list_read_formats()
+
+
+def list_write_formats() -> List[str]:
+ """List the supported audio formats for write
+
+ Returns:
+ List[str]: List of supported audio formats
+ """
+ return sox_ext.list_write_formats()
+
+
+def get_buffer_size() -> int:
+ """Get buffer size for sox effect chain
+
+ Returns:
+ int: size in bytes of buffers used for processing audio.
+ """
+ return sox_ext.get_buffer_size()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f4231151684cbbdc943099712e3f7ed89cf22e4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/code_template.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/code_template.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a67e666757c7ccd166fdaa2a7d98b65e1545d82
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/code_template.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/context.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/context.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1e98d829aa7039836741b06f274391ac740bb17
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/context.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cd20273cd3bd4f3c24e568349c12489997f37a8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c78c534d49730238146b641d100a77fb1ca8cf8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_executorch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_executorch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1386f204b0b5f4b09d44facbaff704584b2edfa
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_executorch.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..400ca0c735b889170e5025610fe431a3b1200017
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f5d6d76f67e6f0a949e0f118de670b6e46b6163
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c49c62056ca896479e9d28640f38abf4411104e2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f4657c66ac05e043b4717f6c820c2eddf90ef765
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/local.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/local.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6b0aa8c177e75363ff2d6143191b493300c5e90
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/local.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/native_function_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/native_function_generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d2e8da2b0925e78789aee6a4350449f973f51f27
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/native_function_generation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f82cfb3b9ea0467d0c24d0f708e2ecdd19b377bd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/yaml_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/yaml_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e14ec7837399e82c5dae44f3607e40a4366d783c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/__pycache__/yaml_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..785d5b42dafe0720ceb8578fd40a725d4756d08f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e08b585992eb7b9fcdc085a0e04c2c7b498dc1c4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/fallback_ops.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/fallback_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..edb4db1f4adf8aa834b0a2b2b78ea7872f2a742a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/aoti/fallback_ops.py
@@ -0,0 +1,156 @@
+# Be extra careful when you edit this file, because it affects AOTInductor ABI compatbility. See
+# https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436
+# for details.
+#
+# The inductor_fallback_ops list is based on the fallback ops from torch/_inductor/lowering.py.
+# Generally speaking, it is ok to add a new op to the list, but you need to run
+# `python torchgen/gen.py --update-aoti-c-shim` in order to regenerate C shim header files.
+# But it is NOT ok to remove an existing fallback op from the list, since that will break
+# some existing AOTInductor-compiled models.
+inductor_fallback_ops = {
+ "aten._adaptive_avg_pool2d_backward.default",
+ "aten._adaptive_avg_pool2d.default",
+ "aten._adaptive_avg_pool3d.default",
+ "aten._adaptive_avg_pool3d_backward.default",
+ "aten.adaptive_max_pool2d_backward.default",
+ "aten.adaptive_max_pool2d.default",
+ "aten.adaptive_max_pool3d.default",
+ "aten.adaptive_max_pool3d_backward.default",
+ "aten.add.Scalar",
+ "aten.add.Tensor",
+ "aten.addbmm.default",
+ "aten._addmm_activation.default",
+ "aten.addmm.out",
+ "aten.addmv.default",
+ "aten.angle.default",
+ "aten.avg_pool2d_backward.default",
+ "aten.avg_pool2d.default",
+ "aten.avg_pool3d_backward.default",
+ "aten.avg_pool3d.default",
+ "aten.baddbmm.out",
+ "aten.bernoulli_.float",
+ "aten.bernoulli_.Tensor",
+ "aten.bmm.out",
+ "aten.bucketize.Tensor",
+ "aten.cat.default",
+ "aten._cdist_backward.default",
+ "aten._cdist_forward.default",
+ "aten.cholesky_inverse.default",
+ "aten.cholesky_solve.default",
+ "aten.convolution_backward.default",
+ "aten._cudnn_rnn.default",
+ "aten._cudnn_rnn_backward.default",
+ "aten.convolution.default",
+ "aten.cummax.default",
+ "aten.cummin.default",
+ "aten.cumprod.default",
+ "aten.cumsum.default",
+ "aten._efficient_attention_backward.default",
+ "aten._efficient_attention_forward.default",
+ "aten._efficientzerotensor.default",
+ "aten._embedding_bag.default",
+ "aten._embedding_bag_dense_backward.default",
+ "aten._embedding_bag_forward_only.default",
+ "aten._embedding_bag_per_sample_weights_backward.default",
+ "aten.exponential.default",
+ "aten._fft_c2c.default",
+ "aten._fft_r2c.default",
+ "aten._flash_attention_backward.default",
+ "aten._flash_attention_forward.default",
+ "aten.fractional_max_pool2d_backward.default",
+ "aten.fractional_max_pool2d.default",
+ "aten.fractional_max_pool3d.default",
+ "aten.fractional_max_pool3d_backward.default",
+ "aten._fused_moving_avg_obs_fq_helper.default",
+ "aten._fused_moving_avg_obs_fq_helper_functional.default",
+ "aten.gcd.default",
+ "aten.geqrf.default",
+ "aten.grid_sampler_2d_backward.default",
+ "aten.histc.default",
+ "aten.histogram.bin_ct",
+ "aten._histogramdd_bin_edges.default",
+ "aten._histogramdd_from_bin_cts.default",
+ "aten.index_put.default",
+ "aten.index_reduce.default",
+ "aten.index.Tensor",
+ "aten.kthvalue.default",
+ "aten.logcumsumexp.default",
+ "aten.lu_unpack.default",
+ "aten.masked_select.default",
+ "aten.masked_scatter.default",
+ "aten.masked_scatter_backward.default",
+ "aten.max_pool2d_with_indices_backward.default",
+ "aten.max_pool2d_with_indices.default",
+ "aten.max_pool3d_with_indices.default",
+ "aten.max_pool3d_with_indices_backward.default",
+ "aten.max_unpool2d.default",
+ "aten.max_unpool3d.default",
+ "aten.median.default",
+ "aten.mm.out",
+ "aten.mode.default",
+ "aten.mul.Scalar",
+ "aten.mul.Tensor",
+ "aten.nanmedian.default",
+ "aten.native_dropout.default",
+ "aten.normal_functional.default",
+ "aten.nonzero.default",
+ "aten.ormqr.default",
+ "aten._pdist_backward.default",
+ "aten._pdist_forward.default",
+ "aten.polar.default",
+ "aten.pow.Scalar",
+ "aten.pow.Tensor_Scalar",
+ "aten.pow.Tensor_Tensor",
+ "aten.rand.default",
+ "aten.rand.generator",
+ "aten.randint.default",
+ "aten.randint.generator",
+ "aten.randint.low",
+ "aten.randint.low_out",
+ "aten.randn.default",
+ "aten.randn.generator",
+ "aten.randperm.default",
+ "aten.repeat_interleave.Tensor",
+ "aten.replication_pad1d_backward.default",
+ "aten.replication_pad2d_backward.default",
+ "aten.reshape.default",
+ "aten.resize_.default",
+ "aten.resize_as_.default",
+ "aten._scaled_dot_product_efficient_attention_backward.default",
+ "aten._scaled_dot_product_efficient_attention.default",
+ "aten._scaled_dot_product_flash_attention_backward.default",
+ "aten._scaled_dot_product_flash_attention.default",
+ "aten._scaled_dot_product_cudnn_attention_backward.default",
+ "aten._scaled_dot_product_cudnn_attention.default",
+ "aten._scaled_dot_product_flash_attention_for_cpu_backward.default",
+ "aten._scaled_dot_product_flash_attention_for_cpu.default",
+ "aten._scaled_mm.default",
+ "aten._scaled_mm.out",
+ "aten.scatter_reduce.two_out",
+ "aten.scatter.src_out",
+ "aten.scatter.value_out",
+ "aten.searchsorted.Scalar",
+ "aten.searchsorted.Tensor",
+ "aten._segment_reduce_backward.default",
+ "aten.segment_reduce.default",
+ "aten.slice.Tensor",
+ "aten.soft_margin_loss_backward.default",
+ "aten.sort.default",
+ "aten.sort.stable",
+ "aten._sparse_coo_tensor_with_dims_and_tensors.default",
+ "aten._thnn_fused_lstm_cell.default",
+ "aten.topk.default",
+ "aten._to_sparse.default",
+ "aten.to_sparse.default",
+ "aten.triangular_solve.default",
+ "aten._trilinear.default",
+ "aten.uniform.default",
+ "aten.upsample_bicubic2d_backward.default",
+ "aten.upsample_linear1d_backward.default",
+ "aten.upsample_trilinear3d_backward.default",
+ "aten.view_as_complex.default",
+ "aten.view_as_real.default",
+ "aten.view.dtype",
+ "aten._weight_int8pack_mm.default",
+ "aten.zeros.names",
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1f516d7229f691ebecc8ba61638af3a8d65809e7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/autograd.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/autograd.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6b4d2baa5766d4ed6eeed093e7d365bc4d78e71
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/autograd.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/cpp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/cpp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbacf943f71fef5c88510c11f2048c98a2593b68
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/cpp.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/dispatcher.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/dispatcher.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a9141645186354df62613e4f13f4f6a10e6b5339
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/dispatcher.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/functionalization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/functionalization.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9abad571228578559f94a1d328b1a0a939a4294f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/functionalization.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/lazy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/lazy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d22fc3b786622e46ec4691fb2225cfad472fed1d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/lazy.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/meta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/meta.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5040a4655868962ac262f7c18cdb747797e02f4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/meta.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/native.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/native.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..633c8c2660f27cdc41c233f007f4feff320287fd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/native.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/python.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/python.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9f5ae3f06cf242215683416ad225e1f18783795
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/python.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/structured.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/structured.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d773b4eaa10513649b9e063a617b5da1d9c5e7e7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/structured.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/translate.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/translate.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..410b2109ed5e1e907198b249e242414df7216eb9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/translate.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/ufunc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/ufunc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b91756cfaa0f1626fb91f8b8efe5871a28fe8aa
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/ufunc.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/unboxing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/unboxing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16a45dea3ed16f48407e58020872dadb09859f31
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/__pycache__/unboxing.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/autograd.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/autograd.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb1caeab6464f00015bd6f5c82a7c5871eb4a3b1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/autograd.py
@@ -0,0 +1,874 @@
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import cast, TYPE_CHECKING
+
+from torchgen import local
+from torchgen.api import cpp
+from torchgen.api.types import BaseCType, Binding, NamedCType, tensorListT
+from torchgen.model import (
+ BaseTy,
+ BaseType,
+ FunctionSchema,
+ ListType,
+ NativeFunction,
+ NativeFunctionsViewGroup,
+ SchemaKind,
+ Type,
+)
+from torchgen.utils import IDENT_REGEX
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+# Represents a saved attribute involved in backward calculation.
+# Note that it can be a derived property of an input argument, e.g.:
+# we could save `other.scalar_type()` instead of the entire `other` tensor.
+@dataclass(frozen=True)
+class SavedAttribute:
+ # The NamedCType holds the updated name and cpp type of the attribute
+ # for the name, Suffix is appended if it's derived property, e.g.: `other_scalar_type`
+ nctype: NamedCType
+
+ # The expression to read the derived property at save time, e.g.:
+ # `other.scalar_type()`.
+ expr: str
+
+
+# Represents a backward formula that calculates derivatives for one
+# or more tensors.
+@dataclass(frozen=True)
+class Derivative:
+ # The formula string (legit C++ expression).
+ # Note that expressions against input arguments have been replaced with the
+ # corresponding saved attributes.
+ # E.g.:
+ # raw formula: `mul_tensor_backward(grad, self, other.scalar_type())`
+ # here: `mul_tensor_backward(grad, self, other_scalar_type)`
+ formula: str
+
+ # The formula string before input argument replacement
+ original_formula: str
+
+ # Names of the arguments for which this formula calculates derivatives.
+ var_names: tuple[str, ...]
+
+ # Saved inputs that are referenced by the formula.
+ saved_inputs: tuple[SavedAttribute, ...]
+
+ # Saved outputs that are referenced by the formula.
+ saved_outputs: tuple[SavedAttribute, ...]
+
+ # Gradients that are referenced by name in the formula.
+ named_gradients: set[str]
+
+
+# Represents a forward formula that calculates forward derivatives
+# for one tensor.
+@dataclass(frozen=True)
+class ForwardDerivative:
+ # The formula string (legit C++ expression).
+ # Note that special keywords such as "linear" or "element_wise" have been
+ # replaced by the automatically generated formula.
+ formula: str
+
+ # Name of the output arguments for which this formula calculates forward
+ # derivatives
+ var_names: tuple[str, ...]
+
+ # Type of the output arguments for which this formula calculates forward
+ # derivatives
+ var_types: tuple[Type, ...]
+
+ # Inputs for which the forward derivatives are required for this formula
+ required_inputs_fw_grad: tuple[str, ...] | None
+
+ # Inputs for which the primal is required for this formula
+ required_inputs_primal: tuple[str, ...] | None
+
+ # Flag to specify if this formula requires the original value of self
+ # This is only used by inplace operations
+ required_original_self_value: bool
+
+ # If this formula is specified in derivatives.yaml or if we are re-using the
+ # out of place formula for inplace
+ is_reusing_outplace_formula: bool
+
+
+# Represents differentiability info for a NativeFunction.
+@dataclass(frozen=True)
+class DifferentiabilityInfo:
+ # The base name read from derivatives.yaml.
+ name: str
+
+ # The matching native function.
+ #
+ # There can be multiple NativeFunction having the same base name:
+ # - different overloads with different types of input arguments;
+ # - in-place/out/functional variants of the same function;
+ #
+ # We first use the schema string (under the 'name' key) in derivatives.yaml
+ # to find the NativeFunction having the same schema string.
+ # Then we find the in-place/out/functional variants of the matching function.
+ # Among these variants, we choose the one having the same name as the
+ # derivatives.yaml entry. If there is no exact match, then we choose the
+ # in-place variant.
+ # TODO: maybe the logic to search for all variants is no longer necessary?
+ func: NativeFunction
+
+ # The name of the generated autograd function.
+ # It's set only if we will calculate a derivative, i.e.
+ # 'args_with_derivatives' is not empty.
+ op: str | None
+
+ # The derivatives formulae for this function.
+ # Note that the length of this sequence is the number of differentiable inputs
+ derivatives: Sequence[Derivative]
+
+ # The forward derivatives formulae for this function.
+ # Note that the length of this sequence is the number of differentiable outputs
+ forward_derivatives: Sequence[ForwardDerivative]
+
+ # The union of 'saved_inputs' of all 'derivatives'.
+ all_saved_inputs: Sequence[SavedAttribute]
+
+ # The union of 'saved_outputs' of all 'derivatives'.
+ all_saved_outputs: Sequence[SavedAttribute]
+
+ # All named gradients that are available for use, in the same
+ # order as in the grads vector.
+ available_named_gradients: Sequence[str]
+
+ # The named gradients that are used in any of the derivatives.
+ # Invariant: all(name in available_named_gradients for name in used_named_gradients)
+ used_named_gradients: set[str]
+
+ # The function's input arguments for which it calculates derivatives.
+ # It's the union of 'var_names' of all 'derivatives', sorted by the
+ # argument order in the function schema.
+ args_with_derivatives: Sequence[Binding]
+
+ # Names of arguments whose derivative formula is 'non_differentiable'.
+ non_differentiable_arg_names: Sequence[str]
+
+ # Raw data read from derivatives.yaml.
+ output_differentiability: list[bool] | None
+
+ # output_differentiability in derivatives.yaml can be a list of
+ # conditions that express if the output is differentiable. In this case,
+ # the number of conditions must match the number of outputs
+ # (NB: we only support one condition right now).
+ # output_differentiability gets populated with True for each condition,
+ # while output_differentiability_conditions gets populated with the conditions
+ output_differentiability_conditions: list[str] | None
+
+ @property
+ def has_derivatives(self) -> bool:
+ return len(self.args_with_derivatives) > 0
+
+ # Generates a new DifferentiabilityInfo using the exact same set of derivative information,
+ # but with a new operator name.
+ # This is used when generating "copy" variants of view ops,
+ # which are able to use the exact same derivative formula as the original view op
+ # See Note [Codegen'd {view}_copy Operators]
+ def create_view_copy_from_view_derivative(
+ self, g: NativeFunctionsViewGroup
+ ) -> DifferentiabilityInfo | None:
+ if g.view_copy is None:
+ return None
+ f = g.view_copy
+
+ name_split_by_period = self.name.split(".", maxsplit=2)
+ # Append a "_copy" to the base name of the operator (but keep the overload name the same)
+ view_copy_name = f"{name_split_by_period[0]}_copy." + ".".join(
+ name_split_by_period[1:]
+ )
+ view_copy_op_name = None if self.op is None else f"{self.op}_copy"
+
+ return DifferentiabilityInfo(
+ # Use the "_copy" version of name/func/op
+ name=view_copy_name,
+ func=f,
+ op=view_copy_op_name,
+ # But keep all derivative info the same
+ derivatives=self.derivatives,
+ forward_derivatives=self.forward_derivatives,
+ all_saved_inputs=self.all_saved_inputs,
+ all_saved_outputs=self.all_saved_outputs,
+ available_named_gradients=self.available_named_gradients,
+ used_named_gradients=self.used_named_gradients,
+ args_with_derivatives=self.args_with_derivatives,
+ non_differentiable_arg_names=self.non_differentiable_arg_names,
+ output_differentiability=self.output_differentiability,
+ output_differentiability_conditions=self.output_differentiability_conditions,
+ )
+
+
+def uses_ident(info: DifferentiabilityInfo | None, ident: str) -> bool:
+ if info is None:
+ return False
+ for derivative in info.derivatives:
+ formula = derivative.formula
+ if re.search(IDENT_REGEX.format(ident), formula):
+ return True
+ return False
+
+
+def uses_retain_variables(info: DifferentiabilityInfo | None) -> bool:
+ return uses_ident(info, "retain_variables")
+
+
+def uses_single_grad(info: DifferentiabilityInfo | None) -> bool:
+ return uses_ident(info, "grad")
+
+
+# Represents a differentiable `Argument`.
+# How is it different from the `Argument` type?
+# - It's processed Arguments which are differentiable and only used in the
+# context of the autograd codegen;
+# - It can represent SelfArgument or regular Argument but not TensorOptionsArgument;
+@dataclass(frozen=True)
+class DifferentiableInput:
+ name: str
+ type: Type
+
+ # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
+ cpp_type: str
+
+
+# Represents a differentiable `Return`.
+# How it it different from the `Return` type?
+# - The name in `Return` is optional. Here it is always populated using the same
+# `cpp.return_names()` method.
+# TODO: some cpp naming logic (e.g. resolving name conflict) might be irrelevant?
+# - It's processed Returns which are differentiable, in compliance with the
+# `output_differentiability` field defined in derivatives.yaml (if specified),
+# and are only used in the context of the autograd codegen;
+@dataclass(frozen=True)
+class DifferentiableOutput:
+ name: str
+ type: Type
+
+ # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove.
+ cpp_type: str
+
+
+@dataclass(frozen=True)
+class NativeFunctionWithDifferentiabilityInfo:
+ func: NativeFunction
+ info: dict[str, DifferentiabilityInfo] | None
+ fw_derivatives: dict[str, Sequence[ForwardDerivative]] | None
+
+
+# TODO: Update comment below since it is out of date.
+def dispatch_strategy(fn: NativeFunctionWithDifferentiabilityInfo) -> str:
+ """How are we going to call the underlying implementation of a
+ declaration? There are two strategies:
+ - use_derived: we want to call the implementation on CPUDoubleType
+ (or a similar, derived Type instance). Because these derived
+ instances deal in Tensors, not Variables (it's a completely different
+ object, so it doesn't dispatch back to VariableType), code on
+ this dispatch path needs to wrap/unwrap tensors. If the
+ derived implementation takes and returns tensors, the
+ implementation is usually differentiable (although we also use
+ the derived dispatch path for non-differentiable functions
+ that we still want to dispatch on the derived Type instance;
+ e.g., size())
+ - use_type: we want to call the implementation on Type, because
+ it is implemented concretely, and the functions it invokes will
+ get dispatched back to VariableType (which will ensure that they
+ are differentiable.)
+ """
+ # fn is derived as long as any of its per-key differentiability infos
+ # has_derivatives. dispatch_strategy() is used to guard generation of fns in VariableType
+ # and ADInplaceOrViewType. We want to generate these functions as long as a
+ # derivative is defined for ANY dispatch key.
+ if fn.func.is_abstract or (
+ fn.info is not None and any(info.has_derivatives for info in fn.info.values())
+ ):
+ # If the function is abstract (not implemented on at::Type), we must
+ # call the implementation on the derived type with unpacked tensors.
+
+ # If the function has a derivative specified and is concrete, we could
+ # call either implementation. We prefer the calling the derived
+ # type's implementation with unpacked tensors because it is more
+ # performant in some cases: any internal calls to other ATen functions
+ # won't have the history tracked.
+
+ # If the function has a type dispatched argument (i.e. is a factory),
+ # we prefer calling the derived type's implementation both because it is
+ # more performant and to ensure factory functions return tensors with _version
+ # of 0 (probably not strictly necessary, but nice to have to keeps versions simple
+ # to understand.
+
+ return "use_derived"
+ else:
+ # If the function is concrete (we don't have to override it) and we
+ # didn't declare it in derivatives.yaml, we'll assume that it is
+ # actually implemented out of differentiable functions. (This
+ # assumption might not hold, but then you'll see gradcheck fail.)
+ return "use_type"
+
+
+def is_foreach_func(f: NativeFunction) -> bool:
+ return f.func.name.name.base.startswith("_foreach_")
+
+
+# note(crcrpar): Most foreach functions can reference an out-place `torch` function whose schema kind
+# is functional for their backward derivatives (and forward derivatives in the future), i.e.,
+# they would find such one in `functional_info_by_signature`. There however are some exceptions:
+_foreach_with_inplace_ref = {"_foreach_zero_"}
+_foreach_with_tensor_overload = {
+ "_foreach_add.Tensor",
+ "_foreach_mul.Tensor",
+ "_foreach_div.Tensor",
+}
+# The following do not support the alpha kwarg, which the nonforeach versions support.
+_skip_argument_len_check = {
+ "_foreach_add.Scalar",
+ "_foreach_add_.Scalar",
+ "_foreach_add.ScalarList",
+ "_foreach_add_.ScalarList",
+ "_foreach_sub.Scalar",
+ "_foreach_sub_.Scalar",
+ "_foreach_sub.ScalarList",
+ "_foreach_sub_.ScalarList",
+}
+
+
+# Checks if `function_schema` is a native, non-foreach function which `f`, a foreach function
+# reference to generate derivatives.
+def is_reference_for_foreach(
+ f: NativeFunction,
+ function_schema: FunctionSchema,
+) -> bool:
+ return (
+ f.func.name.name.base.split("_foreach_")[-1] == function_schema.name.name.base
+ and (
+ not function_schema.name.name.inplace
+ or str(f.func.name) in _foreach_with_inplace_ref
+ )
+ and (
+ str(f.func.name) in _skip_argument_len_check
+ or len(f.func.arguments.flat_non_out)
+ == len(function_schema.arguments.flat_non_out)
+ )
+ and all(
+ ref_arg.type in (arg.type, getattr(arg.type, "elem", None))
+ for arg, ref_arg in zip(
+ f.func.arguments.flat_non_out,
+ function_schema.arguments.flat_non_out,
+ )
+ )
+ )
+
+
+# TODO(crcrpar): Avoid hard coding "Default" ideally.
+def gen_foreach_derivativeinfo(
+ foreach_function: NativeFunction,
+ functional_info_by_signature: dict[
+ FunctionSchema, dict[str, DifferentiabilityInfo]
+ ],
+ non_functional_info_by_signature: dict[
+ FunctionSchema, dict[str, DifferentiabilityInfo]
+ ],
+ dispatch_key: str = "Default",
+) -> tuple[DifferentiabilityInfo | None, bool]:
+ """Generate DifferentiabilityInfo for out-place foreach function, return the existing one for in-place.
+
+ The second return value indicates whether the info is generated in this function.
+ """
+ ref_diff_info: DifferentiabilityInfo | None = None
+
+ for function_schema, diff_info in functional_info_by_signature.items():
+ if not is_reference_for_foreach(foreach_function, function_schema):
+ continue
+ ref_diff_info = diff_info[dispatch_key]
+ if ref_diff_info is not None:
+ break
+ # note(crcrpar): It seems like `zero`'s info isn't available in functional_info_by_signature
+ # while the info of `zero_` is in non_functional_info_by_signature
+ if (
+ ref_diff_info is None
+ and foreach_function.func.kind() == SchemaKind.inplace
+ and str(foreach_function.func.name) in _foreach_with_inplace_ref
+ ):
+ for function_schema, diff_info in non_functional_info_by_signature.items():
+ if not is_reference_for_foreach(foreach_function, function_schema):
+ continue
+ ref_diff_info = diff_info[dispatch_key]
+ if ref_diff_info is not None:
+ break
+ if ref_diff_info is None:
+ return None, False
+
+ # non out-place uses the existing Derivative.
+ if foreach_function.func.kind() == SchemaKind.inplace:
+ return ref_diff_info, False
+
+ map_refarg2foreacharg, map_name2arg = {}, {}
+ for i, (arg, ref_arg) in enumerate(
+ zip(
+ foreach_function.func.arguments.flat_non_out,
+ function_schema.arguments.flat_non_out,
+ )
+ ):
+ map_refarg2foreacharg[ref_arg.name] = arg.name
+ map_name2arg[arg.name] = arg
+
+ all_saved_inputs, all_saved_outputs, all_var_names = [], [], []
+ modified_derivative_formulas = []
+ for i, derivative in enumerate(ref_diff_info.derivatives):
+ modified_formula = derivative.formula.replace("grad", "grads[i]").replace(
+ "result", "result[i]"
+ )
+ saved_inputs, saved_outputs = [], []
+ # note(crcrpar): This context seems necessary to call `cpp.argument_type`
+ with local.parametrize(
+ use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors,
+ use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group,
+ ):
+ for ref_input in derivative.saved_inputs:
+ ref_input_jit_name = ref_input.expr.split(".")[0]
+ mapped_name = map_refarg2foreacharg[ref_input_jit_name]
+ if isinstance(map_name2arg[mapped_name].type, ListType):
+ mapped_expr = mapped_name + "[i]"
+ else:
+ mapped_expr = mapped_name
+ new_expr = ref_input.expr.replace(ref_input_jit_name, mapped_expr)
+ modified_formula = modified_formula.replace(
+ cast(str, ref_input.nctype.name), new_expr
+ )
+
+ nctype = cpp.argument_type(map_name2arg[mapped_name], binds=mapped_name)
+ canonical_nctype = NamedCType(
+ nctype.name, nctype.type.remove_const_ref()
+ )
+ saved_inputs.append(
+ SavedAttribute(nctype=canonical_nctype, expr=mapped_name)
+ )
+ for ref_output in derivative.saved_outputs:
+ if ref_output.nctype.name == "result":
+ saved_outputs.append(
+ SavedAttribute(
+ nctype=NamedCType(
+ name="result", type=BaseCType(tensorListT)
+ ),
+ expr="result",
+ )
+ )
+ else:
+ raise RuntimeError("")
+ var_names = [map_refarg2foreacharg[var] for var in derivative.var_names]
+ all_var_names.extend(var_names)
+ all_saved_inputs.extend(saved_inputs)
+ all_saved_outputs.extend(saved_outputs)
+ modified_derivative = Derivative(
+ formula=modified_formula,
+ original_formula=derivative.formula,
+ var_names=tuple(var_names),
+ saved_inputs=tuple(saved_inputs),
+ saved_outputs=tuple(saved_outputs),
+ named_gradients=set(),
+ )
+ modified_derivative_formulas.append(modified_derivative)
+
+ with local.parametrize(
+ use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors,
+ use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group,
+ ):
+ args_with_derivatives = [
+ Binding(
+ name=arg.name,
+ nctype=cpp.argument_type(arg, binds=arg.name),
+ argument=arg,
+ default=None,
+ )
+ for arg in foreach_function.func.arguments.flat_non_out
+ if arg.name in all_var_names
+ ]
+
+ forward_derivatives: list[ForwardDerivative] = []
+ fw_derivative: ForwardDerivative
+ for fw_derivative in ref_diff_info.forward_derivatives:
+ var_names: list[str] = list(fw_derivative.var_names) # type: ignore[no-redef]
+ var_types: list[Type] = list(fw_derivative.var_types)
+ required_inputs_fw_grad: list[str] = []
+ required_inputs_primal: list[str] = []
+ if fw_derivative.required_inputs_fw_grad is not None:
+ required_inputs_fw_grad = list(fw_derivative.required_inputs_fw_grad)
+ if fw_derivative.required_inputs_primal:
+ required_inputs_primal = list(fw_derivative.required_inputs_primal)
+ modified_formula = fw_derivative.formula
+
+ # Foreach's result is TensorList
+ if "result" in modified_formula:
+ modified_formula = fw_derivative.formula.replace("result", "result[i]")
+
+ for foreach_arg, ref_arg in zip(
+ foreach_function.func.arguments.flat_non_out,
+ ref_diff_info.func.func.arguments.flat_non_out,
+ ):
+ # Modify reference forward formula
+ if (
+ isinstance(foreach_arg.type, ListType)
+ and not foreach_arg.type.is_tensor_like()
+ ):
+ # Assuming ScalarList
+ modified_formula = modified_formula.replace(
+ ref_arg.name, foreach_arg.name + "[i]"
+ )
+ elif foreach_arg.type.is_tensor_like():
+ # Assuming TensorList / Tensor
+ # assert isinstance(foreach_arg.type, ListType), f"{foreach_function.func.name}, {foreach_arg.type}"
+ assert isinstance(foreach_arg.type, ListType) or (
+ foreach_arg.type == BaseType(BaseTy.Tensor)
+ and str(foreach_function.func.name) in _foreach_with_tensor_overload
+ ), f"{foreach_function.func.name}, {foreach_arg.type}"
+ for suffix in ("_p", "_t"):
+ curr_expr = ref_arg.name + suffix
+ if curr_expr in modified_formula:
+ new_expr = foreach_arg.name + suffix
+ modified_formula = modified_formula.replace(curr_expr, new_expr)
+ else:
+ # Assuming Scalar
+ if foreach_arg.name != ref_arg.name:
+ modified_formula = modified_formula.replace(
+ ref_arg.name, foreach_arg.name
+ )
+
+ # note(crcrpar): there should exist a cooler way...
+ for i, name in enumerate(var_names):
+ if name == ref_arg.name:
+ var_names[i] = foreach_arg.name
+ var_types[i] = foreach_arg.type
+ for i, name in enumerate(required_inputs_fw_grad):
+ if name == ref_arg.name:
+ required_inputs_fw_grad[i] = foreach_arg.name
+ for i, name in enumerate(required_inputs_primal):
+ if name == ref_arg.name:
+ required_inputs_primal[i] = foreach_arg.name
+ forward_derivatives.append(
+ ForwardDerivative(
+ formula=modified_formula,
+ var_names=tuple(var_names),
+ var_types=tuple(var_types),
+ required_inputs_fw_grad=tuple(required_inputs_fw_grad),
+ required_inputs_primal=tuple(required_inputs_primal),
+ required_original_self_value=fw_derivative.required_original_self_value,
+ is_reusing_outplace_formula=fw_derivative.is_reusing_outplace_formula,
+ )
+ )
+
+ return (
+ DifferentiabilityInfo(
+ name=foreach_function.func.name.name.base,
+ func=foreach_function,
+ op=f"Foreach{ref_diff_info.op}{foreach_function.func.name.overload_name}",
+ derivatives=modified_derivative_formulas,
+ forward_derivatives=forward_derivatives,
+ all_saved_inputs=tuple(set(all_saved_inputs)),
+ all_saved_outputs=tuple(set(all_saved_outputs)),
+ available_named_gradients=(),
+ used_named_gradients=set(),
+ args_with_derivatives=args_with_derivatives,
+ non_differentiable_arg_names=[],
+ output_differentiability=None,
+ output_differentiability_conditions=None,
+ ),
+ True,
+ )
+
+
+def match_differentiability_info(
+ native_functions: list[NativeFunction],
+ differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
+) -> list[NativeFunctionWithDifferentiabilityInfo]:
+ """Sets the "derivative" key on declarations to matching autograd function
+ In-place functions will use the out-of-place derivative definition if there
+ is no in-place specific derivative.
+ """
+
+ functional_info_by_signature = {
+ schema.signature(strip_default=True): info_dict
+ for schema, info_dict in differentiability_infos.items()
+ if schema.kind() == SchemaKind.functional
+ }
+ non_functional_info_by_signature = {
+ schema.signature(strip_default=True): info_dict
+ for schema, info_dict in differentiability_infos.items()
+ if schema.kind() != SchemaKind.functional
+ }
+
+ def find_info(
+ f: NativeFunction,
+ ) -> tuple[dict[str, DifferentiabilityInfo] | None, bool]:
+ # Don't bother matching info to generated out= variants
+ if "generated" in f.tags and f.func.kind() == SchemaKind.out:
+ return None, False
+
+ # (1) Check for an exact match
+ if f.func in differentiability_infos:
+ return differentiability_infos[f.func], True
+
+ # (2) If no exact match, check if the out-of-place variant
+ # of this operator has a match.
+ # i.e mul() for mul_() or mul_out()
+ # note(crcrpar): Check foreach or not because in-place foreach functions use backward defined for the existing
+ # native functions instead of the out-place counterparts.
+ f_sig = f.func.signature(strip_default=True)
+ if f_sig in functional_info_by_signature and not is_foreach_func(f):
+ return functional_info_by_signature[f_sig], False
+
+ # (3) Some operators have a derivative explicitly defined for the mutable
+ # variant, but get a code-generated out-of-place variant which does *not*
+ # come with a derivative formula.
+ # For the generated out-of-place variant, use the mutable variant's formula
+ # if it exists.
+ if "generated" in f.tags and f_sig in non_functional_info_by_signature:
+ info_dict = non_functional_info_by_signature[f_sig]
+ # See https://github.com/pytorch/pytorch/pull/76320/files#r874816389
+ assert not any(
+ any("self" in str(inpt.nctype.name) for inpt in info.all_saved_inputs)
+ for info in info_dict.values()
+ ), f"""\
+Attempted to convert a derivative formula for a mutable operator
+ to be used by automatically by its functional variant ("{str(f.func)}").
+ this is not currently supported (we'd need to fix up the formula in the codegen)."""
+ return info_dict, False
+
+ # (4) Generate derivative information of foreach functions if none is defined in `derivatives.yaml`
+ if is_foreach_func(f):
+ assert f.func not in differentiability_infos
+ diff_info, is_generated = gen_foreach_derivativeinfo(
+ f,
+ functional_info_by_signature,
+ non_functional_info_by_signature,
+ )
+ if diff_info is None:
+ return None, False
+ # TODO(crcrpar): Avoid hard coding "Default" ideally.
+ diff_info_dict = {"Default": diff_info}
+ if is_generated:
+ differentiability_infos[f.func] = diff_info_dict
+ functional_info_by_signature[f.func] = diff_info_dict
+ return diff_info_dict, is_generated
+
+ return None, False
+
+ result: list[NativeFunctionWithDifferentiabilityInfo] = []
+ for f in native_functions:
+ info_dict, is_exact_match = find_info(f)
+
+ # Currently, the '.strides()' to 'strides_or_error' replacement does not support
+ # 'self' derivatives of an inplace function, so we must check for this case.
+ if f.func.kind() == SchemaKind.inplace and (info_dict is not None):
+ for info in info_dict.values():
+ for derivative in info.derivatives:
+ if "self" in derivative.var_names:
+ for saved_input in derivative.saved_inputs:
+ assert "strides_or_error" not in saved_input.expr, (
+ "Calling '.strides()' in the 'self' derivative formula of an "
+ f"in-place function is not supported: {f.func}"
+ )
+
+ if not info_dict:
+ result.append(
+ NativeFunctionWithDifferentiabilityInfo(
+ func=f, info=None, fw_derivatives=None
+ )
+ )
+ continue
+
+ fw_derivative_dict: dict[str, Sequence[ForwardDerivative]] = {}
+ for key, info in info_dict.items():
+ if not info.forward_derivatives:
+ fw_derivative_dict[key] = []
+ continue
+
+ forward_derivatives = info.forward_derivatives
+
+ # For functions that have a single def for out-of-place and inplace (like abs())
+ if f.func.kind() == SchemaKind.inplace:
+ # For inplace functions there is a little bit of work to do:
+ # 1) Validate the formula and make sure the input that is modified in not used:
+ # - If there is a formula for the inplace variant of the function (is_exact_match == True) then
+ # we make sure that the original value of the input that is being modified inplace (self_p) is
+ # not used in the formula. Note that the formula can use "original_self_p" here and that would
+ # trigger a clone of the original input.
+ # - If we are re-using the out of place formula (is_exact_match == False) then we replace every
+ # occurrence of self_p and self_t by original_self_p and original_self_t. These will be
+ # populated by cloned version of the original input (either the clone done by the backward AD
+ # logic if self is also used in a backward formula or a special clone that we add).
+ # 2) At this point, there cannot be a self_p in the formula.
+ # 3) Change "result" into "self_p" as by design, in the inplace function codegen, the result is
+ # simply called self (as it is modified inplace).
+ # 4) Update the required primals data in case it used to contain "result" but should now contain
+ # "self"
+ # 5) If it is not an exact match, the user formula is not modifying the existing forward grad
+ # inplace as it should. So add some code that makes sure that we do so if the forward grad
+ # already exists.
+
+ assert (
+ len(info.forward_derivatives) == 1
+ ) # Only single output inplace should exist
+ fw_info = info.forward_derivatives[0]
+ formula = fw_info.formula
+
+ def replace_self_with_original_self(formula: str, postfix: str) -> str:
+ def repl(m: re.Match[str]) -> str:
+ return f"{m.group(1)}original_self{postfix}{m.group(2)}"
+
+ return re.sub(IDENT_REGEX.format(f"self{postfix}"), repl, formula)
+
+ if re.search(IDENT_REGEX.format("self_p"), formula):
+ if is_exact_match:
+ # For manually defined formulas, don't allow the original value to be used
+ raise RuntimeError(
+ f'The formula for "{f.func.name}" is using the original value of self '
+ "that is being modified inplace. This would lead to wrong forward gradients. "
+ 'Please use "result" in the formula only.'
+ )
+ else:
+ # When the original formula is out of place, we save a clone of the primal
+ # value to be able to access this value if needed
+ # replace "self_p"/"self_t" from the formula by "original_self_p"/"original_self_t"
+ formula = replace_self_with_original_self(formula, "_p")
+ formula = replace_self_with_original_self(formula, "_t")
+
+ # replace "result" from the formula by "self_p"
+ def repl(m: re.Match[str]) -> str:
+ return f"{m.group(1)}self_p{m.group(2)}"
+
+ formula = re.sub(IDENT_REGEX.format("result"), repl, formula)
+
+ required_primals = fw_info.required_inputs_primal
+ if re.search(IDENT_REGEX.format("self_p"), formula):
+ required_primals = (
+ required_primals + ("self",) if required_primals else ("self",)
+ )
+
+ if not is_exact_match:
+ # NOTE [In-place forward AD formula Optimization]
+ #
+ # This optimization transforms the formula to directly do inplace, i.e.
+ # instead of self_t.copy_(self_t.op()) we do self_t.op_() when the following are met:
+ #
+ # 1) the formula satisfies the pattern: "self_t.op(*args)"
+ # 2) "op" in (1) needs to be the same as the op the derivative is for
+ #
+ # (2) may seem too strict, but currently the only ops that satisfy (1) also satisfy (2)
+ # If there is a need, we can relax (2) to allow any op that has an in-place variant
+ is_single_method_on_self_t = False
+ directly_do_inplace = False
+ op_name: str | None = None
+ between_parens: str | None = None
+ match = re.fullmatch(r"self_t.([\w]*)\((.*)\)", formula)
+ if match:
+ op_name, between_parens = match.group(1), match.group(2)
+
+ # We want to...
+ # Match: self_t.op1(other_p.op2(arg))
+ # Avoid: self_t.op1(args) + self_t.op2(args)
+ # Avoid: self_t.op1(other_p.op2(arg)) + self_t.op2(args)
+ def check_parens_nest_level_gt_zero(s: str) -> bool:
+ level = 1
+ for ch in s:
+ if ch == ")":
+ level -= 1
+ if level == 0:
+ return False
+ if ch == "(":
+ level += 1
+ return True
+
+ is_single_method_on_self_t = check_parens_nest_level_gt_zero(
+ between_parens
+ )
+ directly_do_inplace = (
+ is_single_method_on_self_t and op_name == info.name
+ )
+
+ if directly_do_inplace:
+ assert op_name is not None
+ assert between_parens is not None
+ formula = f"self_t_raw.defined() ? self_t_raw.{op_name}_({between_parens}) : {formula}"
+ else:
+ # Make sure that the forward grad is modified inplace when the original formula
+ # is out of place
+ formula = f"self_t_raw.defined() ? self_t_raw.copy_({formula}) : {formula}"
+
+ required_original_self_value = bool(
+ re.search(IDENT_REGEX.format("original_self_p"), formula)
+ ) or bool(re.search(IDENT_REGEX.format("original_self_t"), formula))
+
+ forward_derivatives = [
+ ForwardDerivative(
+ formula=formula,
+ var_names=("self",),
+ var_types=fw_info.var_types,
+ required_inputs_fw_grad=fw_info.required_inputs_fw_grad,
+ required_inputs_primal=required_primals,
+ required_original_self_value=required_original_self_value,
+ is_reusing_outplace_formula=not is_exact_match,
+ ),
+ ]
+
+ fw_derivative_dict[key] = forward_derivatives
+
+ result.append(
+ NativeFunctionWithDifferentiabilityInfo(
+ func=f, info=info_dict, fw_derivatives=fw_derivative_dict
+ )
+ )
+
+ return result
+
+
+def is_differentiable(
+ name: str, type: Type, info: DifferentiabilityInfo | None
+) -> bool:
+ return type.is_tensor_like() and (
+ info is None or name not in info.non_differentiable_arg_names
+ )
+
+
+def gen_differentiable_outputs(
+ fn: NativeFunctionWithDifferentiabilityInfo, key: str = "Default"
+) -> list[DifferentiableOutput]:
+ f = fn.func
+ info = fn.info[key] if fn.info else None
+ outputs: list[DifferentiableOutput] = [
+ DifferentiableOutput(
+ name=name,
+ type=ret.type,
+ cpp_type=cpp.return_type(ret, symint=True).cpp_type(),
+ )
+ for name, ret in zip(cpp.return_names(f), f.func.returns)
+ ]
+ output_differentiability = info.output_differentiability if info else None
+ if output_differentiability is not None:
+ if len(output_differentiability) != len(outputs):
+ raise RuntimeError(
+ f"The length of output_differentiability ({len(output_differentiability)}), "
+ f"does not match the number of outputs ({len(outputs)})."
+ )
+ differentiable_outputs: list[DifferentiableOutput] = []
+ if False in output_differentiability and f.func.kind() == SchemaKind.inplace:
+ raise RuntimeError(
+ "output_differentiability=False for inplace operation (version_counter won't get updated)"
+ )
+ for differentiable, output in zip(output_differentiability, outputs):
+ if differentiable:
+ differentiable_outputs.append(output)
+ return differentiable_outputs
+ candidate_differentiable_outputs = list(
+ filter(lambda r: is_differentiable(r.name, r.type, info), outputs)
+ )
+ if uses_single_grad(info):
+ return candidate_differentiable_outputs[:1]
+ else:
+ return candidate_differentiable_outputs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/cpp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/cpp.py
new file mode 100644
index 0000000000000000000000000000000000000000..7578afe3a0cdd308da7aadb9a5f96bbab3f41bd1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/cpp.py
@@ -0,0 +1,474 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from torchgen import local
+from torchgen.api.types import (
+ ArgName,
+ ArrayCType,
+ ArrayRefCType,
+ BaseCType,
+ BaseTypeToCppMapping,
+ Binding,
+ boolT,
+ ConstRefCType,
+ CType,
+ dimnameListT,
+ intArrayRefT,
+ iTensorListRefT,
+ ListCType,
+ longT,
+ MutRefCType,
+ NamedCType,
+ OptionalCType,
+ optionalIntArrayRefT,
+ optionalSymIntArrayRefT,
+ scalarT,
+ SpecialArgName,
+ symIntArrayRefT,
+ SymIntT,
+ tensorListT,
+ tensorOptionsT,
+ tensorT,
+ TupleCType,
+ VectorCType,
+ voidT,
+)
+from torchgen.model import (
+ Argument,
+ Arguments,
+ BaseTy,
+ BaseType,
+ FunctionSchema,
+ ListType,
+ NativeFunction,
+ OptionalType,
+ Return,
+ SelfArgument,
+ TensorOptionsArguments,
+ Type,
+)
+from torchgen.utils import assert_never
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+# This file describes the translation of JIT schema to the public C++
+# API, which is what people use when they call functions like at::add.
+#
+# Prominent characteristics of the C++ API:
+#
+# - dtype, layout, device and pin_memory are collected into
+# a single C++ type TensorOptions (the native functions API
+# also has this, but tensor options is really most relevant
+# for the C++ API; it makes calling kwarg factory functions
+# pleasant)
+#
+# - defaulting lives here (in fact, the dispatcher is completely
+# oblivious of defaults!)
+#
+# BTW: policy on name collisions: we try not to have types with
+# collisions, but functions are fair game to collide
+
+
+def name(
+ func: FunctionSchema,
+ *,
+ faithful_name_for_out_overloads: bool = False,
+ symint_overload: bool = False,
+) -> str:
+ name = str(func.name.name)
+ if symint_overload:
+ name += "_symint"
+ if func.is_out_fn():
+ if faithful_name_for_out_overloads:
+ name += "_outf"
+ else:
+ name += "_out"
+
+ return name
+
+
+# Translation of "value types" in JIT schema to C++ API type. Value
+# types look the same no matter if they are argument types or return
+# types. Returns None if the type in question is not a value type.
+def valuetype_type(
+ t: Type,
+ *,
+ binds: ArgName,
+ mutable: bool = True,
+ remove_non_owning_ref_types: bool = False,
+ symint: bool = False,
+) -> NamedCType | None:
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor or t.name == BaseTy.Scalar:
+ return None
+ elif str(t) == "SymInt":
+ if symint:
+ return NamedCType(binds, BaseCType(SymIntT))
+ else:
+ return NamedCType(binds, BaseCType(longT))
+ if remove_non_owning_ref_types:
+ if t.name == BaseTy.str:
+ raise AssertionError(
+ "string ref->value conversion: not implemented yet"
+ )
+ # All other BaseType currently map directly to BaseCppTypes.
+ return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
+ elif isinstance(t, OptionalType):
+ elem = valuetype_type(t.elem, binds=binds, mutable=mutable, symint=symint)
+ if elem is None:
+ return None
+ return NamedCType(binds, OptionalCType(elem.type))
+ elif isinstance(t, ListType):
+ if str(t.elem) == "bool":
+ assert t.size is not None
+ return NamedCType(binds, ArrayCType(BaseCType(boolT), t.size))
+ else:
+ return None
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Translation of types occurring in JIT arguments to a C++ argument type.
+# If remove_non_owning_ref_types is set, we'll guarantee that the outputed CType is not a non-owning reference type.
+# For example, we'll return std::vector instead of IntArrayRef.
+# See Note [translation from C++ reference to value types]
+def argumenttype_type(
+ t: Type,
+ *,
+ mutable: bool,
+ binds: ArgName,
+ remove_non_owning_ref_types: bool = False,
+ symint: bool = False,
+) -> NamedCType:
+ # If it's a value type, do the value type translation
+ r = valuetype_type(
+ t,
+ binds=binds,
+ mutable=mutable,
+ symint=symint,
+ remove_non_owning_ref_types=remove_non_owning_ref_types,
+ )
+ if r is not None:
+ return r
+
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor:
+ if mutable and not local.use_const_ref_for_mutable_tensors():
+ return NamedCType(binds, MutRefCType(BaseCType(tensorT)))
+ else:
+ return NamedCType(binds, ConstRefCType(BaseCType(tensorT)))
+ elif t.name == BaseTy.Scalar:
+ return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+ else:
+ raise AssertionError(f"base type should have been value type {t}")
+ elif isinstance(t, OptionalType):
+ if str(t.elem) == "Tensor":
+ if mutable and not local.use_const_ref_for_mutable_tensors():
+ return NamedCType(
+ binds, MutRefCType(BaseCType(tensorT))
+ ) # TODO: fix this discrepancy
+ else:
+ return NamedCType(
+ binds, ConstRefCType(OptionalCType(BaseCType(tensorT)))
+ )
+ elif str(t.elem) == "Scalar":
+ return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
+ elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int":
+ return NamedCType(binds, BaseCType(optionalIntArrayRefT))
+ elif isinstance(t.elem, ListType) and str(t.elem.elem) == "SymInt":
+ if symint:
+ return NamedCType(binds, BaseCType(optionalSymIntArrayRefT))
+ else:
+ return NamedCType(binds, BaseCType(optionalIntArrayRefT))
+ elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint)
+ return NamedCType(binds, OptionalCType(elem.type))
+ elif isinstance(t, ListType):
+ # TODO: remove these special cases, ArrayRef fallthrough works fine
+ if str(t.elem) == "int":
+ if remove_non_owning_ref_types:
+ return NamedCType(binds, VectorCType(BaseCType(longT)))
+ else:
+ return NamedCType(binds, BaseCType(intArrayRefT))
+ if str(t.elem) == "SymInt":
+ if remove_non_owning_ref_types:
+ if symint:
+ return NamedCType(binds, VectorCType(BaseCType(SymIntT)))
+ else:
+ return NamedCType(binds, VectorCType(BaseCType(longT)))
+ else:
+ if symint:
+ return NamedCType(binds, BaseCType(symIntArrayRefT))
+ else:
+ return NamedCType(binds, BaseCType(intArrayRefT))
+ if str(t.elem) == "Tensor":
+ if local.use_ilistref_for_tensor_lists():
+ return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT)))
+ else:
+ return NamedCType(binds, BaseCType(tensorListT))
+ elif str(t.elem) == "Scalar":
+ return NamedCType(binds, ArrayRefCType(BaseCType(scalarT)))
+ elif str(t.elem) == "Dimname":
+ return NamedCType(binds, BaseCType(dimnameListT))
+ elif str(t.elem) == "Tensor?":
+ return NamedCType(
+ binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT))))
+ )
+ elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint)
+ return NamedCType(binds, ArrayRefCType(elem.type))
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Translate a JIT argument into its C++ type
+def argument_type(a: Argument, *, binds: ArgName, symint: bool = False) -> NamedCType:
+ return argumenttype_type(a.type, mutable=a.is_write, symint=symint, binds=binds)
+
+
+# Translation of a (non-multi) return type from JIT to C++
+# N.B: returntype_type returns a CType, not a NamedCType.
+# This is mostly because of the mismatch between return types and return names.
+# e.g. a function with a return type of 'void' has 0 return names,
+# and a function with a return type of 'std::tuple' has >1 return name.
+def returntype_type(t: Type, *, mutable: bool, symint: bool = False) -> CType:
+ # placeholder is ignored
+ # NB: symint is ALWAYS respected for return types. So symint argument
+ # here is IGNORED
+ r = valuetype_type(t, binds="__placeholder__", mutable=mutable, symint=True)
+ if r is not None:
+ return r.type
+
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor:
+ if mutable:
+ if local.use_const_ref_for_mutable_tensors():
+ return ConstRefCType(BaseCType(tensorT))
+ else:
+ return MutRefCType(BaseCType(tensorT))
+ else:
+ # Note [Tensor Copy Returns]
+ # Currently, we use "Argument.is_write" to determine
+ # whether or not Tensor return types should be copies or references.
+ # If that ever changes, take a look at other locations of this note!
+ return BaseCType(tensorT)
+ elif t.name == BaseTy.Scalar:
+ return BaseCType(scalarT)
+ elif isinstance(t, ListType):
+ assert not mutable, "Native functions should never return a mutable tensor list. They should return void."
+ elem = returntype_type(t.elem, mutable=False)
+ assert t.size is None, f"fixed size list returns not supported: {t}"
+ return VectorCType(elem)
+ elif isinstance(t, OptionalType):
+ elem = returntype_type(t.elem, mutable=mutable)
+ if str(t.elem) == "Tensor":
+ return OptionalCType(elem)
+
+ raise AssertionError(f"unrecognized return type {t}")
+
+
+# Translation of a single return to its C++ type
+def return_type(r: Return, *, symint: bool = False) -> CType:
+ return returntype_type(r.type, mutable=r.is_write, symint=symint)
+
+
+# Translation of a full (possibly multi) return from JIT to its C++ type
+def returns_type(rs: Sequence[Return], *, symint: bool = False) -> CType:
+ if len(rs) == 0:
+ return BaseCType(voidT)
+ elif len(rs) == 1:
+ return return_type(rs[0], symint=symint)
+ else:
+ return TupleCType([return_type(r, symint=symint) for r in rs])
+
+
+def return_names(f: NativeFunction, *, fallback_name: str = "result") -> Sequence[str]:
+ returns: list[str] = []
+ for i, r in enumerate(f.func.returns):
+ # If we have an inplace function, the return argument is
+ # implicitly named self.
+ # TODO: Consider incorporating this into the data model
+ if f.func.name.name.inplace:
+ assert i == 0, "illegal inplace function with multiple returns"
+ name = "self"
+ # If we are out function, the name is the name of the
+ # corresponding output function (r.name will get recorded
+ # in field_name later.)
+ elif f.func.is_out_fn():
+ name = f.func.arguments.out[i].name
+ # If the return argument is explicitly named...
+ elif r.name:
+ name_conflict = any(
+ r.name == a.name for a in f.func.schema_order_arguments()
+ )
+ if name_conflict and not f.func.is_out_fn():
+ name = f"{r.name}_return"
+ else:
+ name = r.name
+ # If there is no explicit name and no fallback name was passed in, we just name the output result,
+ # unless it's a multi-return, in which case it's result0,
+ # result1, etc (zero-indexed)
+ else:
+ name = fallback_name if len(f.func.returns) == 1 else f"{fallback_name}{i}"
+ returns.append(name)
+ return returns
+
+
+JIT_TO_CPP_DEFAULT = {
+ "False": "false",
+ "True": "true",
+ "None": "::std::nullopt", # UGH this one is type directed
+ "Mean": "at::Reduction::Mean",
+ "[]": "{}",
+ "contiguous_format": "c10::MemoryFormat::Contiguous",
+ "long": "at::kLong",
+}
+
+
+# Convert a JIT default into C++ expression representing the default
+def default_expr(d: str, t: Type, *, symint: bool) -> str:
+ if d == "None" and str(t) == "Tensor?":
+ return "{}"
+ if isinstance(t, BaseType) and t.name is BaseTy.str:
+ # Schema allows single quotes but C++ needs double
+ if len(d) >= 2 and d[0] == "'" and d[-1] == "'":
+ s = ""
+ i = 1
+ while i + 1 < len(d):
+ if d[i] != "\\":
+ if d[i] == '"':
+ s += '\\"'
+ else:
+ s += d[i]
+ i += 1
+ else:
+ if d[i + 1] == "'":
+ s += "'"
+ else:
+ s += d[i : i + 2]
+ i += 2
+
+ return f'"{s}"'
+
+ if isinstance(t, OptionalType):
+ if d == "None":
+ return "::std::nullopt"
+
+ return default_expr(d, t.elem, symint=symint)
+
+ if isinstance(t, ListType):
+ if d.startswith("[") and d.endswith("]"):
+ return "{" + d[1:-1] + "}"
+ elif symint and d.isdigit() and str(t.elem) == "SymInt":
+ return f"c10::SymInt({d})"
+ elif t.size is None:
+ # NOTE: Sized lists can have scalar defaults
+ raise ValueError(f"Expected a list default '[...]' but found: '{d}'")
+
+ return JIT_TO_CPP_DEFAULT.get(d, d)
+
+
+# Convert an argument into its C++ API form
+
+
+def argument(
+ a: Argument | TensorOptionsArguments | SelfArgument,
+ *,
+ cpp_no_default_args: set[str],
+ method: bool,
+ faithful: bool,
+ symint: bool = False,
+ has_tensor_options: bool,
+) -> list[Binding]:
+ def sub_argument(
+ a: Argument | TensorOptionsArguments | SelfArgument,
+ ) -> list[Binding]:
+ return argument(
+ a,
+ cpp_no_default_args=cpp_no_default_args,
+ method=method,
+ faithful=faithful,
+ symint=symint,
+ has_tensor_options=has_tensor_options,
+ )
+
+ if isinstance(a, Argument):
+ binds: ArgName
+ if a.name == "memory_format" and has_tensor_options:
+ binds = SpecialArgName.possibly_redundant_memory_format
+ else:
+ binds = a.name
+ default: str | None = None
+ if a.name not in cpp_no_default_args and a.default is not None:
+ default = default_expr(a.default, a.type, symint=symint)
+ return [
+ Binding(
+ nctype=argument_type(a, binds=binds, symint=symint),
+ name=a.name,
+ default=default,
+ argument=a,
+ )
+ ]
+ elif isinstance(a, TensorOptionsArguments):
+ if faithful:
+ return (
+ sub_argument(a.dtype)
+ + sub_argument(a.layout)
+ + sub_argument(a.device)
+ + sub_argument(a.pin_memory)
+ )
+ else:
+ default = None
+ # Enforced by NativeFunction.__post_init__
+ assert "options" not in cpp_no_default_args
+ if all(x.default == "None" for x in a.all()):
+ default = "{}"
+ elif a.dtype.default == "long":
+ default = "at::kLong" # TODO: this is wrong
+ return [
+ Binding(
+ nctype=NamedCType("options", BaseCType(tensorOptionsT)),
+ name="options",
+ default=default,
+ argument=a,
+ )
+ ]
+ elif isinstance(a, SelfArgument):
+ if method:
+ # Caller is responsible for installing implicit this in context!
+ return []
+ else:
+ return sub_argument(a.argument)
+ else:
+ assert_never(a)
+
+
+def arguments(
+ arguments: Arguments,
+ *,
+ faithful: bool,
+ symint: bool = False,
+ method: bool,
+ cpp_no_default_args: set[str],
+) -> list[Binding]:
+ args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+ if faithful:
+ args.extend(arguments.non_out)
+ args.extend(arguments.out)
+ else:
+ args.extend(arguments.out)
+ args.extend(arguments.non_out)
+ return [
+ r.no_default() if faithful else r
+ for a in args
+ for r in argument(
+ a,
+ faithful=faithful,
+ symint=symint,
+ method=method,
+ has_tensor_options=arguments.tensor_options is not None,
+ cpp_no_default_args=cpp_no_default_args,
+ )
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/dispatcher.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/dispatcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..99c61a127e871f09b18fa7ffca16e6100194d182
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/dispatcher.py
@@ -0,0 +1,124 @@
+from __future__ import annotations
+
+import itertools
+from typing import TYPE_CHECKING
+
+from torchgen.api import cpp
+from torchgen.api.types import ArgName, Binding, CType, NamedCType
+from torchgen.model import (
+ Argument,
+ FunctionSchema,
+ Return,
+ SelfArgument,
+ TensorOptionsArguments,
+ Type,
+)
+from torchgen.utils import assert_never, concatMap
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+# This file describes the translation of JIT schema to the dispatcher
+# API, the *unboxed* calling convention by which invocations through
+# the dispatcher are made. Historically, the dispatcher API matched
+# the C++ API, but with the establishment of the boxed API, we've
+# made changes to the dispatcher API to so that the unboxed API
+# better aligns with the boxed API. The dispatcher API hooks heavily
+# into our template based boxing/unboxing machinery, so changes
+# to this convention will usually need template updates too.
+#
+# Prominent characteristics of the dispatcher API:
+#
+# - dtype, layout, device and pin_memory are represented as separate
+# arguments.
+#
+
+
+def name(func: FunctionSchema) -> str:
+ return cpp.name(func)
+
+
+def argumenttype_type(
+ t: Type,
+ *,
+ mutable: bool,
+ binds: ArgName,
+ remove_non_owning_ref_types: bool = False,
+ symint: bool = True,
+) -> NamedCType:
+ # This is a faux amis. If it makes sense in the future to add
+ # more special cases here, or invert things so cpp.argument_type
+ # calls this, or just completely inline the function, please do
+ # it.
+ return cpp.argumenttype_type(
+ t,
+ mutable=mutable,
+ binds=binds,
+ symint=symint,
+ remove_non_owning_ref_types=remove_non_owning_ref_types,
+ )
+
+
+def argument_type(
+ a: Argument,
+ *,
+ binds: ArgName,
+ remove_non_owning_ref_types: bool = False,
+ symint: bool = True,
+) -> NamedCType:
+ return argumenttype_type(
+ a.type,
+ mutable=a.is_write,
+ binds=binds,
+ remove_non_owning_ref_types=remove_non_owning_ref_types,
+ symint=symint,
+ )
+
+
+def returns_type(rs: Sequence[Return], *, symint: bool = True) -> CType:
+ # At present, there is no difference. But there could be!
+ return cpp.returns_type(rs, symint=symint)
+
+
+def jit_arguments(func: FunctionSchema) -> list[Argument]:
+ def to_argument(
+ a: Argument | TensorOptionsArguments | SelfArgument,
+ ) -> list[Argument]:
+ if isinstance(a, Argument):
+ return [a]
+ elif isinstance(a, SelfArgument):
+ return [a.argument]
+ elif isinstance(a, TensorOptionsArguments):
+ return [a.dtype, a.layout, a.device, a.pin_memory]
+ else:
+ assert_never(a)
+
+ return list(
+ concatMap(
+ to_argument,
+ itertools.chain(
+ func.arguments.positional, func.arguments.kwarg_only, func.arguments.out
+ ),
+ )
+ )
+
+
+def argument(
+ a: Argument, *, remove_non_owning_ref_types: bool = False, symint: bool = True
+) -> Binding:
+ return Binding(
+ nctype=argument_type(
+ a,
+ binds=a.name,
+ remove_non_owning_ref_types=remove_non_owning_ref_types,
+ symint=symint,
+ ),
+ name=a.name,
+ argument=a,
+ )
+
+
+def arguments(func: FunctionSchema, *, symint: bool = True) -> list[Binding]:
+ return [argument(a, symint=symint) for a in jit_arguments(func)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/functionalization.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/functionalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d2adb7555ead8a7afabacff20e5616ece3c688f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/functionalization.py
@@ -0,0 +1,199 @@
+from __future__ import annotations
+
+from torchgen.api import dispatcher
+from torchgen.api.types import (
+ BaseCppType,
+ BaseCType,
+ Binding,
+ boolT,
+ ConstRefCType,
+ CType,
+ longT,
+ NamedCType,
+ tensorT,
+)
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ FunctionSchema,
+ NativeFunction,
+ NativeFunctionsViewGroup,
+)
+
+
+# This file describes the translation of JIT schema to API's used
+# when creating view lambdas that are used by the functionalization pass.
+# There are two types of lambdas: forward lambdas and reverse lambdas.
+# These API's mostly follow the dispatcher API, with a few quirks:
+# - The lambda capture has to convert reference types to value types
+# - While the forward lambda just directly calls into the at::_ops API
+# (following the dispatcher convention), the logic here for the reverse lambda
+# is responsible for generating both the call-site, and the declarations
+# (which are implemented manually in the at::functionalization::impl namespace).
+
+# The lambdas generated for each view op in the functionalization pass are of the form
+# [capture_arguments](outer_arguments) -> returns_type {
+# return name(inner_arguments);
+# }
+
+# Define some specific lambda input arguments.
+base_binding = Binding(
+ name="base",
+ nctype=NamedCType(name="base", type=ConstRefCType(BaseCType(tensorT))),
+ argument=Argument(
+ name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
+ ),
+ default=None,
+)
+mutated_view_binding = Binding(
+ name="mutated_view",
+ nctype=NamedCType(name="mutated_view", type=ConstRefCType(BaseCType(tensorT))),
+ argument=Argument(
+ name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
+ ),
+ default=None,
+)
+mutated_view_idx_binding = Binding(
+ name="mutated_view_idx",
+ nctype=NamedCType(name="mutated_view_idx", type=BaseCType(longT)),
+ argument=Argument(
+ name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
+ ),
+ default=None,
+)
+reapply_views_binding = Binding(
+ name="reapply_views",
+ nctype=NamedCType(name="reapply_views", type=BaseCType(boolT)),
+ argument=Argument(
+ name="reapply_views", type=BaseType(BaseTy.bool), default=None, annotation=None
+ ),
+ default=None,
+)
+
+InverseReturnModeT = BaseCppType("at::functionalization", "InverseReturnMode")
+inverse_return_mode_binding = Binding(
+ name="inverse_return_mode",
+ nctype=NamedCType(name="inverse_return_mode", type=BaseCType(InverseReturnModeT)),
+ argument=Argument(
+ name="inverse_return_mode",
+ # NB: not actually a bool but it doesn't matter because this isn't used
+ type=BaseType(BaseTy.bool),
+ default=None,
+ annotation=None,
+ ),
+ default=None,
+)
+
+
+# The lambda capture itself doesn't have a name.
+# The name returned here corresponds to the name of the inner function called by the lambda.
+def name(
+ g: NativeFunctionsViewGroup,
+ *,
+ is_reverse: bool,
+ include_namespace: bool,
+ reapply_views: bool | None = None,
+) -> str:
+ if reapply_views is None:
+ # reapply_views is only important for the fwd lambda,
+ # since we always plumb the runtime "reapply_views" argument into the reverse function.
+ assert is_reverse
+ if is_reverse:
+ return reverse_name(g.view, include_namespace)
+ # in the forward case, we just directly call into the at::_ops API (so we always need the namespace)
+ assert include_namespace
+ assert g.view_copy is not None
+ api_name = (
+ g.view.func.name.unambiguous_name()
+ if reapply_views
+ else g.view_copy.func.name.unambiguous_name()
+ )
+ return f"at::_ops::{api_name}::call"
+
+
+def reverse_name(f: NativeFunction, include_namespace: bool) -> str:
+ # for the reverse: we plumb the "reapply_views" flag into that function and support
+ # both copy and non-copy variants. (We could avoid doing that, but that would require
+ # writing out twice as many view inverse functions).
+ api_name = f.func.name.unambiguous_name()
+ # in the reverse case, we codegen both the call-sites (which need the full namespace) and the declarations (which don't)
+ if include_namespace:
+ return f"at::functionalization::FunctionalInverses::{api_name}_inverse"
+ else:
+ return f"{api_name}_inverse"
+
+
+def capture_arguments(func: FunctionSchema, *, is_reverse: bool) -> list[Binding]:
+ # capture arguments include all arguments except `self`.
+ # Importantly, they don't include any C++ reference types (or else we'll get a dangling reference in the capture),
+ # So any reference types (IntArrayRef) need to be converted to value types (vector)
+ args = func.arguments.flat_all
+ assert args[0].type == BaseType(BaseTy.Tensor)
+ non_self_args = args[1:]
+ non_self_value_bindings = [
+ dispatcher.argument(a, remove_non_owning_ref_types=True) for a in non_self_args
+ ]
+
+ all_bindings = [
+ inverse_return_mode_binding if is_reverse else reapply_views_binding
+ ]
+ all_bindings.extend(non_self_value_bindings)
+ return all_bindings
+
+
+def returns_type(func: FunctionSchema) -> CType:
+ # Assertion: all view ops return tensor-like outputs
+ assert len(func.returns) >= 1
+ for ret in func.returns:
+ assert ret.type.is_tensor_like()
+ # However, the return type of the lambda is always an individual tensor.
+ # For multi-tensor outputs, each tensor needs to be tracked individually.
+ return BaseCType(tensorT)
+
+
+def outer_arguments(*, is_reverse: bool) -> list[Binding]:
+ if is_reverse:
+ return [base_binding, mutated_view_binding, mutated_view_idx_binding]
+ else:
+ return [base_binding, mutated_view_idx_binding]
+
+
+def inner_call_index(func: FunctionSchema) -> Binding | None:
+ # For view ops that return multiple tensors (like `split`), we generate a separate lambda for each output.
+ # When we replay a view op that returns multiple tensors, we need to index into the output appropriately
+ if len(func.returns) > 1 or (
+ len(func.returns) == 1 and func.returns[0].type.is_list_like()
+ ):
+ return mutated_view_idx_binding
+ return None
+
+
+def inner_arguments(func: FunctionSchema, is_reverse: bool) -> list[Binding]:
+ args = func.arguments.flat_all
+ assert args[0].type == BaseType(BaseTy.Tensor)
+ non_self_args = args[1:]
+ # The forward lambda calls the at::_ops API, while the reverse lambda calls the view inverse API.
+ # Both of these follow the dispatcher API.
+ non_self_bindings = [dispatcher.argument(a) for a in non_self_args]
+ if not is_reverse:
+ # the forward lambda swaps out the original tensor argument with the lambd arg "base"
+ return [base_binding] + non_self_bindings
+ else:
+ # the reverse lambda does the same, but with an additional "mutated_view" arg
+ # additionally, we have a calling convention: for view ops that return multiple tensor outputs
+ # their corresponding view_inverse function takes in an additional index argument.
+ index_binding = inner_call_index(func)
+ if index_binding is not None:
+ return [
+ base_binding,
+ mutated_view_binding,
+ inverse_return_mode_binding,
+ index_binding,
+ ] + non_self_bindings
+ else:
+ return [
+ base_binding,
+ mutated_view_binding,
+ inverse_return_mode_binding,
+ ] + non_self_bindings
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/lazy.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/lazy.py
new file mode 100644
index 0000000000000000000000000000000000000000..99cc1fed962fecf19ca2d46d9a964967a252f9ca
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/lazy.py
@@ -0,0 +1,468 @@
+from __future__ import annotations
+
+from typing import Any
+
+from torchgen.api.types import (
+ BaseCppType,
+ BaseCType,
+ boolT,
+ CType,
+ deviceT,
+ doubleT,
+ generatorT,
+ layoutT,
+ ListCType,
+ longT,
+ memoryFormatT,
+ NamedCType,
+ OptionalCType,
+ scalarT,
+ scalarTypeT,
+ stringT,
+ SymIntT,
+ VectorCType,
+)
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ FunctionSchema,
+ ListType,
+ OperatorName,
+ OptionalType,
+ Return,
+ TensorOptionsArguments,
+ Type,
+)
+
+
+_valueT: BaseCppType | None = None
+
+
+# A ValueT is an IR type which represents the computation of a Tensor. In other
+# words, a PyTorch user will do operations on lazy tensors, and each output lazy
+# tensor internally tracks a ValueT representing the IR node that would have
+# actually produced the value of this tensor for real.
+#
+# This is configurable because different lazy tensor backends (LTC vs XLA) will
+# have different IR representations. (Though, arguably, after unification they
+# shouldn't!)
+def getValueT() -> BaseCppType:
+ global _valueT
+ if not _valueT:
+ raise NotImplementedError(
+ "The value type needs to be set with setValueT() in run_gen_lazy_tensor()"
+ )
+
+ return _valueT
+
+
+def setValueT(val: BaseCppType) -> None:
+ global _valueT
+ _valueT = val
+
+
+# this is a bad hack. I need to refactor the data model to represent each arg in the schema as an object,
+# making it easier to represent special properties of an arg.
+tensorListValueT = BaseCppType("torch::lazy", "Value")
+
+
+def process_ir_type(
+ typ: Type, properties: LazyIrProperties, *, symint: bool
+) -> BaseCType | VectorCType | OptionalCType | ListCType:
+ """
+ This function takes a type from NativeFunctions and converts it for use with
+ lazy tensor codegen.
+
+ Type conversion for lazy currently consists of
+ (1) changing at::Tensors into lazy::Values
+ (2) wrapping everything in a BaseCType
+ (3) making cpp-reference types into cpp-value types (e.g. vector instead of IntArrayRef)
+
+ (1) converts at::Tensors to lazy::Values (which wrap lazy::Nodes, with which Lazy IR represents tensors.)
+ There is special handling for Optional[Tensor] or list[Tensor], etc- hence 'tensor-like'
+
+ This is incomplete- there are assertions in places that it's expected to need to add
+ more types as the codegen is used with more operators.
+ """
+ if isinstance(typ, BaseType):
+ if typ.name == BaseTy.Tensor:
+ return BaseCType(getValueT())
+ elif typ.name == BaseTy.Scalar:
+ if properties.TreatScalarsAsConstants:
+ return BaseCType(scalarT)
+ # at::scalar has special handling,
+ # and is wrapped in an lazy::Value just like at::tensor
+ return BaseCType(getValueT())
+ elif typ.name == BaseTy.ScalarType:
+ return BaseCType(scalarTypeT)
+ elif typ.name == BaseTy.int:
+ return BaseCType(longT)
+ elif typ.name == BaseTy.SymInt:
+ if symint:
+ return BaseCType(getValueT())
+ else:
+ return BaseCType(longT)
+ elif typ.name == BaseTy.bool:
+ return BaseCType(boolT)
+ elif typ.name == BaseTy.float:
+ return BaseCType(doubleT)
+ elif typ.name == BaseTy.str:
+ return BaseCType(stringT)
+ elif typ.name == BaseTy.Device:
+ return BaseCType(deviceT)
+ elif typ.name == BaseTy.Generator:
+ return BaseCType(generatorT)
+ elif typ.name == BaseTy.Layout:
+ return BaseCType(layoutT)
+ elif typ.name == BaseTy.MemoryFormat:
+ return BaseCType(memoryFormatT)
+ else:
+ raise AssertionError(f"TODO add support for type {repr(typ)}")
+ elif isinstance(typ, OptionalType):
+ return OptionalCType(process_ir_type(typ.elem, properties, symint=symint))
+ elif isinstance(typ, ListType):
+ if str(typ.elem) == "Tensor?":
+ # TODO(whc) is this actually correct? or should it use a Vector like above
+ return ListCType(OptionalCType(BaseCType(getValueT())))
+ elif str(typ.elem) == "Tensor":
+ # this is a TensorList which comes in from GetTensorList as a Value
+ return BaseCType(tensorListValueT)
+ elif typ.elem == BaseType(BaseTy.SymInt):
+ # TODO: return a value type. The problem here is analogous to
+ # the problem with tensorListValueT: if you have SymInt[] you
+ # cannot conveniently save the list of Value directly, as nodes
+ # expect to save values as a vector for ALL arguments. So you
+ # need a separate IR node that represents all of the size nodes
+ # assembled into a list. I'm not an LTC dev so I don't want to
+ # figure it out right now. Y'all figure it out...
+ return VectorCType(BaseCType(longT))
+
+ else:
+ return VectorCType(process_ir_type(typ.elem, properties, symint=symint))
+ else:
+ raise AssertionError(f"unrecognized type {repr(typ)}")
+
+
+# TODO: Determining this based off of CType is bad; this should be computed
+# from Type directly; then the same logic as process_ir_type can be used
+#
+# Invariant: passed typ should be an *owning* CType (e.g., we will report
+# that ArrayRef is NOT a value type)
+def isValueType(typ: CType, properties: LazyIrProperties | None = None) -> bool:
+ """
+ Given a type, determine if it is a Value-like type. This is equivalent to
+ being Tensor-like, but assumes the type has already been transformed.
+ """
+ if isinstance(typ, BaseCType):
+ # I am regretting my naming conventions, but now we are wrapping at::scalar in
+ # lazy value, while preserving other 'scalar' types as scalars in the IR
+ treat_scalars_as_constants = properties and properties.TreatScalarsAsConstants
+ return (
+ typ.type == getValueT()
+ or (typ.type == scalarT and not treat_scalars_as_constants)
+ or typ.type == SymIntT
+ )
+ elif typ == VectorCType(BaseCType(SymIntT)):
+ # TODO: report True for this
+ return False
+ elif isinstance(typ, (OptionalCType, ListCType, VectorCType)):
+ return isValueType(typ.elem, properties)
+ return False
+
+
+def isSymIntType(typ: Type) -> bool:
+ return isinstance(typ, BaseType) and typ.name == BaseTy.SymInt
+
+
+def isWrappedScalarType(typ: Type) -> bool:
+ """
+ Given a type, determine if it is a c10::scalar which we will wrap in a lazy Value.
+ Since we literally change the type from scalarT to valueT, information is lost.
+ This function helps build a list of wrapped scalars to save that information
+ """
+ if isinstance(typ, BaseType):
+ # I am regretting my naming conventions, but now we are wrapping at::scalar in
+ # lazy value, while preserving other 'scalar' types as scalars in the IR
+ return typ.name == BaseTy.Scalar
+ elif isinstance(typ, (OptionalType, ListType)):
+ return isWrappedScalarType(typ.elem)
+ return False
+
+
+# TODO: dedupe with Type.is_generator_like
+def isGeneratorType(typ: Type) -> bool:
+ if isinstance(typ, BaseType):
+ return typ.name == BaseTy.Generator
+ elif isinstance(typ, (OptionalType)):
+ return isGeneratorType(typ.elem)
+ return False
+
+
+# This class caches a few derived properties computed from an Argument
+# and LazyIrProperties
+class LazyArgument:
+ name: str
+ orig_type: Type
+ lazy_type_: CType | None
+ is_wrapped_scalar: bool
+ is_generator: bool
+ # TODO: this is lies, it is false for symint list
+ is_symint_or_list: bool
+
+ # Whether or not we are treating this as symint or not
+ symint: bool
+
+ # true if this argument is or contains a lazy IR value
+ is_lazy_value: bool
+
+ def __init__(
+ self, arg: Argument, properties: LazyIrProperties, *, symint: bool
+ ) -> None:
+ self.name = arg.name
+ self.orig_type = arg.type
+ self.symint = symint
+ self.is_optional = isinstance(arg.type, OptionalType)
+ self.is_generator = isGeneratorType(arg.type)
+ self.lazy_type_ = process_ir_type(arg.type, properties, symint=symint)
+ self.is_wrapped_scalar = isWrappedScalarType(arg.type)
+ self.is_symint_or_list = symint and (
+ isSymIntType(arg.type)
+ or (isinstance(arg.type, OptionalType) and isSymIntType(arg.type.elem))
+ # TODO: lists of symints are not currently treated as value types
+ # or (isinstance(arg.type, ListType) and isSymIntType(arg.type.elem))
+ )
+
+ self.is_lazy_value = isValueType(self.lazy_type, properties)
+
+ @property
+ def lazy_type(self) -> CType:
+ assert (
+ self.lazy_type_ is not None
+ ), f"Attempted to access lazy_type for invalid argument {self.name}"
+ return self.lazy_type_
+
+
+class LazyIrProperties:
+ """Collection of properties for an IR node
+
+ The property groups are listed below. Each group is mutually
+ exclusive, meaning that only one property from each group can be True
+ at any one time. The properties can be accessed as if they were normal
+ attributes. The mutual exclusivity is automatically handled.
+ """
+
+ Properties: tuple[tuple[str, ...], ...] = (
+ (
+ "ShapePrecompute", # Assume shape has been precomputed
+ "ShapeCompute", # Need to compute the shape on construction
+ "ShapeCache", # Utilize the shape cache to defer computation
+ ),
+ (
+ "Lower", # Codegen full lower function
+ "LowerDeclOnly", # Codegen only lower function declaration
+ ),
+ (
+ "CanBeReused", # Codegen full reuse function
+ "CanBeReusedDeclOnly", # Codegen only reuse function declaration
+ ),
+ (
+ "CreateFn", # Codegen full create function
+ "CreateFnDeclOnly", # Codegen only create function declaration
+ ),
+ (
+ "TreatScalarsAsConstants", # Treat Scalars as constants instead of handling like values
+ ),
+ )
+
+ def __init__(self, *default_properties: str) -> None:
+ properties: dict[tuple[str, ...], str | None] = dict.fromkeys(
+ LazyIrProperties.Properties
+ )
+ self.__dict__["properties"] = properties
+ for p in default_properties:
+ setattr(self, p, True)
+
+ def __getattr__(self, key: str) -> Any:
+ properties = self.__dict__["properties"]
+ for values in LazyIrProperties.Properties:
+ if key in values:
+ return properties[values] == key
+
+ return self.__getattribute__(key)
+
+ def __setattr__(self, key: str, value: Any) -> Any:
+ properties = self.__dict__["properties"]
+ for values in LazyIrProperties.Properties:
+ if key in values:
+ properties[values] = key if value else None
+ return value
+
+ raise KeyError(f"Invalid property: {key}")
+
+
+# Inspired by a FunctionSchema object, a LazyIrSchema holds the schema of a Lazy IR node.
+# Unlike a FunctionSchema, it has no round-trippable string form (relating to the YAML),
+# but carries type information from a native FunctionSchema modified for use with IR nodes,
+# and preserving original argument names.
+#
+# TODO: This is not idiomatic with how other torchgen APIs transform on schema.
+class LazyIrSchema:
+ # The name of the operator this function schema describes.
+ name: OperatorName
+
+ positional_args: tuple[LazyArgument, ...]
+ keyword_args: tuple[LazyArgument, ...]
+
+ # TODO: Need to handle collisions with argument names at some point
+ returns: tuple[Return, ...]
+
+ # if this schema has a Generator arg, list its orig ctype/name but don't
+ # build a LazyArgument since lazy IR doesn't support it
+ generator_arg: NamedCType | None = None
+
+ # original function schema
+ func: FunctionSchema
+
+ # Whether or not we are code-genning for SymInt or not
+ symint: bool
+
+ properties: LazyIrProperties = LazyIrProperties(
+ # default properties
+ "ShapePrecompute",
+ "Lower",
+ "CanBeReused",
+ )
+ opkind: str | None = None
+
+ def __init__(
+ self,
+ func: FunctionSchema,
+ properties: LazyIrProperties | None = None,
+ *,
+ symint: bool,
+ ) -> None:
+ if properties:
+ self.properties = properties
+
+ self.func = func
+ self.symint = symint
+ positional_args: list[LazyArgument] = []
+ for arg_field in ["pre_self_positional", "self_arg", "post_self_positional"]:
+ if arg_field == "self_arg" and func.arguments.self_arg is not None:
+ arg = func.arguments.self_arg.argument
+ positional_args.append(
+ LazyArgument(arg, self.properties, symint=symint)
+ )
+ elif getattr(func.arguments, arg_field) is not None:
+ positional_args.extend(
+ LazyArgument(arg, self.properties, symint=symint)
+ for arg in getattr(func.arguments, arg_field)
+ )
+ self.positional_args = tuple(positional_args)
+
+ keyword_args: list[LazyArgument] = []
+ for arg_field in [
+ "pre_tensor_options_kwarg_only",
+ "tensor_options",
+ "post_tensor_options_kwarg_only",
+ "out",
+ ]:
+ curr_args = getattr(func.arguments, arg_field)
+ if curr_args is not None:
+ if isinstance(curr_args, TensorOptionsArguments):
+ curr_args = curr_args.all()
+ for arg in curr_args:
+ if isGeneratorType(arg.type):
+ assert (
+ self.generator_arg is None
+ ), "We expect there is only one generator arg"
+ self.generator_arg = NamedCType(
+ arg.name,
+ arg.type, # type:ignore[arg-type]
+ )
+ keyword_args.extend(
+ LazyArgument(arg, self.properties, symint=symint)
+ for arg in curr_args
+ )
+ self.keyword_args = tuple(keyword_args)
+ self.name = func.name
+ self.returns = func.returns
+
+ @property
+ def node_name(self) -> str:
+ """
+ Return camel-case version of op in node.
+
+ Note: This function also appends any `overload_name` in the operation.
+ For example, if the op is `bitwise_and.Tensor`, the returned name
+ will be `BitwiseAndTensor`.
+ """
+ op_name = f"{self.name.name}_{self.name.overload_name}".lower()
+ return "".join(word.capitalize() or "" for word in op_name.split("_"))
+
+ @property
+ def aten_name(self) -> str:
+ return str(self.name.name)
+
+ @property
+ def base_name(self) -> str:
+ return f"{self.name.name.base}"
+
+ def filtered_args(
+ self,
+ positional: bool = True,
+ keyword: bool = True,
+ values: bool = True,
+ scalars: bool = True,
+ generator: bool = True,
+ ) -> list[LazyArgument]:
+ # This function maintains the sorted order of arguments but provides different filtered views.
+ # Some parts of the code care about kwargs vs args (TS lowerings),
+ # other parts care about whether they need to wrap the arg in a lazy value or leave it alone.
+ # Generators are special cased, as they are needed for fallback/shape-inference but not supported
+ # in TS lowerings and therefore also omitted from lazy IR.
+ args: list[LazyArgument] = []
+ if positional:
+ args.extend(self.positional_args)
+ if keyword:
+ args.extend(self.keyword_args)
+
+ if values and scalars and generator:
+ return args
+ elif values and scalars:
+ return [a for a in args if not a.is_generator]
+ elif values:
+ return [a for a in args if a.is_lazy_value]
+ elif scalars:
+ return [
+ a
+ for a in args
+ if not a.is_lazy_value and (generator or not a.is_generator)
+ ]
+
+ return []
+
+ @property
+ def positional_values(self) -> list[LazyArgument]:
+ return self.filtered_args(
+ positional=True, keyword=False, values=True, scalars=False
+ )
+
+ @property
+ def positional_scalars(self) -> list[LazyArgument]:
+ return self.filtered_args(
+ positional=True, keyword=False, values=False, scalars=True
+ )
+
+ @property
+ def keyword_values(self) -> list[LazyArgument]:
+ return self.filtered_args(
+ positional=False, keyword=True, values=True, scalars=False
+ )
+
+ @property
+ def keyword_scalars(self) -> list[LazyArgument]:
+ return self.filtered_args(
+ positional=False, keyword=True, values=False, scalars=True
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/meta.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffafc500dbfdde8b290ef6a2283c57fd602f0606
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/meta.py
@@ -0,0 +1,13 @@
+from torchgen.model import NativeFunctionsGroup
+
+
+# Follows dispatcher calling convention, but:
+# - Mutable arguments not allowed. Meta functions are always
+# written in functional form. Look at FunctionSchema.signature()
+# - No tensor returns; instead we return a TensorMeta describing
+# the tensor in question
+
+
+def name(g: NativeFunctionsGroup) -> str:
+ # use the overload name from the functional version
+ return str(g.functional.func.name).replace(".", "_")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/native.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/native.py
new file mode 100644
index 0000000000000000000000000000000000000000..09039857d683517b46dcaa1e160369ac0a52ad0e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/native.py
@@ -0,0 +1,159 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from torchgen import local
+from torchgen.api import cpp
+from torchgen.api.types import (
+ ArgName,
+ BaseCType,
+ Binding,
+ boolT,
+ ConstRefCType,
+ CType,
+ deviceT,
+ layoutT,
+ ListCType,
+ MutRefCType,
+ NamedCType,
+ OptionalCType,
+ scalarT,
+ scalarTypeT,
+ tensorT,
+)
+from torchgen.model import (
+ Argument,
+ FunctionSchema,
+ Return,
+ SelfArgument,
+ TensorOptionsArguments,
+ Type,
+)
+from torchgen.utils import assert_never
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+# This file describes the translation of JIT schema to the native functions API.
+# This looks a lot like the C++ API (which makes historical sense, because the
+# idea was you wrote native functions to implement functions in the C++ API),
+# but over time we have evolved the C++ API without actually changing our
+# native:: kernels. The intention is to make native API and dispatcher API
+# line up as closely as possible, since this results in the least overhead
+# (no translation is needed from dispatcher API to native API).
+#
+# NB: this is symint aware, you will get the non-SymInt variant for some
+# dispatch entries and SymInt for others.
+
+
+def name(func: FunctionSchema) -> str:
+ name = str(func.name.name)
+ # TODO: delete this!
+ if func.is_out_fn():
+ name += "_out"
+ if func.name.overload_name:
+ name += f"_{func.name.overload_name}"
+ return name
+
+
+def argumenttype_type(
+ t: Type, *, mutable: bool, binds: ArgName, symint: bool
+) -> NamedCType:
+ if str(t) == "Tensor?":
+ tensor_type: OptionalCType = OptionalCType(BaseCType(tensorT))
+ if mutable and not local.use_const_ref_for_mutable_tensors():
+ return NamedCType(binds, MutRefCType(tensor_type))
+ else:
+ return NamedCType(binds, ConstRefCType(tensor_type))
+ elif str(t) == "Tensor?[]":
+ return NamedCType(
+ binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT))))
+ )
+ elif str(t) == "Scalar":
+ return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+ elif str(t) == "Scalar?":
+ return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
+ return cpp.argumenttype_type(t, mutable=mutable, binds=binds, symint=symint)
+
+
+def returns_type(rs: Sequence[Return], *, symint: bool) -> CType:
+ return cpp.returns_type(rs, symint=symint)
+
+
+def argument_type(a: Argument, *, binds: ArgName, symint: bool) -> NamedCType:
+ return argumenttype_type(a.type, mutable=a.is_write, binds=binds, symint=symint)
+
+
+def argument(
+ a: Argument | SelfArgument | TensorOptionsArguments,
+ *,
+ is_out: bool,
+ symint: bool,
+) -> list[Binding]:
+ # Ideally, we NEVER default native functions. However, there are a number
+ # of functions that call native:: directly and rely on the defaulting
+ # existing. So for BC, we generate defaults for non-out variants (but not
+ # for out variants, where it is impossible to generate an appropriate
+ # default)
+ should_default = not is_out
+ if isinstance(a, Argument):
+ default: str | None = None
+ if should_default and a.default is not None:
+ default = cpp.default_expr(a.default, a.type, symint=symint)
+ return [
+ Binding(
+ nctype=argument_type(a, binds=a.name, symint=symint),
+ name=a.name,
+ default=default,
+ argument=a,
+ )
+ ]
+ elif isinstance(a, SelfArgument):
+ # Erase SelfArgument from the distinction
+ return argument(a.argument, is_out=is_out, symint=symint)
+ elif isinstance(a, TensorOptionsArguments):
+ default = None
+ if should_default:
+ default = "{}"
+ # TODO: Not sure why the arguments assigned here are for
+ # TensorOptionsArguments and not the constituent pieces. It seems
+ # to matter
+ return [
+ Binding(
+ nctype=NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))),
+ name="dtype",
+ default=default,
+ argument=a,
+ ),
+ Binding(
+ nctype=NamedCType("layout", OptionalCType(BaseCType(layoutT))),
+ name="layout",
+ default=default,
+ argument=a,
+ ),
+ Binding(
+ nctype=NamedCType("device", OptionalCType(BaseCType(deviceT))),
+ name="device",
+ default=default,
+ argument=a,
+ ),
+ Binding(
+ nctype=NamedCType("pin_memory", OptionalCType(BaseCType(boolT))),
+ name="pin_memory",
+ default=default,
+ argument=a,
+ ),
+ ]
+ else:
+ assert_never(a)
+
+
+def arguments(func: FunctionSchema, *, symint: bool) -> list[Binding]:
+ args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+ args.extend(func.arguments.non_out)
+ args.extend(func.arguments.out)
+ return [
+ r for arg in args for r in argument(arg, symint=symint, is_out=func.is_out_fn())
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/python.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/python.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e8b939cf3c515c869c21634cd0738fb829aec12
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/python.py
@@ -0,0 +1,1521 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen.api import cpp
+from torchgen.api.types import Binding, CppSignature, CppSignatureGroup
+from torchgen.gen import pythonify_default
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ FunctionSchema,
+ ListType,
+ NativeFunction,
+ OptionalType,
+ Return,
+ Type,
+ Variant,
+)
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# Data Models
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# [Notes] python binding codegen
+#
+# The Python binding codegen produces code that takes the input list of
+# PyObjects, finds the matching ATen C++ function using PythonArgParser,
+# converts the PyObjects into C++ types and calls the ATen C++ function:
+#
+# +--------+ parsing +------------------------+ binding +-----------------------+
+# | PyObjs | ---------> | PythonArgParser Output | ---------> | Cpp Function Dispatch |
+# +--------+ +------------------------+ +-----------------------+
+#
+# The following examples demonstrate the data models the Python binding
+# codegen needs to deal with and the tasks it needs to accomplish. It
+# helps understand the purpose of the new data types we introduced below.
+#
+# - Function Schema (source of truth)
+#
+# aten::empty.names(int[] size, *, Dimname[]? names,
+# ScalarType? dtype=None, Layout? layout=None,
+# Device? device=None, bool? pin_memory=None,
+# MemoryFormat? memory_format=None) -> Tensor
+#
+# - Python Signature
+#
+# It's used to generate input schema string for PythonArgParser.
+# Note: TensorOptions fields are reordered and the additional
+# 'requires_grad' field is added:
+#
+# empty(IntArrayRef size, *, DimnameList? names,
+# MemoryFormat? memory_format=None, ScalarType dtype=None,
+# Layout layout=torch.strided, Device device=None,
+# bool pin_memory=False, bool requires_grad=False)
+#
+# - C++ Signature
+#
+# It's used to generate C++ lambda formals & dispatch call.
+# Note: the scattered TensorOptions fields are packed into 'options'.
+#
+# auto dispatch_empty =
+# [](IntArrayRef size, std::optional names,
+# const TensorOptions & options,
+# std::optional memory_format) -> Tensor {
+# pybind11::gil_scoped_release no_gil;
+# return torch::empty(size, names, options, memory_format);
+# };
+#
+# - Binding between Python Arguments and C++ Arguments
+#
+# Given a set of Python Arguments in scope, we need produce the
+# binding expressions that translate the Python API into C++ API:
+#
+# Python Args Cpp Args Binding Exprs
+# -----------------------------------------------------------------
+# 0: size size '_r.intlist(0)'
+# 1: names names 'names' [special init]
+# 2: memory_format -------+
+# 3: dtype -----+-|--> options 'options' [special packing]
+# 4: layout / |
+# 5: device / +--> memory_format '_r.memoryformatOptional(2)'
+# 6: pin_memory /
+# 7: requires_grad -+
+#
+# So the full dispatch expression would look like:
+#
+# dispatch_empty(_r.intlist(0), names, options,
+# _r.memoryformatOptional(2))
+#
+# Where does 'names' come from? It involves special local init:
+#
+# auto __names = _r.toDimnameListOptional(1);
+# std::optional names =
+# __names ? std::make_optional(DimnameList(__names.value()))
+# : std::nullopt;
+#
+# Where does 'options' come from? It involves special local init
+# for TensorOptions. Note that Python side has the additional
+# 'requires_grad' field:
+#
+# const auto options = TensorOptions()
+# .dtype(_r.scalartype(3))
+# .device(_r.device(5))
+# .layout(_r.layoutOptional(4))
+# .requires_grad(_r.toBool(7))
+# .pinned_memory(_r.toBool(6));
+#
+# In some other cases one Python Argument can map to multiple C++
+# Arguments. For example:
+#
+# aten::max.names_dim(Tensor self, Dimname dim, bool keepdim=False)
+# -> (Tensor values, Tensor indices)
+#
+# Python Args Cpp Args Binding Exprs
+# ---------------------------------------------------------------------
+# +----> max 'out[0]'
+# /-----> max_values 'out[1]
+# 0: input / self '_r.tensor(0)'
+# 1: dim / dim '_r.dimname(1)'
+# 2: keepdim / keepdim '_r.toBool(2)'
+# 3: out -----+ [local init] out '_r.tensorlist_n<2>(3)'
+#
+# As demonstrated above, the binding can involve reordering,
+# packing, unpacking and special local inits.
+#
+#
+# Let's look at a concrete example:
+#
+# static PythonArgParser parser({
+# "abs(Tensor input, *, Tensor out=None)",
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# ^
+# +--- Python Schema, represented by PythonSignature and PythonArgument
+#
+# }, /*traceable=*/true);
+#
+# ParsedArgs<2> parsed_args;
+# auto _r = parser.parse(nullptr, args, kwargs, parsed_args);
+#
+# ...
+#
+# if (_r.isNone(1)) {
+# ~~~~~~~~~~~~ <--- Scattered PythonArgParser output (arg name = 'out')
+# represented by PythonArgParserOutputExpr
+#
+# // aten::abs(Tensor self) -> Tensor
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# ^
+# +--- NativeFunction schema, base version
+#
+# auto dispatch_abs = [](const Tensor & self) -> Tensor {
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# ^
+# +--- dispatch_lambda_args / dispatch_lambda_return_str
+# generated from NativeFunction / CppSignature
+# (deprecated PythonSignature is special)
+# arguments are represented by DispatchLambdaArgument
+#
+# pybind11::gil_scoped_release no_gil;
+# return self.abs();
+# ~~~~~~~~~~~ <--- cpp_dispatch_target / cpp_dispatch_exprs
+# generated from NativeFunction / CppSignature
+# };
+# return wrap(dispatch_abs(_r.tensor(0)));
+# ~~~~~~~~~~~~~
+# ^
+# +--- dispatch_lambda_exprs
+# binding PythonArgParserOutputExpr (python args)
+# and DispatchLambdaArgument (c++ args)
+#
+# } else {
+# // aten::abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# ^
+# +--- NativeFunction schema, out-variant
+#
+# auto dispatch_abs_out = [](Tensor out, const Tensor & self) -> Tensor {
+# pybind11::gil_scoped_release no_gil;
+# return at::abs_out(out, self);
+# };
+# return wrap(dispatch_abs_out(_r.tensor(1), _r.tensor(0)));
+# }
+#
+#
+# [Notes] python interface codegen
+# The python dataclasses below are used used to generate both python binding code
+# and pyi type hint signatures.
+# In theory these two should look very similar, but there are number of differences
+# in how pyi signatures vs. python_arg_parser signatures are generated.
+# These differences have been encapsulated in signature_str() vs. signature_str_pyi()
+# to display the full signatures, and argument_str() vs argument_str_pyi() to display arguments.
+# For examples, only pyi signatures include return types.
+
+
+@dataclass(frozen=True)
+class PythonReturns:
+ returns: tuple[Return, ...]
+
+
+@dataclass(frozen=True)
+class PythonArgument:
+ name: str
+ type: Type
+ default: str | None
+
+ # Used to generate the default init expr for some PythonArgParser outputs, e.g.:
+ #
+ # _r.layoutWithDefault(3, layout_from_backend(self.options().backend())))
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ # ^
+ # +--- default_init str
+ default_init: str | None
+
+ # Compute argument formal for python argument parsing.
+ # Needs to be consistent with torch/csrc/utils/python_arg_parser.h.
+ def argument_str(self, *, method: bool = False, symint: bool = True) -> str:
+ type_str = (
+ argument_type_str(self.type, symint=symint)
+ .replace("const ", "")
+ .replace(" &", "")
+ )
+
+ name = self.name
+ # s/self/input/ outside method bindings
+ # [old codegen] TODO: remove this? doesn't rename in codegen, it's just
+ # for the parse string
+ if name == "self" and type_str in ["Tensor", "Number"] and not method:
+ name = "input"
+
+ # add default
+ if self.default is not None:
+ default = {
+ "nullptr": "None",
+ "::std::nullopt": "None",
+ "std::nullopt": "None",
+ "{}": "None",
+ }.get(self.default, self.default)
+ return f"{type_str} {name}={default}"
+ else:
+ return f"{type_str} {name}"
+
+ def argument_str_pyi(
+ self, *, method: bool = False, deprecated: bool = False
+ ) -> str:
+ type_str = argument_type_str_pyi(self.type)
+
+ name = self.name
+ # s/self/input/ outside method bindings
+ # [old codegen] TODO: remove this? doesn't rename in codegen, it's just
+ # for the parse string
+ if name == "self" and type_str == "Tensor" and not method and not deprecated:
+ name = "input"
+
+ if name == "from": # from is a Python keyword...
+ name += "_"
+
+ # pyi merges the _out and functional variants into the same signature, with an optional out arg
+ if name == "out" and type_str == "Tensor" and not deprecated:
+ type_str = "Optional[" + type_str + "]"
+
+ # pyi deprecated signatures don't get defaults for their out arg
+ treat_as_no_default = (
+ deprecated
+ and isinstance(self, PythonOutArgument)
+ and self.default == "None"
+ )
+
+ # add default
+ if self.default is not None and not treat_as_no_default:
+ if (
+ isinstance(self.type, ListType)
+ and self.type.elem == BaseType(BaseTy.int)
+ and self.default.startswith("{")
+ and self.default.endswith("}")
+ ):
+ default = (
+ "(" + ", ".join(map(str.strip, self.default[1:-1].split(","))) + ")"
+ )
+ else:
+ default = {
+ "nullptr": "None",
+ "::std::nullopt": "None",
+ "std::nullopt": "None",
+ "{}": "None",
+ "c10::MemoryFormat::Contiguous": "contiguous_format",
+ "QScheme::PER_TENSOR_AFFINE": "per_tensor_affine",
+ }.get(self.default, self.default)
+ return f"{name}: {type_str} = {default}"
+ else:
+ return f"{name}: {type_str}"
+
+
+@dataclass(frozen=True)
+class PythonOutArgument(PythonArgument):
+ # In Python signature multiple output fields are packed into one 'out' argument.
+ # When binding to C++, it's first binded to a local 'out' variable:
+ # 'auto out = _r.tensorlist_n<2>(2);',
+ # then binded to scattered C++ output arguments as 'out[0]', 'out[1]', and etc.
+ # TODO: maybe don't need keep scattered out fields for python signature?
+ outputs: tuple[PythonArgument, ...]
+
+ @staticmethod
+ def from_outputs(outputs: tuple[PythonArgument, ...]) -> PythonOutArgument | None:
+ if not outputs:
+ return None
+
+ size = len(outputs)
+ if size == 1:
+ return PythonOutArgument(
+ name=outputs[0].name,
+ type=outputs[0].type,
+ default="None",
+ default_init=None,
+ outputs=outputs,
+ )
+ elif size > 1:
+ if any(not a.type.is_tensor_like() for a in outputs):
+ raise RuntimeError(f"Unsupported output type: {outputs}")
+ return PythonOutArgument(
+ name="out",
+ # TODO: shouldn't this be OptionalType[ListType[...]], since it defaults to None?
+ type=ListType(BaseType(BaseTy.Tensor), size),
+ default="None",
+ default_init=None,
+ outputs=outputs,
+ )
+ raise AssertionError(r"Unexpected PythonOutArgument size")
+
+
+@dataclass(frozen=True)
+class PythonSignature:
+ # Base operator name, without inplace/outplace suffix.
+ name: str
+
+ # Positional arguments.
+ # TODO: create a dedicated SelfArgument type for 'self'?
+ input_args: tuple[PythonArgument, ...]
+
+ # Keyword arguments excluding the 'out' argument and scattered kwargs belonging
+ # to TensorOptions (dtype, layout, device, pin_memory, requires_grad, etc).
+ input_kwargs: tuple[PythonArgument, ...]
+
+ output_args: PythonOutArgument | None
+
+ # Return types, which are only used by pyi
+ returns: PythonReturns
+
+ # These are scattered kwargs arguments belonging to TensorOptions.
+ # When binding to C++, they are packed into a TensorOptions object 'options'.
+ # It's possible that the C++ signature doesn't take TensorOptions object (e.g.
+ # for out variant), in which case they will be used as scattered fields without
+ # being packed into 'options'.
+ # TODO: maybe create a PythonTensorOptionsArgument?
+ tensor_options_args: tuple[PythonArgument, ...]
+
+ # method or function signature?
+ method: bool
+
+ @property
+ def deprecated(self) -> bool:
+ return False
+
+ def arguments(
+ self, *, skip_outputs: bool = False, skip_tensor_options: bool = False
+ ) -> tuple[PythonArgument | PythonOutArgument, ...]:
+ result: list[PythonArgument | PythonOutArgument] = []
+ result.extend(self.input_args)
+ result.extend(self.input_kwargs)
+ if self.output_args is not None and not skip_outputs:
+ result.append(self.output_args)
+ if not skip_tensor_options:
+ result.extend(self.tensor_options_args)
+ return tuple(result)
+
+ def arguments_count(self) -> int:
+ return len(self.arguments())
+
+ def output_idx(self) -> int:
+ return len(self.input_args) + len(self.input_kwargs)
+
+ # [old codegen] Compute the Python function signature for argument parsing,
+ # as specified in torch/csrc/utils/python_arg_parser.h. WARNING:
+ # this is NOT the same type signature as specified by PEP 484
+ # as understood by mypy; our format was independently developed
+ # and has some quirks to make it more suitable specifically
+ # for error parsing.
+ #
+ # For a translation to mypy-valid type signatures, see
+ # signature_str_pyi().
+ def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str:
+ args = self.arguments(skip_outputs=skip_outputs)
+ schema_formals: list[str] = [
+ a.argument_str(method=self.method, symint=symint) for a in args
+ ]
+ positional_argc = len(self.input_args)
+ if len(schema_formals) > positional_argc:
+ schema_formals.insert(positional_argc, "*")
+
+ return f'{self.name}({", ".join(schema_formals)})'
+
+ def signature_str_pyi(self, *, skip_outputs: bool = False) -> str:
+ args = self.arguments(skip_outputs=skip_outputs)
+ schema_formals: list[str] = [
+ a.argument_str_pyi(method=self.method) for a in args
+ ]
+ positional_argc = len(self.input_args)
+ if len(schema_formals) > positional_argc:
+ schema_formals.insert(positional_argc, "*")
+
+ # only pyi signatures include returns
+ returns_str = returns_str_pyi(self)
+ # pyi also includes self (with no typing/defaults) for methods
+ if self.method:
+ schema_formals.insert(0, "self")
+ return f'def {self.name}({", ".join(schema_formals)}) -> {returns_str}: ...'
+
+ def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None:
+ # only pyi uses vararg signatures
+ args = self.arguments(skip_outputs=skip_outputs)
+ schema_formals: list[str] = [
+ a.argument_str_pyi(method=self.method) for a in args
+ ]
+ # vararg only applies to pyi signatures. vararg variants are not generated for all signatures
+ num_args = self.arguments_count()
+ num_positionalargs = len(self.input_args)
+
+ have_vararg_version = False
+ if num_args > 0:
+ vararg_type = args[0].type
+ if (
+ isinstance(vararg_type, ListType)
+ and str(vararg_type.elem) in ["int", "SymInt"]
+ and num_positionalargs == 1
+ ):
+ have_vararg_version = True
+
+ if not have_vararg_version:
+ return None
+
+ # Below are the major changes in vararg vs. regular pyi signatures
+ # vararg signatures also omit the asterix
+ assert isinstance(vararg_type, ListType)
+ schema_formals[0] = (
+ "*" + args[0].name + ": " + argument_type_str_pyi(vararg_type.elem)
+ )
+
+ returns_str = returns_str_pyi(self)
+ # pyi also includes self (with no typing/defaults) for methods
+ if self.method:
+ schema_formals.insert(0, "self")
+ return f'def {self.name}({", ".join(schema_formals)}) -> {returns_str}: ...'
+
+
+# The deprecated python signature involves some special logic, so create a
+# dedicated data model to store these extra properties.
+@dataclass(frozen=True)
+class PythonSignatureDeprecated(PythonSignature):
+ # Schema for the deprecated function
+ deprecated_schema: FunctionSchema
+
+ # The deprecated signature might miss some arguments that the corresponding
+ # C++ signature expects. We need store the constant default values to pass in.
+ # For example:
+ # [deprecate signature]: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2)
+ # [func schema]: aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ # [func call]: self.addmm(mat1, mat2, beta, 1)
+ # We store ['self', 'mat1', 'mat2', 'beta', '1'] in this case.
+ deprecated_args_exprs: tuple[str, ...]
+
+ @property
+ def deprecated(self) -> bool:
+ return True
+
+ def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str:
+ return (
+ PythonSignature.signature_str(
+ self, skip_outputs=skip_outputs, symint=symint
+ )
+ + "|deprecated"
+ )
+
+ def signature_str_pyi(self, *, skip_outputs: bool = False) -> str:
+ args = self.arguments(skip_outputs=skip_outputs)
+ schema_formals: list[str] = [
+ a.argument_str_pyi(method=self.method, deprecated=True) for a in args
+ ]
+ positional_argc = len(self.input_args)
+ if len(schema_formals) > positional_argc:
+ schema_formals.insert(positional_argc, "*")
+
+ returns_str = returns_str_pyi(self)
+ return f'def {self.name}({", ".join(schema_formals)}) -> {returns_str}: ...'
+
+ def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None:
+ # the codegen doesn't include vararg variants for deprecated signatures
+ return None
+
+
+# This struct is used to hold the PythonSignature and its corresponding
+# NativeFunction BEFORE grouping base and out-variant functions.
+# Why not store NativeFunction in PythonSignature or construct PythonSignature
+# from NativeFunction? Because they are not 1-1 mapped.
+# One native function could have both deprecated and non-deprecated python
+# signatures - NativeFunction doesn't contain information to construct the
+# deprecated python signature.
+# One python signature is used to handle both the base and the out-variant
+# function - see 'PythonSignatureGroup'.
+@dataclass(frozen=True)
+class PythonSignatureNativeFunctionPair:
+ signature: PythonSignature
+ function: NativeFunction
+
+
+# We merge pairs of functions with signatures that are equivalent mod
+# output arguments, and use a single entry in the python_arg_parser sig
+# list for both (output arguments become optional).
+@dataclass(frozen=True)
+class PythonSignatureGroup:
+ # The signature used for Python argument parsing. The outplace signature
+ # is preferred if exists, because it can be used to parse inputs for both
+ # the out-place variant and the base version (with output omitted).
+ signature: PythonSignature
+
+ # The regular ATen declaration (e.g. conv2d)
+ base: NativeFunction
+
+ # The out variant (e.g. conv2d_out)
+ outplace: NativeFunction | None
+
+ @classmethod
+ def from_pairs(
+ cls,
+ functional: PythonSignatureNativeFunctionPair,
+ out: PythonSignatureNativeFunctionPair | None,
+ ) -> PythonSignatureGroup:
+ if out is None:
+ return PythonSignatureGroup(
+ signature=functional.signature,
+ base=functional.function,
+ outplace=None,
+ )
+
+ # prefer the signature with optional out=... arguments because it's the
+ # superset that can be used to parse input for both base and outplace.
+ signature_kwargs = out.signature.__dict__.copy()
+
+ # Out overloads in C++ don't have TensorOptions arguments,
+ # so take these from the functional variant
+ signature_kwargs["tensor_options_args"] = (
+ functional.signature.tensor_options_args
+ )
+
+ return PythonSignatureGroup(
+ signature=type(out.signature)(**signature_kwargs),
+ base=functional.function,
+ outplace=out.function,
+ )
+
+
+# C++ function dispatch is wrapped in a lambda function. The lambda function
+# has almost the same signature as the C++ function, only with some small
+# variants - see details below.
+# This data model is used to represent arguments of the lambda function
+# signature.
+@dataclass(frozen=True)
+class DispatchLambdaArgument:
+ name: str
+ type_str: str
+ is_out_arg: bool
+
+
+# To pass PyObjects arguments to C++ function (via the lambda wrapper),
+# we need first convert PyObjects into simple C++ objects. This work
+# is done by PythonArgParser.
+# This data model is used to represent the output of PythonArgParser.
+# It has 1-1 mapping with PythonArgument in PythonSignature.
+@dataclass(frozen=True)
+class PythonArgParserOutputExpr:
+ # argument name
+ name: str
+
+ # RHS expression to reference PythonArgParser output.
+ expr: str
+
+ # In some special cases we need create different expr, e.g.:
+ # '_r.isNone(1)' instead of '_r.tensor(1)'.
+ index: int
+
+ # The python argument it maps to.
+ argument: PythonArgument
+
+ @property
+ def is_none_expr(self) -> str:
+ return f"_r.isNone({self.index})"
+
+
+# To pass PythonArgParser output to the lambda wrapper, we need bind
+# PythonArgParserOutputExpr to DispatchLambdaArgument.
+# They are not always 1-1 mapped, e.g. scattered TensorOptions fields
+# need be packed into a TensorOptions object, which is the argument
+# that the lambda function wrapper takes.
+@dataclass(frozen=True)
+class DispatchLambdaArgumentExprs:
+ # The exprs that provide the binding for lambda arguments, e.g.:
+ #
+ # 'self' -> '_r.tensor(0)'
+ # 'min' -> 'out[0]' / 'min_indices' -> 'out[1]'
+ # 'options' -> 'options'
+ #
+ # It has 1-1 mapping with DispatchLambdaArgument.
+ exprs: Sequence[str]
+
+ # Special local inits, which might introduce new variables that
+ # the 'exprs' above reference, e.g.:
+ #
+ # 'auto out = _r.tensorlist_n<2>(2);'
+ #
+ inits: Sequence[str]
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# Helper Functions
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def _cpp_signature(f: NativeFunction, *, method: bool = False) -> CppSignature:
+ return CppSignatureGroup.from_native_function(f, method=method).signature
+
+
+def has_tensor_options(f: NativeFunction) -> bool:
+ return f.func.arguments.tensor_options is not None
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# Python Signature
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+# 'simple_type' was introduced by the old codegen, which is slightly
+# different from the python schema type, e.g.: doesn't have '?' suffix
+# for optional Tensor/TensorList; doesn't have '[size]' suffix for list type.
+def argument_type_str(
+ t: Type, *, simple_type: bool = False, symint: bool = True
+) -> str:
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor:
+ return "Tensor"
+ elif t.name == BaseTy.int:
+ return "int64_t"
+ elif t.name == BaseTy.float:
+ return "double"
+ elif t.name == BaseTy.str:
+ return "c10::string_view"
+ elif t.name in [
+ BaseTy.bool,
+ BaseTy.QScheme,
+ BaseTy.Scalar,
+ BaseTy.ScalarType,
+ BaseTy.Generator,
+ BaseTy.Storage,
+ BaseTy.Layout,
+ BaseTy.Device,
+ BaseTy.DeviceIndex,
+ BaseTy.MemoryFormat,
+ BaseTy.Dimname,
+ BaseTy.Stream,
+ BaseTy.SymInt,
+ ]:
+ # These python schema type names line up with their function schema names
+ return t.name.name
+
+ elif isinstance(t, OptionalType):
+ if str(t.elem) == "Tensor":
+ # Is it desired to keep '?' for simple_type with new style dispatcher?
+ return "Tensor?"
+ elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint)
+ return f"{elem}?"
+ elif isinstance(t, ListType):
+ size = t.size if not simple_type else None
+ if str(t.elem) == "bool":
+ assert t.size is not None
+ return f"::std::array"
+ elif str(t.elem) == "int":
+ return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef"
+ elif str(t.elem) == "SymInt":
+ if symint:
+ return (
+ f"SymIntArrayRef[{size}]" if size is not None else "SymIntArrayRef"
+ )
+ else:
+ return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef"
+ elif str(t.elem) == "Tensor":
+ return f"TensorList[{size}]" if size is not None else "TensorList"
+ elif str(t.elem) == "Scalar":
+ return f"ScalarList[{size}]" if size is not None else "ScalarList"
+ elif str(t.elem) == "Tensor?":
+ if simple_type:
+ return "c10::List<::std::optional>"
+ else:
+ return "const c10::List<::std::optional> &"
+ elif str(t.elem) == "Dimname":
+ return f"DimnameList[{size}]" if size is not None else "DimnameList"
+ elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint)
+ return f"ArrayRef<{elem}>"
+
+ raise RuntimeError(f"unrecognized type {repr(t)}")
+
+
+def argument_type_size(t: Type) -> int | None:
+ l = t.is_list_like()
+ if l is not None and str(l.elem) != "bool":
+ return l.size
+ else:
+ return None
+
+
+def argument(a: Argument) -> PythonArgument:
+ return PythonArgument(
+ name=a.name,
+ type=a.type,
+ # TODO: directly translate a.default to python default
+ default=(
+ str(pythonify_default(cpp.default_expr(a.default, a.type, symint=False)))
+ if a.default is not None
+ else None
+ ),
+ default_init=None,
+ )
+
+
+# Generates a PythonSignature that can be used for either .pyi or PythonArgParser codegen
+def signature(
+ f: NativeFunction, *, method: bool = False, pyi: bool = False
+) -> PythonSignature:
+ return signature_from_schema(
+ f.func, category_override=f.category_override, method=method, pyi=pyi
+ )
+
+
+def signature_from_schema(
+ func: FunctionSchema,
+ *,
+ category_override: str | None,
+ method: bool = False,
+ pyi: bool = False,
+) -> PythonSignature:
+ args: list[Argument] = []
+ args.extend(func.arguments.pre_self_positional)
+ # Skip SelfArgument if this is method.
+ if not method and func.arguments.self_arg is not None:
+ args.append(func.arguments.self_arg.argument)
+ args.extend(func.arguments.post_self_positional)
+ args.extend(func.arguments.pre_tensor_options_kwarg_only)
+ # Skip TensorOptionsArguments. Python side TensorOptions
+ # arguments are created based on different rules - see below.
+ args.extend(func.arguments.post_tensor_options_kwarg_only)
+ args.extend(func.arguments.out)
+
+ input_arg_set = {a.name for a in func.arguments.flat_positional}
+ kwarg_only_set = {a.name for a in func.arguments.flat_kwarg_only}
+ out_arg_set = {a.name for a in func.arguments.out}
+
+ input_args = tuple(map(argument, filter(lambda a: a.name in input_arg_set, args)))
+ input_kwargs = tuple(
+ map(argument, filter(lambda a: a.name in kwarg_only_set, args))
+ )
+ outputs = tuple(map(argument, filter(lambda a: a.name in out_arg_set, args)))
+
+ # Reintroduce the scattered fields of TensorOptions for Python.
+ # Compared to the cpp counterpart, the python arguments have new property
+ # (default_init) and a new argument 'requires_grad', which require some
+ # special handlings.
+ # [old codegen] TODO: because these aren't guaranteed to be 100% faithful
+ # to the original versions in the yaml, this recreation is a potential
+ # source of drift between eager and JIT. Pull this logic out to a shared place.
+
+ has_tensor_input_arg = any(
+ a.type.is_tensor_like() for a in func.arguments.flat_non_out
+ )
+ if any(a.name == "requires_grad" for a in func.schema_order_arguments()):
+ raise ValueError(
+ "argument named requires_grad is reserved, should not explicitly add it in the schema"
+ )
+
+ # [old codegen] this probably won't work if one of the returns is not a tensor,
+ # but it will produce a compile-time error that is obvious.
+ has_tensor_return = any(r.type.is_tensor_like() for r in func.returns)
+
+ name: str = cpp.name(func)
+ is_factory_function = category_override == "factory" or (
+ has_tensor_return and not has_tensor_input_arg
+ )
+ is_like_or_new_function = (
+ category_override in ("new", "like")
+ or name.startswith("new_")
+ or name.endswith("_like")
+ )
+ is_dummy_function = category_override == "dummy"
+
+ tensor_options_args: list[PythonArgument] = []
+ if (is_factory_function or is_like_or_new_function) and not is_dummy_function:
+
+ def topt_default_init(name: str) -> str | None:
+ topt_args = func.arguments.tensor_options
+ if topt_args is None:
+ return None
+ a = getattr(topt_args, name)
+ if a.default is None or a.default == "None":
+ return None
+ return cpp.default_expr(a.default, a.type, symint=False)
+
+ tensor_options_args.append(
+ PythonArgument(
+ name="dtype",
+ type=OptionalType(BaseType(BaseTy.ScalarType)),
+ default="None",
+ default_init=(
+ None if is_like_or_new_function else topt_default_init("dtype")
+ ),
+ )
+ )
+ tensor_options_args.append(
+ PythonArgument(
+ name="layout",
+ type=OptionalType(BaseType(BaseTy.Layout)),
+ default="None",
+ default_init=(
+ None if is_like_or_new_function else topt_default_init("layout")
+ ),
+ )
+ )
+ tensor_options_args.append(
+ PythonArgument(
+ name="device",
+ type=OptionalType(BaseType(BaseTy.Device)),
+ default="None",
+ default_init=(
+ None
+ if is_like_or_new_function
+ else (
+ topt_default_init("device")
+ or "torch::tensors::get_default_device()"
+ )
+ ),
+ )
+ )
+ tensor_options_args.append(
+ PythonArgument(
+ name="pin_memory",
+ type=OptionalType(BaseType(BaseTy.bool)),
+ default="False",
+ default_init=None,
+ )
+ )
+ tensor_options_args.append(
+ PythonArgument(
+ name="requires_grad",
+ type=OptionalType(BaseType(BaseTy.bool)),
+ default="False",
+ default_init=None,
+ )
+ )
+
+ returns = PythonReturns(returns=func.returns)
+
+ return PythonSignature(
+ name=str(func.name.name),
+ input_args=input_args,
+ input_kwargs=input_kwargs,
+ output_args=PythonOutArgument.from_outputs(outputs),
+ tensor_options_args=tuple(tensor_options_args),
+ returns=returns,
+ method=method,
+ )
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# Python Interface
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+def structseq_fieldnames(returns: tuple[Return, ...]) -> list[str]:
+ if len(returns) <= 1 or all(r.name is None for r in returns):
+ return []
+ else:
+ if any(r.name is None for r in returns):
+ # When building on Windows, `PyStructSequence_UnnamedField` could not be
+ # resolved by the linker for some reason, which cause error in building:
+ #
+ # python_nn_functions.cpp.obj : error LNK2001: unresolved external symbol
+ # PyStructSequence_UnnamedField
+ #
+ # Thus, at this point in time, we do not support unnamed
+ # fields in structseq; you must either name all fields,
+ # or none of them.
+ raise ValueError("Unnamed field is not supported by codegen")
+
+ return [str(r.name) for r in returns]
+
+
+def argument_type_str_pyi(t: Type) -> str:
+ add_optional = False
+ if isinstance(t, OptionalType):
+ t = t.elem
+ add_optional = True
+
+ if isinstance(t, BaseType):
+ if t.name in [BaseTy.int, BaseTy.DeviceIndex]:
+ ret = "_int"
+ if t.name == BaseTy.SymInt:
+ ret = "Union[_int, SymInt]"
+ elif t.name == BaseTy.float:
+ ret = "_float"
+ elif t.name == BaseTy.str:
+ ret = "str"
+ elif t.name == BaseTy.Scalar:
+ ret = "Union[Number, _complex]"
+ elif t.name == BaseTy.ScalarType:
+ ret = "_dtype"
+ elif t.name == BaseTy.bool:
+ ret = "_bool"
+ elif t.name == BaseTy.QScheme:
+ ret = "_qscheme"
+ elif t.name == BaseTy.Layout:
+ ret = "_layout"
+ elif t.name == BaseTy.Device:
+ ret = "Optional[DeviceLikeType]"
+ elif t.name == BaseTy.MemoryFormat:
+ ret = "memory_format"
+ elif t.name == BaseTy.Dimname:
+ ret = "Union[str, ellipsis, None]"
+ elif t.name == BaseTy.Storage:
+ ret = "Union[Storage, UntypedStorage]"
+ elif t.name in [BaseTy.Tensor, BaseTy.Generator, BaseTy.Stream]:
+ # These python schema type names line up with their function schema names
+ ret = t.name.name
+
+ elif isinstance(t, ListType):
+ if str(t.elem) == "int":
+ ret = "Union[_int, _size]" if t.size is not None else "_size"
+ elif t.is_tensor_like():
+ # TODO: this doesn't seem right...
+ # Tensor?[] currently translates to Optional[Union[tuple[Tensor, ...], list[Tensor]]]
+ # It should probably translate to Union[tuple[Optional[Tensor], ...], list[Optional[Tensor]]]
+ add_optional = True
+ ret = (
+ "Union[Tensor, tuple[Tensor, ...], list[Tensor]]"
+ if t.size is not None
+ else "Union[tuple[Tensor, ...], list[Tensor]]"
+ )
+ elif str(t.elem) == "float":
+ ret = "Sequence[_float]"
+ elif str(t.elem) == "SymInt" and t.size is not None:
+ elem = argument_type_str_pyi(t.elem)
+ ret = f"Union[{elem}, Sequence[{elem}]]"
+ else:
+ elem = argument_type_str_pyi(t.elem)
+ ret = f"Sequence[{elem}]"
+
+ else:
+ raise RuntimeError(f"unrecognized type {repr(t)}")
+
+ if add_optional:
+ ret = "Optional[" + ret + "]"
+
+ return ret
+
+
+def return_type_str_pyi(t: Type) -> str:
+ # Where arguments are open to accepting Union, return types should return
+ # concrete types
+
+ if isinstance(t, OptionalType):
+ inner = return_type_str_pyi(t.elem)
+ return f"Optional[{inner}]"
+
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Device:
+ return "_device"
+ elif t.name == BaseTy.Dimname:
+ return "Optional[str]"
+ else:
+ return argument_type_str_pyi(t)
+
+ if isinstance(t, ListType):
+ inner = return_type_str_pyi(t.elem)
+ return f"tuple[{inner}, ...]"
+
+ return argument_type_str_pyi(t)
+
+
+def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None:
+ python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
+ structseq_name = signature.name
+ field_names = structseq_fieldnames(signature.returns.returns)
+ if field_names:
+ # These types are structseq objects which act like named NamedTuples, but
+ # the constructor acts like the constructor of tuple. Using typing.NamedTuple
+ # does not allow us to override __init__.
+ seq_type = f"tuple[{', '.join(python_returns)}]"
+ structseq_def_lines = [
+ f"class {structseq_name}({seq_type}):",
+ ]
+ for name, typ in zip(field_names, python_returns):
+ structseq_def_lines.extend(
+ [
+ " @property",
+ f" def {name}(self) -> {typ}: ...",
+ ]
+ )
+ structseq_def_lines.extend(
+ [
+ f" def __new__(cls, sequence: {seq_type}): ...",
+ f" n_fields: _int = {len(field_names)}",
+ f" n_sequeunce_fields: _int = {len(field_names)}",
+ " n_unnamed_fields: _int = 0",
+ " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing",
+ "", # add an extra newline
+ ]
+ )
+ structseq_def = "\n".join(structseq_def_lines)
+ # Example:
+ # structseq_def = (
+ # "class max(tuple[Tensor, Tensor]):\n"
+ # " @property\n"
+ # " def values(self) -> Tensor: ...\n"
+ # " @property\n"
+ # " def indices(self) -> Tensor: ...\n"
+ # " def __new__(cls, sequence: tuple[Tensor, Tensor]): ...\n"
+ # " n_fields: _int = 2",
+ # " n_sequeunce_fields: _int = 2",
+ # " n_unnamed_fields: _int = 0",
+ # " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing",
+ # )
+ return structseq_name, structseq_def
+ return None
+
+
+def returns_str_pyi(signature: PythonSignature) -> str:
+ field_names = structseq_fieldnames(signature.returns.returns)
+ if field_names:
+ return f"torch.return_types.{signature.name}"
+
+ python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns]
+ if len(python_returns) > 1:
+ return "tuple[" + ", ".join(python_returns) + "]"
+ if len(python_returns) == 1:
+ return python_returns[0]
+ return "None"
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# C++ Function Dispatch
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+# This section provides APIs to generate the code that does C++ function
+# dispatch. The C++ function call is wrapped by a lambda function.
+# For example:
+#
+# // aten::selu_(Tensor(a!) self) -> Tensor(a!)
+# auto dispatch_selu_ = [](Tensor self) -> Tensor {
+# pybind11::gil_scoped_release no_gil;
+# return at::selu_(self);
+# };
+#
+# The lambda function's signature follows the C++ signature in common
+# cases, e.g.:
+#
+# // aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+# [](const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor
+#
+# For out variant the 'out' argument's type is changed from 'Tensor &'
+# to 'Tensor'. It's because when calling the lambda it passes in the
+# PythonArgParser output '_r.tensor(3)', which is stack allocated object
+# and needs to pass by value. Also see comments in 'dispatch_lambda_return_str()'.
+#
+# // aten::add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+# [](Tensor out, const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor
+#
+# For multi-output case it can keep using reference type because the
+# PythonArgParser output has been unpacked to local variables, e.g.:
+#
+# // aten::max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *,
+# // Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
+# [](Tensor & max, Tensor & max_values, const Tensor & self, Dimname dim, bool keepdim) -> std::tuple
+#
+# For deprecated python signature, it should follow deprecated python arg order.
+# TODO: This is to keep same byte-for-byte result as the old codegen - maybe unnecessary?
+
+
+def dispatch_lambda_args(
+ ps: PythonSignature, f: NativeFunction, symint: bool = True
+) -> tuple[DispatchLambdaArgument, ...]:
+ if isinstance(ps, PythonSignatureDeprecated):
+ schema = ps.deprecated_schema
+ else:
+ schema = f.func
+
+ # Start with cpp arguments - dispatch lambda signature always include 'self'
+ cpp_args = cpp.arguments(
+ arguments=schema.arguments,
+ faithful=False,
+ symint=symint,
+ method=False,
+ cpp_no_default_args=f.cpp_no_default_args,
+ )
+ out_args: set[str] = {a.name for a in schema.arguments.out}
+
+ # Convert from cpp argument to lambda argument
+ def dispatch_lambda_arg(cpp_arg: Binding) -> DispatchLambdaArgument:
+ type_str = cpp_arg.type
+ is_out_arg = cpp_arg.name in out_args
+ if ps.method and cpp_arg.name == "self":
+ # For method's 'self', we can use 'const Tensor &' and simply ignore mutability!
+ type_str = "const at::Tensor &"
+ else:
+ # For other cases we need prevent dangling refs to temps (unless it's
+ # unpacked scattered output)
+ # The reason is explained in the comments above and in 'dispatch_lambda_return_str()'.
+ # TODO: avoid this special handling?
+ ensure_temp_safe = len(out_args) <= 1 or not is_out_arg
+ if ensure_temp_safe:
+ type_str = {
+ "at::Tensor &": "at::Tensor",
+ }.get(type_str, type_str)
+ return DispatchLambdaArgument(
+ name=cpp_arg.name,
+ type_str=type_str,
+ is_out_arg=is_out_arg,
+ )
+
+ return tuple(map(dispatch_lambda_arg, cpp_args))
+
+
+# [old codegen] XXX: if you got here because of an assertion failure, it doesn't mean
+# it's enough to just extend the list here. Before you do this, make sure
+# to add an appropriate wrap() overload in torch/csrc/autograd/utils/wrap_outputs.h.
+SUPPORTED_RETURN_TYPES = {
+ "at::Tensor",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple",
+ "::std::tuple>",
+ "::std::vector",
+ # Needed for flash attention forw/backward
+ "::std::tuple",
+ "at::Scalar",
+ "bool",
+ "int64_t",
+ "void*",
+ "void",
+ "at::QScheme",
+ "double",
+ "at::IntArrayRef",
+ "at::ScalarType",
+ "at::Stream",
+}
+
+
+def dispatch_lambda_return_str(f: NativeFunction) -> str:
+ # [old codegen] Remove type annotation (e.g. 'Tensor' rather than 'Tensor &')
+ # because the dispatch lambdas take mutable arguments *by value*, not
+ # by reference. If you then return a reference to such an argument, you
+ # will now have a pointer to a dangling stack entry. Not good.
+ #
+ # You want:
+ #
+ # auto dispatch_selu_ = [](Tensor self) -> Tensor { ...; return at::selu_(self); };
+ # ^^^^^^
+ #
+ # *not*
+ #
+ # auto dispatch_selu_ = [](Tensor self) -> Tensor& { ...; return at::selu_(self); };
+ # ^^^^^^^
+ #
+ # (NB: We can't make dispatch_selu_ take Tensor&, because the enclosing
+ # codegen looks like dispatch_selu_(_r.tensor(0)), and you can't take a
+ # mutable reference to temporary. Maybe we could assign it to a
+ # variable itself.)
+ returns_without_annotation = tuple(
+ Return(r.name, r.type, None) for r in f.func.returns
+ )
+ return_str = cpp.returns_type(returns_without_annotation, symint=True).cpp_type()
+ if return_str not in SUPPORTED_RETURN_TYPES:
+ raise RuntimeError(f"{f.func.name} returns unsupported type {return_str}")
+ return return_str
+
+
+def cpp_dispatch_target(f: NativeFunction) -> str:
+ symint = f.func.has_symint()
+ name = cpp.name(f.func, symint_overload=symint)
+ if Variant.method in f.variants:
+ return f"self.{name}"
+ if Variant.function in f.variants:
+ if has_tensor_options(f) or f.func.name.name.base.endswith("_like"):
+ namespace = "torch"
+ else:
+ namespace = "at"
+ return f"{namespace}::{name}"
+ raise RuntimeError(f"could not dispatch, neither function nor method: {f.func}")
+
+
+def cpp_dispatch_exprs(
+ f: NativeFunction,
+ *,
+ python_signature: PythonSignature | None = None,
+) -> tuple[str, ...]:
+ cpp_args: Sequence[Binding] = _cpp_signature(f, method=False).arguments()
+
+ exprs: tuple[str, ...] = ()
+ if not isinstance(python_signature, PythonSignatureDeprecated):
+ # By default the exprs are consistent with the C++ signature.
+ exprs = tuple(a.name for a in cpp_args)
+ else:
+ # For deprecated python signature we may need fill in some constants.
+ exprs = tuple(
+ filter(
+ lambda n: n != "out" or f.func.is_out_fn(),
+ python_signature.deprecated_args_exprs,
+ )
+ )
+
+ if Variant.method in f.variants:
+ exprs = tuple(filter("self".__ne__, exprs))
+
+ return exprs
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# Python / C++ Args Binding
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+# We explicitly enumerate the PythonArgParser unpacking methods for all
+# supported types. This might be more verbose than necessary, partially
+# because of the irregularity of unpacking method naming, partially
+# because we want to mimic the old codegen behavior - to reject
+# unexpected and/or unsupported cases which the old codegen rejects.
+# For certain cases it is intentionally more restrictive than necessary,
+# e.g.: it doesn't accepts doublelist with definite size.
+def arg_parser_unpack_method(
+ t: Type, default: str | None, default_init: str | None, *, symint: bool = True
+) -> str:
+ has_default_init = default_init is not None
+ if has_default_init and str(t) not in (
+ "ScalarType?",
+ "ScalarType",
+ "Device",
+ "Device?",
+ "Layout",
+ "Layout?",
+ "bool",
+ "bool?",
+ ):
+ raise RuntimeError(f"type '{t}' does not supported unpacking with default")
+
+ if isinstance(t, BaseType):
+ if t.name in [
+ BaseTy.Tensor,
+ BaseTy.Stream,
+ BaseTy.Storage,
+ BaseTy.Scalar,
+ BaseTy.Dimname,
+ ]:
+ # These unpack methods line up with their schema names
+ return t.name.name.lower()
+ elif t.name == BaseTy.ScalarType:
+ return "scalartypeWithDefault" if has_default_init else "scalartype"
+ elif t.name == BaseTy.Device:
+ return "deviceWithDefault" if has_default_init else "device"
+ elif t.name == BaseTy.DeviceIndex:
+ return "toInt64"
+ elif t.name == BaseTy.int:
+ return "toInt64"
+ elif t.name == BaseTy.SymInt:
+ return "toSymInt" if symint else "toInt64"
+ elif t.name == BaseTy.bool:
+ return "toBoolWithDefault" if has_default_init else "toBool"
+ elif t.name == BaseTy.float:
+ return "toDouble"
+ elif t.name == BaseTy.str:
+ return "stringView"
+ elif t.name == BaseTy.Layout:
+ return "layoutWithDefault" if has_default_init else "layout"
+ elif t.name == BaseTy.MemoryFormat:
+ return "memoryformat"
+
+ elif isinstance(t, OptionalType):
+ if str(t.elem) == "Tensor":
+ return "optionalTensor"
+ elif str(t.elem) == "Generator":
+ return "generator"
+ elif str(t.elem) == "Dimname[]":
+ return "toDimnameListOptional"
+ elif not has_default_init and default in (
+ None,
+ "None",
+ "::std::nullopt",
+ "std::nullopt",
+ ):
+ # If default is None: append 'Optional' to elem's unpacking method
+ return (
+ arg_parser_unpack_method(t.elem, None, None, symint=symint) + "Optional"
+ )
+ else:
+ # Otherwise, load as underlying type with default
+ return arg_parser_unpack_method(
+ t.elem, default, default_init, symint=symint
+ )
+
+ elif isinstance(t, ListType):
+ if str(t.elem) == "Tensor":
+ # accept and use definite size
+ return f"tensorlist_n<{t.size}>" if t.size is not None else "tensorlist"
+ elif str(t.elem) == "Tensor?":
+ return "list_of_optional_tensors"
+ elif str(t.elem) == "Dimname":
+ # accept definite size
+ return "dimnamelist"
+ elif str(t.elem) == "int":
+ # accept definite size
+ return "intlist"
+ elif str(t.elem) == "float":
+ return "doublelist"
+ elif str(t.elem) == "SymInt":
+ # accept definite size
+ return "symintlist" if symint else "intlist"
+ elif str(t.elem) == "Scalar":
+ return "scalarlist"
+ raise RuntimeError(f"type '{t}' is not supported by PythonArgParser")
+
+
+# Return RHS expression for python argument using PythonArgParser output.
+# e.g. for arg name 'foo', arg type 'bool', arg_index = 2, returns '_r.toBool(2)'
+def arg_parser_output_expr(
+ arg_index: int, a: PythonArgument, *, symint: bool = True
+) -> PythonArgParserOutputExpr:
+ has_default = a.default_init is not None
+ unpack_method = arg_parser_unpack_method(
+ t=a.type, default=a.default, default_init=a.default_init, symint=symint
+ )
+ default = f", {a.default_init}" if has_default else ""
+ expr = f"_r.{unpack_method}({arg_index}{default})"
+
+ return PythonArgParserOutputExpr(
+ name=a.name,
+ expr=expr,
+ index=arg_index,
+ argument=a,
+ )
+
+
+# Returns a map with key = arg_name and value = PythonArgParserOutputExpr.
+def arg_parser_output_exprs(
+ ps: PythonSignature, f: NativeFunction, *, symint: bool = True
+) -> dict[str, PythonArgParserOutputExpr]:
+ return {
+ e.name: e
+ for i, a in enumerate(ps.arguments())
+ for e in (arg_parser_output_expr(i, a, symint=symint),)
+ }
+
+
+# argument name to type for scattered tensor options fields
+TENSOR_OPTIONS_FIELDS = {
+ "dtype": "ScalarType?",
+ "device": "Device?",
+ "layout": "Layout?",
+ "pin_memory": "bool?",
+ "requires_grad": "bool?",
+}
+
+
+# bind arg parser outputs (python args) with dispatch lambda arguments (c++ args).
+def dispatch_lambda_exprs(
+ ps: PythonSignature, f: NativeFunction, *, symint: bool = True
+) -> DispatchLambdaArgumentExprs:
+ # This method is to bind 'arg_parser_outputs' and 'lambda_args' by producing
+ # 'inits' and 'lambda_args_exprs' for each lambda argument using arg parser
+ # outputs.
+ arg_parser_outputs = arg_parser_output_exprs(ps, f, symint=symint)
+ lambda_args = dispatch_lambda_args(ps, f, symint=symint)
+ inits: list[str] = []
+ lambda_args_exprs: dict[str, str] = {}
+
+ has_toptions = has_tensor_options(f)
+
+ # 1. special inits/unpacking to provide binding exprs for lambda arguments.
+ for a in ps.arguments(skip_tensor_options=True):
+ name = a.name
+ arg_parser_expr = arg_parser_outputs[a.name].expr
+
+ if has_toptions and name == "self":
+ # TODO: why this needs to be special case?
+ inits.extend(
+ [
+ f"auto self = {arg_parser_expr};",
+ ]
+ )
+ lambda_args_exprs[name] = name
+ elif (
+ isinstance(a, PythonOutArgument)
+ and len(a.outputs) > 1
+ and f.func.is_out_fn()
+ ):
+ inits.extend(
+ [
+ f"auto out = {arg_parser_expr};",
+ ]
+ )
+ for i, out_arg in enumerate(a.outputs):
+ lambda_args_exprs[out_arg.name] = f"out[{i}]"
+ elif str(a.type) == "Dimname[]?":
+ # [old codegen]
+ # TODO: make this part of something more general, or get rid of it.
+ # optional> are special. The PythonArgParser returns an
+ # optional>, which cannot be implicitly converted to
+ # optional>. One needs to unwrap the optional and rewrap.
+ inits.extend(
+ [
+ f"auto __{name} = {arg_parser_expr};",
+ f"::std::optional {name} = __{name} ? ::std::make_optional(DimnameList(__{name}.value())) : ::std::nullopt;", # noqa: B950
+ ]
+ )
+ lambda_args_exprs[name] = name
+ else:
+ # default case - directly using PythonArgParser output expr
+ lambda_args_exprs[name] = arg_parser_expr
+
+ # method's self is passed directly to python binding, rather than parsed
+ if ps.method:
+ lambda_args_exprs["self"] = "self"
+
+ # 2. special packing/checking for TensorOptions.
+ tensor_options_args_names = [a.name for a in ps.tensor_options_args]
+ if has_toptions:
+ if f.func.is_out_fn():
+ raise RuntimeError(f"{f.func}: tensor options with output arg")
+ for a in ps.tensor_options_args:
+ if a.name not in TENSOR_OPTIONS_FIELDS:
+ raise RuntimeError(
+ f"{f.func}: unrecognized tensor options field '{a.name}' in python binding arguments"
+ )
+ if str(a.type) != TENSOR_OPTIONS_FIELDS.get(a.name):
+ raise RuntimeError(
+ f"{f.func}: unrecognized type '{str(a.type)}' for tensor options field '{a.name}'"
+ )
+ if not all(a in tensor_options_args_names for a in TENSOR_OPTIONS_FIELDS):
+ raise RuntimeError(
+ f"{f.func}: incomplete tensor options args: {tensor_options_args_names}"
+ )
+
+ inits.append(
+ f"""\
+const auto options = TensorOptions()
+ .dtype({arg_parser_outputs['dtype'].expr})
+ .device({arg_parser_outputs['device'].expr})
+ .layout({arg_parser_outputs['layout'].expr})
+ .requires_grad({arg_parser_outputs['requires_grad'].expr})
+ .pinned_memory({arg_parser_outputs['pin_memory'].expr});
+torch::utils::maybe_initialize_device(options);
+"""
+ )
+ lambda_args_exprs["options"] = "options"
+
+ # 3. special case - access scattered TensorOptions fields without packing
+ # TODO: maybe move to the generator side as it's not related to binding.
+ if not has_toptions and tensor_options_args_names:
+ if "dtype" in tensor_options_args_names:
+ # we're an output-arg variant, check these args against output tensor
+ if not f.func.is_out_fn():
+ raise RuntimeError(
+ f"{f.func}: dtype in tensor_options_args without output arg, {ps} {ps.arguments}"
+ )
+ if not all(a in tensor_options_args_names for a in ("layout", "device")):
+ raise RuntimeError(
+ f"{f.func}: incomplete tensor options for output check"
+ )
+
+ inits.append(
+ f"""\
+check_out_type_matches({arg_parser_outputs['out'].expr}, {arg_parser_outputs['dtype'].expr},
+ {arg_parser_outputs['dtype'].is_none_expr}, {arg_parser_outputs['layout'].expr},
+ {arg_parser_outputs['device'].expr}, {arg_parser_outputs['device'].is_none_expr});
+"""
+ )
+ # we'll set requires_grad on outgoing tensor
+ if "requires_grad" not in tensor_options_args_names:
+ raise RuntimeError(
+ f'{f.func}: expected "requires_grad" in tensor_options_args absent, but found [{tensor_options_args_names}]'
+ )
+
+ return DispatchLambdaArgumentExprs(
+ exprs=tuple(lambda_args_exprs[a.name] for a in lambda_args),
+ inits=inits,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/structured.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/structured.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4a7ac9cc30a7838297dda96099441822e92ac17
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/structured.py
@@ -0,0 +1,157 @@
+from __future__ import annotations
+
+from torchgen.api import cpp
+from torchgen.api.types import (
+ ArgName,
+ ArrayRefCType,
+ BaseCType,
+ Binding,
+ ConstRefCType,
+ dimnameListT,
+ intArrayRefT,
+ iOptTensorListRefT,
+ iTensorListRefT,
+ NamedCType,
+ OptionalCType,
+ optionalIntArrayRefT,
+ optionalScalarRefT,
+ optionalTensorRefT,
+ scalarT,
+ tensorT,
+)
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ ListType,
+ NativeFunctionsGroup,
+ OptionalType,
+ SelfArgument,
+ TensorOptionsArguments,
+ Type,
+)
+from torchgen.utils import assert_never
+
+
+# This file describes the translation of JIT schema to the structured functions API.
+# This is similar to native API, but a number of historical problems with native
+# API have been fixed.
+
+
+# Translation of types occurring in JIT arguments to a C++ argument type.
+# NB: For now, mutable doesn't do anything; but it could if we make
+# some more nominal types
+def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
+ # If it's a value type, do the value type translation
+ # NB: structured kernels ALWAYS have symint off, since they involve actual
+ # kernels that require real ints. The one exception is the
+ # CompositeExplicitAutograd and the meta function (which could
+ # hypothetically be SymInt), but for simplicity we plan for these to just
+ # be handled in Python
+ r = cpp.valuetype_type(t, symint=False, binds=binds, mutable=mutable)
+ if r is not None:
+ return r
+
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor:
+ return NamedCType(binds, ConstRefCType(BaseCType(tensorT)))
+ elif t.name == BaseTy.Scalar:
+ return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+ else:
+ raise AssertionError(f"base type should have been value type {t}")
+ elif isinstance(t, OptionalType):
+ if t.elem == BaseType(BaseTy.Tensor):
+ return NamedCType(binds, BaseCType(optionalTensorRefT))
+ elif t.elem == BaseType(BaseTy.Scalar):
+ return NamedCType(binds, BaseCType(optionalScalarRefT))
+ elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int":
+ return NamedCType(binds, BaseCType(optionalIntArrayRefT))
+ elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
+ return NamedCType(binds, OptionalCType(elem.type))
+ elif isinstance(t, ListType):
+ if t.elem == BaseType(BaseTy.Tensor):
+ return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT)))
+ elif t.elem == OptionalType(BaseType(BaseTy.Tensor)):
+ return NamedCType(binds, BaseCType(iOptTensorListRefT))
+ # TODO: delete these special cases; see torchgen.api.cpp--these
+ # must be changed in tandem, but there are problems; see
+ # https://github.com/pytorch/pytorch/pull/51485
+ elif str(t.elem) == "int":
+ return NamedCType(binds, BaseCType(intArrayRefT))
+ elif str(t.elem) == "Dimname":
+ return NamedCType(binds, BaseCType(dimnameListT))
+ elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
+ return NamedCType(binds, ArrayRefCType(elem.type))
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+def argument_type(a: Argument, *, binds: ArgName) -> NamedCType:
+ return argumenttype_type(a.type, mutable=a.is_write, binds=binds)
+
+
+# returns_type intentionally omitted, because structured kernels never "return";
+# instead, they always indirectly report their outputs (in the case of a meta
+# function, by calling set_output; in the case of an impl function, by writing
+# directly into the provided out argument).
+
+
+# Structured kernels are never defaulted
+def argument(a: Argument | SelfArgument | TensorOptionsArguments) -> list[Binding]:
+ if isinstance(a, Argument):
+ return [
+ Binding(
+ nctype=argument_type(a, binds=a.name),
+ name=a.name,
+ default=None,
+ argument=a,
+ )
+ ]
+ elif isinstance(a, SelfArgument):
+ return argument(a.argument)
+ elif isinstance(a, TensorOptionsArguments):
+ raise AssertionError("structured kernels don't support TensorOptions yet")
+ else:
+ assert_never(a)
+
+
+def impl_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+ args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+
+ if g.out.precomputed:
+ # A list of parameters for the impl function with
+ # certain parameters replaced with precomputed counterparts
+ # as specified in native_functions.yaml.
+ non_out_args_replaced: list[
+ Argument | TensorOptionsArguments | SelfArgument
+ ] = []
+ for a in g.out.func.arguments.non_out:
+ if isinstance(a, Argument) and a.name in g.out.precomputed.replace:
+ # If a is in precompute.replace, append the parameters
+ # that should replace it onto non_out_args_replaced.
+ non_out_args_replaced.extend(g.out.precomputed.replace[a.name])
+ else:
+ # If not, push a as it is.
+ non_out_args_replaced.append(a)
+
+ args.extend(non_out_args_replaced)
+ # g.out.precomputed.add is the list of parameters that are added
+ # without replacement after the non out args and just before the out args
+ args.extend(g.out.precomputed.add)
+ else:
+ args.extend(g.out.func.arguments.non_out)
+
+ args.extend(g.out.func.arguments.out)
+ return [r for arg in args for r in argument(arg)]
+
+
+def meta_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+ args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+ args.extend(g.functional.func.arguments.non_out)
+ return [r for arg in args for r in argument(arg)]
+
+
+def out_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+ args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+ args.extend(g.out.func.arguments.out)
+ return [r for arg in args for r in argument(arg)]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/translate.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/translate.py
new file mode 100644
index 0000000000000000000000000000000000000000..e119e436bd296e0d592da40b2682a3e328eb9cad
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/translate.py
@@ -0,0 +1,437 @@
+from __future__ import annotations
+
+from typing import NoReturn, TYPE_CHECKING
+
+from torchgen.api.types import (
+ ArrayRefCType,
+ BaseCType,
+ Binding,
+ boolT,
+ ConstRefCType,
+ deviceT,
+ Expr,
+ intArrayRefT,
+ iOptTensorListRefT,
+ layoutT,
+ ListCType,
+ longT,
+ memoryFormatT,
+ MutRefCType,
+ NamedCType,
+ opmath_t,
+ OptionalCType,
+ optionalIntArrayRefT,
+ optionalScalarRefT,
+ optionalSymIntArrayRefT,
+ optionalTensorRefT,
+ scalar_t,
+ scalarT,
+ scalarTypeT,
+ SpecialArgName,
+ symIntArrayRefT,
+ SymIntT,
+ tensorOptionsT,
+ tensorT,
+ VectorCType,
+)
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+# This file implements a small program synthesis engine that implements
+# conversions between one API to another.
+#
+# The key data type in this file in NamedCType, short for Named C++ semantic type. A NamedCType
+# represents a C++ type, plus semantic information about what it represents.
+# For example, consider the argument "bool pin_memory"; its normal C++ type is
+# "bool", but its C++ semantic type also keeps track that this represents a
+# "pin_memory"; you can't just use a random other boolean in a context where you
+# need a "pin_memory"!
+#
+# The translator takes a list of needed NamedCTypes, and then figures out how
+# to construct expressions with these NamedCTypes from the given bindings. Many
+# of these expressions are trivial (I need a Tensor other; there's a Tensor
+# other scope); others are more nontrivial and may require packing/unpacking.
+# Some examples of non-trivial action:
+#
+# - Need the "dtype" binding? Well, maybe "dtype" isn't available
+# in the context, instead, "options" is, and you need to extract
+# it from there. (Gather)
+#
+# - Need the "context" binding? Well, maybe "context" isn't available
+# in the context, and you need to construct it from "dtype", "device",
+# etc. (Scatter)
+#
+# - Need the "memory_format" binding? Well, actually, it's available
+# from both "memory_format" and "options", so you had better make sure
+# they are consistent. (Join)
+
+options_ctype = NamedCType("options", ConstRefCType(BaseCType(tensorOptionsT)))
+
+out_tensor_ctype = NamedCType("out", ConstRefCType(BaseCType(tensorT)))
+
+longVec_ctype = VectorCType(BaseCType(longT))
+longSymVec_ctype = VectorCType(BaseCType(SymIntT))
+optionalLongVec_ctype = OptionalCType(VectorCType(BaseCType(longT)))
+optionalScalar_ctype = OptionalCType(BaseCType(scalarT))
+optionalTensor_ctype = OptionalCType(BaseCType(tensorT))
+
+
+class UnsatError(RuntimeError):
+ pass
+
+
+# Given a set of in-scope bindings and a set of target bindings, synthesize
+# a list of expressions that uses only the in-scope bindings (bindings) that
+# have all of the types of goals. You may want to use this function if
+# you're generating code for a function like:
+#
+# void f({args}) {
+# g({exprs}); // g is a different API
+# }
+#
+# and you need to generate "exprs".
+#
+# Typically, a list of Bindings is convenient to get (you usually call something
+# like arguments() to get them); but technically you only need less information:
+# for 'bindings' an (un-ordered) list of Exprs is sufficient; similarly, for
+# 'goals', an (ordered) list of NamedCType goals is sufficient. If you are doing
+# something more complicated, e.g., tracking the set of bindings in a context,
+# you may find using these smaller types more convenient.
+def translate(
+ bindings: Sequence[Expr | Binding],
+ goals: Sequence[NamedCType | Binding],
+ *,
+ method: bool = False,
+ allow_expensive_conversions: bool = False,
+) -> list[Expr]:
+ binding_exprs: list[Expr] = []
+ for b in bindings:
+ if isinstance(b, Binding):
+ binding_exprs.append(
+ Expr(
+ expr=b.name,
+ type=b.nctype,
+ )
+ )
+ else:
+ binding_exprs.append(b)
+
+ goal_ctypes: list[NamedCType] = []
+ for g in goals:
+ if isinstance(g, Binding):
+ goal_ctypes.append(g.nctype)
+ else:
+ goal_ctypes.append(g)
+
+ # Add all the bindings to the context
+ ctx: dict[NamedCType, str] = {}
+ for b in binding_exprs:
+ ctx[b.type] = b.expr
+
+ # While we're at it, do some simple forward inference, looking through
+ # constructors.
+ #
+ # NB: When should you do forward inference versus backward inference?
+ # The general idea:
+ #
+ # - Backward inference WHEN the goal gets smaller
+ # - Forward inference WHEN the hypothesis gets smaller
+ #
+ # This helps ensure termination: backward inference starts with a goal
+ # and tries to make it simpler and simpler until it's trivial; if the
+ # goal can grow in size, we blow up to a really huge goal size.
+ # Similarly, with forward inference we take hypotheses and decompose
+ # them into simpler hypotheses; if hypotheses could expand in size,
+ # we also have potential nontermination. (In the code below, forward
+ # inference is only ever carried out at a single step, but you could
+ # imagine repeated application of forward inference being profitable.)
+ #
+ # A good starting point in the literature for exploring more about proof
+ # search are these lecture notes
+ # https://www.cs.cmu.edu/~fp/courses/oregon-m10/04-focusing.pdf
+ #
+ # TODO: My kingdom for a pattern matcher
+ # https://www.python.org/dev/peps/pep-0634/
+ #
+ # TODO: This could get us in recomputation trouble if b.expr is nontrivial.
+ # Fix this by implementing some sort of sharing so that if multiple
+ # goals share the same expression, we only compute it once. This seems
+ # to matter in practice as compiler is often unwilling to CSE nontrivial
+ # expressions like scalar.to()
+ t = b.type
+ if (
+ isinstance(t, ConstRefCType)
+ and isinstance(t.elem, OptionalCType)
+ and isinstance(t.elem.elem, BaseCType)
+ and str(t.elem.elem.type) == "at::Tensor"
+ ):
+ ctx[NamedCType(t.elem.elem.name, ConstRefCType(BaseCType(tensorT)))] = (
+ f"({b.expr}.has_value() ? *{b.expr} : at::Tensor())"
+ )
+
+ if t.type == ConstRefCType(OptionalCType(BaseCType(tensorT))):
+ ctx[NamedCType(t.name, BaseCType(optionalTensorRefT))] = (
+ f"(({b.expr}.has_value() && (*{b.expr}).defined()) ? at::OptionalTensorRef(*{b.expr}) : at::OptionalTensorRef())"
+ )
+
+ if t.type == ConstRefCType(BaseCType(scalarT)):
+ ctx[NamedCType(t.name, BaseCType(opmath_t))] = f"({b.expr}).to()"
+
+ if t.type == ConstRefCType(OptionalCType(BaseCType(scalarT))):
+ ctx[NamedCType(t.name, BaseCType(optionalScalarRefT))] = (
+ f"({b.expr}.has_value() ? at::OptionalScalarRef(&({b.expr}.value())) : at::OptionalScalarRef())"
+ )
+
+ if t.type == BaseCType(scalar_t):
+ ctx[NamedCType(t.name, BaseCType(opmath_t))] = (
+ f"static_cast({b.expr})"
+ )
+
+ # [Note: IOptTensorListRef]
+ if t.type == ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))):
+ ctx[NamedCType(t.name, BaseCType(iOptTensorListRefT))] = (
+ f"at::IOptTensorListRef({b.expr})"
+ )
+
+ # Add implicit bindings if the generated code is inside a Tensor method
+ if method:
+ ctx[NamedCType("self", MutRefCType(BaseCType(tensorT)))] = (
+ "const_cast(*this)"
+ )
+ ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = (
+ "const_cast(*this)"
+ )
+ # This is better! Byte-for-byte compat
+ # ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = "*this"
+
+ def unsat(goal: NamedCType) -> NoReturn:
+ ctx_desc = "\n".join(
+ f" {t.cpp_type()} {t.name}; // {e}" for t, e in ctx.items()
+ )
+ raise UnsatError(
+ f"""
+Failed to synthesize the expression "{goal.cpp_type()} {goal.name}".
+When I failed, the following bindings were available in the context:
+
+{ctx_desc}
+
+This probably means there is a missing rule in the rules of torchgen.api.translate.
+Check this module for more information.
+"""
+ )
+
+ # A shitty backtracking search implementation. It's shitty because it
+ # does backtracking via stack (bad idea!) and for the most part tries to
+ # avoid backtracking. In particular, if
+ # direct=True, we won't try to do any fancy synthesis, just trivial
+ # conversions (e.g., "T a" is OK for "const T& a"). So all of the
+ # existing rules in this function simply try to solve immediately,
+ # and bail if things don't work out.
+ def solve(goal: NamedCType, *, direct: bool) -> str:
+ def direct_solve(goal: NamedCType) -> str:
+ return solve(goal, direct=True)
+
+ if goal in ctx:
+ # Trivial
+ return ctx[goal]
+
+ # const & is satisfied with mutable &
+ if isinstance(goal.type, ConstRefCType):
+ try:
+ # WARNING: not strictly decreasing; be careful not
+ # to add a direct conversion that goes satisfies
+ # mutable& with const&
+ return solve(
+ NamedCType(goal.name, MutRefCType(goal.type.elem)), direct=direct
+ )
+ except UnsatError:
+ pass
+
+ # mutable & is satisfied with value
+ if isinstance(goal.type, MutRefCType):
+ try:
+ return solve(NamedCType(goal.name, goal.type.elem), direct=direct)
+ except UnsatError:
+ pass
+
+ # TODO: These are referentially equal, shouldn't have to do this;
+ # ensuring we don't use type synonym IntArrayRef in codegen would
+ # help
+ if goal.type == ArrayRefCType(BaseCType(longT)):
+ return solve(NamedCType(goal.name, BaseCType(intArrayRefT)), direct=direct)
+
+ if direct:
+ unsat(goal)
+
+ # For now, all of these rules are mutually exclusive.
+ if goal == NamedCType("memory_format", OptionalCType(BaseCType(memoryFormatT))):
+ memory_format = direct_solve(
+ NamedCType(
+ SpecialArgName.possibly_redundant_memory_format,
+ OptionalCType(BaseCType(memoryFormatT)),
+ )
+ )
+ # No need to join "memory_format" and "options" if the target API takes "options" directly.
+ # Otherwise it will cause the redundant memory_format error.
+ if options_ctype in goal_ctypes:
+ return memory_format
+ try:
+ options = direct_solve(options_ctype)
+ return f"c10::impl::check_tensor_options_and_extract_memory_format({options}, {memory_format})"
+ except UnsatError:
+ return memory_format
+ elif goal == NamedCType("options", BaseCType(tensorOptionsT)):
+ dtype = direct_solve(
+ NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT)))
+ )
+ pin_memory = direct_solve(
+ NamedCType("pin_memory", OptionalCType(BaseCType(boolT)))
+ )
+ device = direct_solve(
+ NamedCType("device", OptionalCType(BaseCType(deviceT)))
+ )
+ layout = direct_solve(
+ NamedCType("layout", OptionalCType(BaseCType(layoutT)))
+ )
+ return f"TensorOptions().dtype({dtype}).layout({layout}).device({device}).pinned_memory({pin_memory})"
+
+ elif goal == NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))):
+ try:
+ options = direct_solve(options_ctype)
+ return f"c10::optTypeMetaToScalarType({options}.dtype_opt())"
+ except UnsatError:
+ out_tensor = direct_solve(out_tensor_ctype)
+ return f"{out_tensor}.scalar_type()"
+
+ elif goal == NamedCType("layout", OptionalCType(BaseCType(layoutT))):
+ try:
+ options = direct_solve(options_ctype)
+ return f"{options}.layout_opt()"
+ except UnsatError:
+ out_tensor = direct_solve(out_tensor_ctype)
+ return f"{out_tensor}.layout()"
+
+ elif goal == NamedCType("device", OptionalCType(BaseCType(deviceT))):
+ try:
+ options = direct_solve(options_ctype)
+ return f"{options}.device_opt()"
+ except UnsatError:
+ out_tensor = direct_solve(out_tensor_ctype)
+ return f"{out_tensor}.device()"
+
+ elif goal == NamedCType("pin_memory", OptionalCType(BaseCType(boolT))):
+ try:
+ options = direct_solve(options_ctype)
+ return f"{options}.pinned_memory_opt()"
+ except UnsatError:
+ # If we're calling a factory op from its out= variant,
+ # We don't actually care about the value of pin_memory.
+ out_tensor = direct_solve(out_tensor_ctype)
+ return "::std::nullopt"
+
+ # We can always do translations from value types to reference types, like vector -> IntArrayRef
+ elif goal.type == BaseCType(intArrayRefT):
+ try:
+ return direct_solve(NamedCType(goal.name, longVec_ctype))
+ except UnsatError:
+ # We can also go SymIntArrayRef -> IntArrayRef
+ symIntArrayRef_type = direct_solve(
+ NamedCType(goal.name, BaseCType(symIntArrayRefT))
+ )
+ return f"C10_AS_INTARRAYREF_SLOW({symIntArrayRef_type})"
+ elif goal.type == BaseCType(symIntArrayRefT):
+ try:
+ r = direct_solve(NamedCType(goal.name, BaseCType(intArrayRefT)))
+ return f"c10::fromIntArrayRefSlow({r})"
+ except UnsatError:
+ return direct_solve(NamedCType(goal.name, longSymVec_ctype))
+ elif goal.type == BaseCType(SymIntT):
+ return direct_solve(NamedCType(goal.name, BaseCType(longT)))
+ elif goal.type == OptionalCType(BaseCType(SymIntT)):
+ argname = direct_solve(
+ NamedCType(goal.name, OptionalCType(BaseCType(longT)))
+ )
+ return f"{argname}.has_value() ? ::std::make_optional(c10::SymInt(*{argname})) : ::std::nullopt"
+ elif goal.type == BaseCType(longT):
+ symInt_type = direct_solve(NamedCType(goal.name, BaseCType(SymIntT)))
+ return f"{symInt_type}.guard_int(__FILE__, __LINE__)"
+ elif goal.type == OptionalCType(BaseCType(longT)):
+ argname = direct_solve(
+ NamedCType(goal.name, OptionalCType(BaseCType(SymIntT)))
+ )
+ return f"{argname}.has_value() ? ::std::make_optional({argname}->guard_int(__FILE__, __LINE__)) : ::std::nullopt"
+ elif goal.type == BaseCType(optionalIntArrayRefT):
+ try:
+ return direct_solve(NamedCType(goal.name, optionalLongVec_ctype))
+ except UnsatError:
+ argname = direct_solve(
+ NamedCType(goal.name, BaseCType(optionalSymIntArrayRefT))
+ )
+ return f"{argname}.has_value() ? ::std::make_optional(C10_AS_INTARRAYREF_SLOW(*{argname})) : ::std::nullopt"
+ elif goal.type == BaseCType(optionalSymIntArrayRefT):
+ # TODO: You might also want to solve this from longSymVec_ctype or
+ # an optional version of it
+ argname = direct_solve(
+ NamedCType(goal.name, BaseCType(optionalIntArrayRefT))
+ )
+ return f"{argname}.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*{argname})) : ::std::nullopt"
+ elif goal.type == BaseCType(optionalScalarRefT):
+ return direct_solve(NamedCType(goal.name, optionalScalar_ctype))
+ elif goal.type == BaseCType(optionalTensorRefT):
+ return direct_solve(NamedCType(goal.name, optionalTensor_ctype))
+
+ # Note [translation from C++ reference to value types]
+ # The below cases are all for when we have an argument with a reference type,
+ # and a corresponding goal with a value type.
+ # These are needed when we populate the inputs to a lambda capture and we need
+ # to guarantee the lifetime of each captured argument.
+ # We guard it with an explicit kwarg because converting to a value type is expensive
+ # (O(n)) to convert from IntArrayRef to vector),
+ # so the caller of translate() should be explicit that they need it.
+ if allow_expensive_conversions:
+ if goal.type == VectorCType(BaseCType(longT)):
+ intArrayRef_ctype = NamedCType(goal.name, BaseCType(intArrayRefT))
+ argname = direct_solve(intArrayRef_ctype)
+ return f"{argname}.vec()"
+ if goal.type == VectorCType(BaseCType(SymIntT)):
+ symIntArrayRef_ctype = NamedCType(goal.name, BaseCType(symIntArrayRefT))
+ argname = direct_solve(symIntArrayRef_ctype)
+ return f"{argname}.vec()"
+ elif goal.type == OptionalCType(VectorCType(BaseCType(longT))):
+ optionalIntArrayRef_ctype = NamedCType(
+ goal.name, BaseCType(optionalIntArrayRefT)
+ )
+ argname = direct_solve(optionalIntArrayRef_ctype)
+ return f"{argname}.has_value() ? ::std::make_optional({argname}->vec()) : ::std::nullopt"
+ elif goal.type == OptionalCType(BaseCType(scalarT)):
+ optionalScalarRef_ctype = NamedCType(
+ goal.name, BaseCType(optionalScalarRefT)
+ )
+ argname = direct_solve(optionalScalarRef_ctype)
+ return f"{argname}.has_value() ? ::std::make_optional({argname}) : ::std::nullopt"
+ elif goal.type == OptionalCType(BaseCType(scalarT)):
+ optionalTensorRef_ctype = NamedCType(
+ goal.name, BaseCType(optionalTensorRefT)
+ )
+ argname = direct_solve(optionalTensorRef_ctype)
+ return f"{argname}.has_value() ? ::std::make_optional({argname}) : ::std::nullopt"
+ # Technically, we also need to handle cases of C++ containers holding reference types.
+ # But there currently aren't any ops that require lambda capture codegen
+ # With arguments like ::std::vector.
+ # If that changes, we'll have to add the translation here.
+
+ # We allow const casting on tensors, since const-correctness is a bit broken for at::Tensor.
+ # We could probably generalize this to non-tensor types too.
+ if goal.type == MutRefCType(BaseCType(tensorT)):
+ const_ref_tensor_ctype = NamedCType(
+ goal.name, ConstRefCType(BaseCType(tensorT))
+ )
+ argname = direct_solve(const_ref_tensor_ctype)
+ return f"const_cast({argname})"
+
+ unsat(goal)
+
+ return [Expr(solve(g, direct=False), g) for g in goal_ctypes]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b48163dbd3706644e162f899267674b86bf053e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__init__.py
@@ -0,0 +1,5 @@
+from torchgen.api.types.types import *
+from torchgen.api.types.types_base import *
+
+
+from torchgen.api.types.signatures import * # usort: skip
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..056dec8ff31cc76fe56626743c2bb326a1fe3d2e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/signatures.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/signatures.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f69431846e3bac983f9d338f8e494940bab2e63
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/signatures.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..656556cab6c784750c0db8bee8e9fba37cf7a190
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/types.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/types_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/types_base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8bf4c22c881864487d119753f6b1954c8f5e208
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/__pycache__/types_base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/signatures.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/signatures.py
new file mode 100644
index 0000000000000000000000000000000000000000..a56cc8bc794cbdae2fb9b09578b7016f059f8d51
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/signatures.py
@@ -0,0 +1,426 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen.api.types.types_base import Binding, CType, Expr
+
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator, Sequence
+
+ from torchgen.model import (
+ BackendIndex,
+ FunctionSchema,
+ NativeFunction,
+ NativeFunctionsGroup,
+ NativeFunctionsViewGroup,
+ )
+
+
+@dataclass(frozen=True)
+class CppSignature:
+ """
+ A CppSignature represents a single overload in the C++ API. For
+ any given function schema, there may be multiple CppSignatures
+ corresponding to it, based on how we desugar to C++. See also
+ CppSignatureGroup.
+ """
+
+ # The schema this signature is derived from
+ func: FunctionSchema
+
+ # Is this a C++ signature for a method, i.e. Tensor::my_op(...)?
+ method: bool
+
+ # Is this a faithful C++ signature (i.e. following the JIT schema) or a convenience API
+ # (i.e. with a potential TensorOptions argument and out arguments in the front)
+ faithful: bool
+
+ # Is this a symint C++ signature. For BC reasons, functions that take
+ # SymInts still present as int64_t in C++, and the SymInt variant is
+ # offered at a different overload name
+ #
+ # NB: If a function RETURNS a SymInt, this is ALWAYS false
+ symint: bool
+
+ # The set of C++ arguments which should not have defaults applied to them
+ cpp_no_default_args: set[str]
+
+ # Is this a fallback C++ binding? Fallback bindings are enabled by
+ # manual_cpp_binding: True and are alternate, non-public API that
+ # lets manual C++ binding implementors access the binding that would
+ # have been automatically generated
+ fallback_binding: bool = False
+
+ # Return the unpacked argument structure of this signature,
+ # discarding information about which arguments are semantically
+ # related to each other.
+ def arguments(self) -> Sequence[Binding]:
+ return cpp.arguments(
+ self.func.arguments,
+ faithful=self.faithful,
+ symint=self.symint,
+ method=self.method,
+ cpp_no_default_args=self.cpp_no_default_args,
+ )
+
+ def name(self, *, suppress_symint_suffix: bool = False) -> str:
+ n = cpp.name(
+ self.func,
+ faithful_name_for_out_overloads=self.faithful,
+ symint_overload=False if suppress_symint_suffix else self.symint,
+ )
+ if self.fallback_binding:
+ n = f"__dispatch_{n}"
+ return n
+
+ # Render the C++ declaration for this signature
+ def decl(
+ self,
+ *,
+ name: str | None = None,
+ prefix: str = "",
+ is_redispatching_fn: bool = False,
+ suppress_symint_suffix: bool = False,
+ ) -> str:
+ returns_type = cpp.returns_type(
+ self.func.returns, symint=self.symint
+ ).cpp_type()
+ cpp_args = [a.decl() for a in self.arguments()]
+ if is_redispatching_fn:
+ cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
+ cpp_args_str = ", ".join(cpp_args)
+ if name is None:
+ name = prefix + self.name(suppress_symint_suffix=suppress_symint_suffix)
+ return f"{returns_type} {name}({cpp_args_str})"
+
+ # Render the C++ definition for this signature, not including
+ # the body (with curly braces)
+ def defn(
+ self,
+ *,
+ name: str | None = None,
+ prefix: str = "",
+ is_redispatching_fn: bool = False,
+ ) -> str:
+ returns_type = cpp.returns_type(
+ self.func.returns, symint=self.symint
+ ).cpp_type()
+ cpp_args = [a.defn() for a in self.arguments()]
+ if is_redispatching_fn:
+ cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
+ cpp_args_str = ", ".join(cpp_args)
+ if name is None:
+ name = prefix + self.name()
+ return f"{returns_type} {name}({cpp_args_str})"
+
+ def ptr_type(self) -> str:
+ args_types_str = ", ".join(a.type for a in self.arguments())
+ return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_types_str})"
+
+ # Return the C++ function type, e.g., something like int(bool)
+ def type(self) -> str:
+ args_types_str = ", ".join(a.type for a in self.arguments())
+ return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} ({args_types_str})"
+
+
+# Represents group of all CppSignatures associated with a
+# FunctionSchema. Right now, that's the regular, user-visible
+# signature, as well as a "faithful" signature which doesn't
+# have grouping.
+@dataclass(frozen=True)
+class CppSignatureGroup:
+ func: FunctionSchema
+ signature: CppSignature
+ faithful_signature: CppSignature | None
+ symint_signature: CppSignature | None
+ symint_faithful_signature: CppSignature | None
+
+ def most_faithful_signature(self) -> CppSignature:
+ if self.faithful_signature:
+ return self.faithful_signature
+ else:
+ return self.signature
+
+ def signatures(self, *, symint: bool = True) -> Iterator[CppSignature]:
+ yield self.signature
+ if self.faithful_signature:
+ yield self.faithful_signature
+ if symint:
+ if self.symint_signature:
+ yield self.symint_signature
+ if self.symint_faithful_signature:
+ yield self.symint_faithful_signature
+
+ @staticmethod
+ def from_native_function(
+ f: NativeFunction, *, method: bool, fallback_binding: bool = False
+ ) -> CppSignatureGroup:
+ func = f.func
+
+ def make_sig(*, faithful: bool, symint: bool) -> CppSignature:
+ return CppSignature(
+ func=func,
+ faithful=faithful,
+ symint=symint,
+ method=method,
+ fallback_binding=fallback_binding,
+ cpp_no_default_args=f.cpp_no_default_args,
+ )
+
+ def make_sigs(*, symint: bool) -> tuple[CppSignature, CppSignature | None]:
+ faithful_signature: CppSignature | None = None
+ if func.arguments.tensor_options is not None or len(func.arguments.out) > 0:
+ faithful_signature = make_sig(faithful=True, symint=symint)
+ signature = make_sig(faithful=False, symint=symint)
+ return signature, faithful_signature
+
+ signature, faithful_signature = make_sigs(symint=False)
+ symint_signature: CppSignature | None = None
+ symint_faithful_signature: CppSignature | None = None
+ if func.has_symint():
+ symint_signature, symint_faithful_signature = make_sigs(symint=True)
+
+ return CppSignatureGroup(
+ func=func,
+ signature=signature,
+ faithful_signature=faithful_signature,
+ symint_signature=symint_signature,
+ symint_faithful_signature=symint_faithful_signature,
+ )
+
+
+@dataclass(frozen=True)
+class DispatcherSignature:
+ # The schema this signature is derived from
+ func: FunctionSchema
+
+ # Allows you to prepend an arbitrary prefix to the signature name.
+ # This is useful for parts of the codegen that generate wrappers around kernels,
+ # and need to avoid naming collisions.
+ prefix: str = ""
+
+ symint: bool = True
+
+ def arguments(self) -> list[Binding]:
+ return dispatcher.arguments(self.func, symint=self.symint)
+
+ def name(self) -> str:
+ return self.prefix + dispatcher.name(self.func)
+
+ def decl(self, name: str | None = None) -> str:
+ args_str = ", ".join(a.decl() for a in self.arguments())
+ if name is None:
+ name = self.name()
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
+
+ def defn(
+ self, name: str | None = None, *, is_redispatching_fn: bool = False
+ ) -> str:
+ args = [a.defn() for a in self.arguments()]
+ if is_redispatching_fn:
+ args = ["c10::DispatchKeySet dispatchKeySet"] + args
+ args_str = ", ".join(args)
+ if name is None:
+ name = self.name()
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
+
+ def exprs(self) -> list[Expr]:
+ return [Expr(a.name, a.nctype) for a in self.arguments()]
+
+ def returns_type(self) -> CType:
+ return dispatcher.returns_type(self.func.returns, symint=self.symint)
+
+ def ptr_type(self) -> str:
+ dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
+ return f"{self.returns_type().cpp_type()} (*)({dispatcher_args_types_str})"
+
+ # Return the C++ function type, e.g., something like int(bool)
+ def type(self) -> str:
+ dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
+ return f"{self.returns_type().cpp_type()} ({dispatcher_args_types_str})"
+
+ @staticmethod
+ def from_schema(
+ func: FunctionSchema, *, prefix: str = "", symint: bool = True
+ ) -> DispatcherSignature:
+ return DispatcherSignature(func, prefix, symint)
+
+
+@dataclass(frozen=True)
+class NativeSignature:
+ # The schema this signature is derived from
+ func: FunctionSchema
+
+ symint: bool
+
+ prefix: str = ""
+
+ def name(self) -> str:
+ return self.prefix + native.name(self.func)
+
+ def decl(self, name: str | None = None) -> str:
+ args_str = ", ".join(a.decl() for a in self.arguments())
+ if name is None:
+ name = self.name()
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
+
+ def defn(self, name: str | None = None) -> str:
+ args_str = ", ".join(a.defn() for a in self.arguments())
+ if name is None:
+ name = self.name()
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
+
+ def ptr_type(self) -> str:
+ # don't include defaults in type signature!
+ args_str = ", ".join(a.defn() for a in self.arguments())
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_str})"
+
+ def arguments(self) -> list[Binding]:
+ return native.arguments(self.func, symint=self.symint)
+
+ def returns_type(self) -> CType:
+ return native.returns_type(self.func.returns, symint=self.symint)
+
+ def dispatcher_exprs(self) -> list[Expr]:
+ return translate.translate(
+ self.arguments(), dispatcher.arguments(self.func), method=False
+ )
+
+
+@dataclass(frozen=True)
+class ViewInverseSignature:
+ g: NativeFunctionsViewGroup
+
+ def name(self) -> str:
+ return functionalization.reverse_name(self.g.view, include_namespace=False)
+
+ def decl(self) -> str:
+ return_type = functionalization.returns_type(self.g.view.func)
+ decls = [
+ a.decl()
+ for a in functionalization.inner_arguments(
+ self.g.view.func, is_reverse=True
+ )
+ ]
+ return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});"
+
+
+@dataclass(frozen=True)
+class FunctionalizationLambda:
+ g: NativeFunctionsViewGroup
+
+ # are we generating the forward lambda or the reverse lambda?
+ is_reverse: bool
+
+ def captures(self) -> list[Expr]:
+ # The lambda lives inside of a kernel following the dispatcher API, so its outer context is the dispatcher arguments
+ # We also need to read the "reapply views" TLS at the time that the functionalization kernel was executed,
+ # and plumb it into the lambda.
+ outer_ctx = dispatcher.arguments(self.g.view.func) + [
+ functionalization.reapply_views_binding,
+ functionalization.inverse_return_mode_binding,
+ ]
+ capture_bindings = functionalization.capture_arguments(
+ self.g.view.func, is_reverse=self.is_reverse
+ )
+ # allow_expensive_conversions is set because we want to convert
+ # some reference types (IntArrayRef) to value types (vector).
+ capture_exprs = translate.translate(
+ outer_ctx, capture_bindings, method=False, allow_expensive_conversions=True
+ )
+ return capture_exprs
+
+ def decl(self) -> str:
+ return_type = functionalization.returns_type(self.g.view.func)
+ capture_str = ", ".join(
+ f"{val.type.name} = {val.expr}" for val in self.captures()
+ )
+ decls = [
+ a.decl()
+ for a in functionalization.outer_arguments(is_reverse=self.is_reverse)
+ ]
+ return f"[{capture_str}]({', '.join(decls)}) -> {return_type.cpp_type()}"
+
+ def inner_call(self, *, reapply_views: bool | None = None) -> str:
+ inner_call_name = functionalization.name(
+ self.g,
+ is_reverse=self.is_reverse,
+ include_namespace=True,
+ reapply_views=reapply_views,
+ )
+
+ arg_ctx = functionalization.outer_arguments(is_reverse=self.is_reverse)
+ capture_ctx = functionalization.capture_arguments(
+ self.g.view.func, is_reverse=self.is_reverse
+ )
+ full_ctx = arg_ctx + capture_ctx
+
+ assert self.g.view_copy is not None
+ call_bindings = functionalization.inner_arguments(
+ self.g.view_copy.func, is_reverse=self.is_reverse
+ )
+ maybe_index = functionalization.inner_call_index(self.g.view_copy.func)
+ call_exprs = [
+ e.expr for e in translate.translate(full_ctx, call_bindings, method=False)
+ ]
+ if not self.is_reverse and maybe_index is not None:
+ return f'{inner_call_name}({", ".join(call_exprs)})[{maybe_index.name}];'
+ else:
+ return f'{inner_call_name}({", ".join(call_exprs)});'
+
+ @staticmethod
+ def from_func(
+ g: NativeFunctionsViewGroup, *, is_reverse: bool
+ ) -> FunctionalizationLambda:
+ return FunctionalizationLambda(g, is_reverse)
+
+
+@dataclass(frozen=True)
+class StructuredImplSignature:
+ g: NativeFunctionsGroup
+ name: str
+
+ def defn(self, name: str | None = None) -> str:
+ args_str = ", ".join(a.defn() for a in self.arguments())
+ return f"TORCH_IMPL_FUNC({self.name})({args_str})"
+
+ def arguments(self) -> list[Binding]:
+ return structured.impl_arguments(self.g)
+
+
+# Helper functions
+
+
+def kernel_signature(
+ f: NativeFunction, backend_index: BackendIndex, *, prefix: str = ""
+) -> NativeSignature | DispatcherSignature:
+ # Note [External Backends Follow Dispatcher API]
+ # Kernel signatures for in-tree backends follow the "native" API,
+ # while kernels for out-of-tree backends follow the dispatcher API.
+ # See the comments in `native.py` for details, but historically there have been
+ # some small differences in schema convention between them and the Dispatcher API.
+ # Any differences that require translating between the two will results in a runtime cost,
+ # so we'd like to keep the differences as small as possible.
+ # With external backends, we'd like to enforce that they write their kernels with schemas
+ # that match the Dispatcher API directly, if they can.
+ meta = backend_index.get_kernel(f)
+ symint = meta is not None and meta.supports_symint()
+ if symint:
+ assert f.func.has_symint(), f"attempted to define symint kernel for {backend_index.dispatch_key} without SymInt in schema"
+ if backend_index.external:
+ return DispatcherSignature.from_schema(f.func, prefix=prefix, symint=symint)
+ else:
+ return NativeSignature(f.func, prefix=prefix, symint=symint)
+
+
+# Functions only, no types
+from torchgen.api import (
+ cpp,
+ dispatcher,
+ functionalization,
+ native,
+ structured,
+ translate,
+)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0870cff5b1c06f28b7fb7f99ebf1704843dcf10
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/types.py
@@ -0,0 +1,191 @@
+"""
+Where should I add a new type? `types_base.py` vs `types.py`
+
+This file defines data model classes for torchgen typing system, as well as some base types such as int32_t.
+
+`types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types.
+
+The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't
+contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused
+if we want to generate code for another C++ library.
+
+Add new types to `types.py` if these types are ATen/c10 related.
+Add new types to `types_base.py` if they are basic and not attached to ATen/c10.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from torchgen.api.types.types_base import (
+ BaseCppType,
+ BaseCType,
+ boolT,
+ byteT,
+ charT,
+ CType,
+ doubleT,
+ floatT,
+ int32T,
+ longT,
+ shortT,
+)
+from torchgen.model import BaseTy, ScalarType
+
+
+TENSOR_LIST_LIKE_CTYPES = [
+ "at::TensorList",
+ "const c10::List<::std::optional> &",
+ "const at::ITensorListRef &",
+]
+
+
+halfT = BaseCppType("at", "Half")
+complexHalfT = BaseCppType(
+ "c10", "complex"
+) # stuffing template param here is an abuse
+complexFloatT = BaseCppType("c10", "complex")
+complexDoubleT = BaseCppType("c10", "complex")
+bfloat16T = BaseCppType("at", "BFloat16")
+float8_e5m2T = BaseCppType("at", "Float8_e5m2")
+float8_e5m2fnuzT = BaseCppType("at", "Float8_e5m2fnuz")
+float8_e4m3fnT = BaseCppType("at", "Float8_e4m3fn")
+float8_e4m3fnuzT = BaseCppType("at", "Float8_e4m3fnuz")
+stringT = BaseCppType("c10", "string_view")
+generatorT = BaseCppType("at", "Generator")
+scalarTypeT = BaseCppType("at", "ScalarType")
+tensorT = BaseCppType("at", "Tensor")
+optionalTensorRefT = BaseCppType("at", "OptionalTensorRef")
+tensorListT = BaseCppType("at", "TensorList")
+iTensorListRefT = BaseCppType("at", "ITensorListRef")
+iOptTensorListRefT = BaseCppType("at", "IOptTensorListRef")
+dimnameT = BaseCppType("at", "Dimname")
+dimnameListT = BaseCppType("at", "DimnameList")
+dimVectorT = BaseCppType("at", "DimVector")
+layoutT = BaseCppType("at", "Layout")
+deviceT = BaseCppType("at", "Device")
+deviceIndexT = BaseCppType("at", "DeviceIndex")
+scalarT = BaseCppType("at", "Scalar")
+optionalScalarRefT = BaseCppType("at", "OptionalScalarRef")
+memoryFormatT = BaseCppType("at", "MemoryFormat")
+qschemeT = BaseCppType("at", "QScheme")
+storageT = BaseCppType("at", "Storage")
+streamT = BaseCppType("at", "Stream")
+intArrayRefT = BaseCppType("at", "IntArrayRef")
+optionalIntArrayRefT = BaseCppType("at", "OptionalIntArrayRef")
+optionalSymIntArrayRefT = BaseCppType("at", "OptionalSymIntArrayRef")
+tensorOptionsT = BaseCppType("at", "TensorOptions")
+typeAndSizeT = BaseCppType("torch::autograd::generated", "TypeAndSize")
+tensorGeometryT = BaseCppType("at", "TensorGeometry")
+SymIntT = BaseCppType("c10", "SymInt")
+symIntArrayRefT = BaseCppType("c10", "SymIntArrayRef")
+
+# Types representing template parameters. Technically, we probably shouldn't
+# represent them this way in codegen, but it was pretty convenient.
+scalar_t = BaseCppType("", "scalar_t")
+opmath_t = BaseCppType("", "opmath_t")
+
+ScalarTypeToCppMapping: dict[ScalarType, BaseCppType] = {
+ ScalarType.Byte: byteT,
+ ScalarType.Char: charT,
+ ScalarType.Short: shortT,
+ ScalarType.Int: int32T,
+ ScalarType.Long: longT,
+ ScalarType.Half: halfT,
+ ScalarType.Float: floatT,
+ ScalarType.Double: doubleT,
+ ScalarType.ComplexHalf: complexHalfT,
+ ScalarType.ComplexFloat: complexFloatT,
+ ScalarType.ComplexDouble: complexDoubleT,
+ ScalarType.Bool: boolT,
+ ScalarType.Float8_e5m2: float8_e5m2T,
+ ScalarType.Float8_e5m2fnuz: float8_e5m2fnuzT,
+ ScalarType.Float8_e4m3fn: float8_e4m3fnT,
+ ScalarType.Float8_e4m3fnuz: float8_e4m3fnuzT,
+}
+
+BaseTypeToCppMapping: dict[BaseTy, BaseCppType] = {
+ BaseTy.int: longT,
+ BaseTy.float: doubleT,
+ BaseTy.bool: boolT,
+ BaseTy.str: stringT,
+ BaseTy.Generator: generatorT,
+ BaseTy.ScalarType: scalarTypeT,
+ BaseTy.Tensor: tensorT,
+ BaseTy.Dimname: dimnameT,
+ BaseTy.DimVector: dimVectorT,
+ BaseTy.Layout: layoutT,
+ BaseTy.Device: deviceT,
+ BaseTy.DeviceIndex: deviceIndexT,
+ BaseTy.Scalar: scalarT,
+ BaseTy.MemoryFormat: memoryFormatT,
+ BaseTy.QScheme: qschemeT,
+ BaseTy.Storage: storageT,
+ BaseTy.Stream: streamT,
+ BaseTy.SymInt: SymIntT,
+}
+
+# CTypes encode C++ type structure as needed for translation.
+
+
+@dataclass(frozen=True)
+class OptionalCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"::std::optional<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"::std::optional<{self.elem.cpp_type_registration_declarations()}>"
+
+ def remove_const_ref(self) -> CType:
+ return OptionalCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ListCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"c10::List<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"c10::List<{self.elem.cpp_type_registration_declarations()}>"
+
+ def remove_const_ref(self) -> CType:
+ return ListCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ArrayRefCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"at::ArrayRef<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"ArrayRef<{self.elem.cpp_type_registration_declarations()}>"
+
+ def remove_const_ref(self) -> CType:
+ return ArrayRefCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class VectorizedCType(CType):
+ # This template is explicitly specialized, so the only valid
+ # elems are those we have specializations for (e.g., float, double, ...)
+ # scalar_t is also a common argument here (when we are codegen in
+ # a templated context)
+ elem: BaseCType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ return f"at::vec::Vectorized<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ raise NotImplementedError
+
+ def remove_const_ref(self) -> CType:
+ return self
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/types_base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/types_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..c24016d74ef4835686532c8f544fcd77f1776765
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/types/types_base.py
@@ -0,0 +1,276 @@
+"""
+Where should I add a new type? `types_base.py` vs `types.py`
+
+This file defines data model classes for torchgen typing system, as well as some base types such as int32_t.
+
+`types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types.
+
+The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't
+contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused
+if we want to generate code for another C++ library.
+
+Add new types to `types.py` if these types are ATen/c10 related.
+Add new types to `types_base.py` if they are basic and not attached to ATen/c10.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from enum import auto, Enum
+from typing import TYPE_CHECKING, Union
+
+
+if TYPE_CHECKING:
+ from torchgen.model import Argument, SelfArgument, TensorOptionsArguments
+
+
+# An ArgName is just the str name of the argument in schema;
+# but in some special circumstances, we may add a little extra
+# context. The Enum SpecialArgName covers all of these cases;
+# grep for their construction sites to see when they can occur.
+
+
+class SpecialArgName(Enum):
+ possibly_redundant_memory_format = auto()
+
+
+ArgName = Union[str, SpecialArgName]
+
+
+# This class shouldn't be created directly; instead, use/create one of the singletons below.
+@dataclass(frozen=True)
+class BaseCppType:
+ ns: str | None
+ name: str
+
+ def __str__(self) -> str:
+ if self.ns is None or self.ns == "":
+ return self.name
+ return f"{self.ns}::{self.name}"
+
+
+# The set of all non-templated, valid, fully-qualified names of C++ types that are used in the codegen.
+# Templated types get their own dataclass, mainly to make namespace parsing easier.
+byteT = BaseCppType("", "uint8_t")
+charT = BaseCppType("", "int8_t")
+shortT = BaseCppType("", "int16_t")
+# It would be more symmetric for this to be called intT, but it easy to mix
+# this up with JIT int (which is int64_t in C++), so we intentionally don't
+# define intT to make it obvious when you've stuffed it up
+int32T = BaseCppType("", "int32_t")
+longT = BaseCppType("", "int64_t")
+doubleT = BaseCppType("", "double")
+floatT = BaseCppType("", "float")
+boolT = BaseCppType("", "bool")
+voidT = BaseCppType("", "void")
+
+
+class CType(ABC):
+ @abstractmethod
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ raise NotImplementedError
+
+ @abstractmethod
+ def cpp_type_registration_declarations(self) -> str:
+ raise NotImplementedError
+
+ @abstractmethod
+ def remove_const_ref(self) -> CType:
+ return self
+
+
+@dataclass(frozen=True)
+class BaseCType(CType):
+ type: BaseCppType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ return str(self.type)
+
+ # For BC reasons, we don't want to introduce at:: namespaces to RegistrationDeclarations.yaml
+ # TODO: Kill this when we eventually remove it!
+ def cpp_type_registration_declarations(self) -> str:
+ return str(self.type).replace("at::", "")
+
+ def remove_const_ref(self) -> CType:
+ return self
+
+
+@dataclass(frozen=True)
+class ConstRefCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ if strip_ref:
+ return self.elem.cpp_type(strip_ref=strip_ref)
+ return f"const {self.elem.cpp_type()} &"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"const {self.elem.cpp_type_registration_declarations()} &"
+
+ def remove_const_ref(self) -> CType:
+ return self.elem.remove_const_ref()
+
+
+@dataclass(frozen=True)
+class VectorCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"::std::vector<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"::std::vector<{self.elem.cpp_type_registration_declarations()}>"
+
+ def remove_const_ref(self) -> CType:
+ return VectorCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ArrayCType(CType):
+ elem: CType
+ size: int
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"::std::array<{self.elem.cpp_type()},{self.size}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"::std::array<{self.elem.cpp_type_registration_declarations()},{self.size}>"
+
+ def remove_const_ref(self) -> CType:
+ return ArrayCType(self.elem.remove_const_ref(), self.size)
+
+
+@dataclass(frozen=True)
+class TupleCType(CType):
+ elems: list[CType]
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f'::std::tuple<{",".join([e.cpp_type() for e in self.elems])}>'
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f'::std::tuple<{",".join([e.cpp_type_registration_declarations() for e in self.elems])}>'
+
+ def remove_const_ref(self) -> CType:
+ return TupleCType([e.remove_const_ref() for e in self.elems])
+
+
+@dataclass(frozen=True)
+class MutRefCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ if strip_ref:
+ return self.elem.cpp_type(strip_ref=strip_ref)
+ return f"{self.elem.cpp_type()} &"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"{self.elem.cpp_type_registration_declarations()} &"
+
+ def remove_const_ref(self) -> CType:
+ return self.elem.remove_const_ref()
+
+
+# A NamedCType is short for Named C++ semantic type. A NamedCType represents a C++ type, plus
+# semantic information about what it represents. For example, consider the
+# argument "bool pin_memory"; its normal C++ type is "bool", but its C++
+# semantic type also keeps track that this represents a "pin_memory"; you can't
+# just use a random other boolean in a context where you need a "pin_memory"!
+#
+
+
+@dataclass(frozen=True)
+class NamedCType:
+ name: ArgName
+ type: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ return self.type.cpp_type(strip_ref=strip_ref)
+
+ # For BC reasons, we don't want to introduce at:: namespaces to RegistrationDeclarations.yaml
+ # TODO: Kill this when we eventually remove it!
+ def cpp_type_registration_declarations(self) -> str:
+ return self.type.cpp_type_registration_declarations()
+
+ def remove_const_ref(self) -> NamedCType:
+ return NamedCType(self.name, self.type.remove_const_ref())
+
+ def with_name(self, name: str) -> NamedCType:
+ return NamedCType(name, self.type)
+
+
+# A binding represents any C++ binding site for a formal parameter.
+# We don't distinguish between binding sites for different APIs;
+# instead, all of the important distinctions are encoded in CType,
+# which you can use to figure out if a given Binding is appropriate
+# for use in another context. (See torchgen.api.translate)
+
+
+@dataclass(frozen=True)
+class Binding:
+ name: str
+ nctype: NamedCType
+ argument: Argument | TensorOptionsArguments | SelfArgument
+ # TODO: maybe don't represent default here
+ default: str | None = None
+
+ def rename(self, name: str) -> Binding:
+ return Binding(
+ name=name,
+ nctype=self.nctype,
+ argument=self.argument,
+ default=self.default,
+ )
+
+ @property
+ def type(self) -> str:
+ return self.nctype.cpp_type()
+
+ def no_default(self) -> Binding:
+ return Binding(
+ name=self.name,
+ nctype=self.nctype,
+ default=None,
+ argument=self.argument,
+ )
+
+ def decl(self, *, func_ptr_cast: bool = False) -> str:
+ mb_default = ""
+ if self.default is not None:
+ mb_default = f"={self.default}"
+
+ # casting only needs to know the type
+ if func_ptr_cast:
+ return f"{self.type}"
+ else:
+ return f"{self.type} {self.name}{mb_default}"
+
+ # For BC reasons, we don't want to introduce at:: namespaces to RegistrationDeclarations.yaml
+ # TODO: Kill this when we eventually remove it!
+ def decl_registration_declarations(self) -> str:
+ type_s = self.nctype.cpp_type_registration_declarations()
+ mb_default = ""
+ if self.default is not None:
+ mb_default = f"={self.default}"
+ return f"{type_s} {self.name}{mb_default}"
+
+ def defn(self) -> str:
+ return f"{self.type} {self.name}"
+
+ def with_name(self, name: str) -> Binding:
+ return Binding(
+ name=name, nctype=self.nctype, argument=self.argument, default=self.default
+ )
+
+
+# An Expr is a C++ expression. It has a C++ string representing its syntax,
+# as well as a CType saying what it provides.
+
+
+@dataclass(frozen=True)
+class Expr:
+ expr: str
+ type: NamedCType
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/ufunc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bfc0de5fe6fd3e8f56eb3753bdb8031d8e5c659
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/ufunc.py
@@ -0,0 +1,209 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import torchgen.api.types as api_types
+from torchgen.api import cpp, structured
+from torchgen.api.types import (
+ ArgName,
+ BaseCppType,
+ BaseCType,
+ Binding,
+ ConstRefCType,
+ CType,
+ NamedCType,
+ scalarT,
+)
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ DispatchKey,
+ FunctionSchema,
+ NativeFunctionsGroup,
+ Type,
+)
+
+
+def schema_kernel_name(func: FunctionSchema, dispatch_key: DispatchKey) -> str:
+ assert func.is_out_fn(), "ufunc.kernel_name should only be invoked on out schemas"
+ return f"ufunc_{func.name.name}_{dispatch_key}"
+
+
+def kernel_name(g: NativeFunctionsGroup, dispatch_key: DispatchKey) -> str:
+ return schema_kernel_name(g.out.func, dispatch_key)
+
+
+# Tensors are omitted (as they are stored in TensorIterator), everything else is
+# passed along (technically, we can pass tensors along too, it just wastes
+# argument registers)
+#
+# NB: used for CPU only
+def dispatchstub_type(t: Type, *, binds: ArgName) -> NamedCType | None:
+ # Dispatch stubs are always plain ints
+ r = cpp.valuetype_type(t, binds=binds, symint=False)
+ if r is not None:
+ return r
+
+ if t == BaseType(BaseTy.Scalar):
+ return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+ elif t == BaseType(BaseTy.Tensor):
+ return None
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+def opmath_type(scalar_t: BaseCppType) -> BaseCppType:
+ if scalar_t == api_types.scalar_t:
+ return api_types.opmath_t
+ raise NotImplementedError
+
+
+# NB: Tensors in constructor are stored in opmath_t, not scalar_t
+# because Tensor in constructor = its a scalar tensor partially applied =
+# it can be higher precision and we want to compute in that higher precision
+#
+# NB: CUDA only
+def ufunctor_ctor_type(t: Type, *, binds: ArgName, scalar_t: BaseCppType) -> NamedCType:
+ r = cpp.valuetype_type(t, binds=binds, symint=False)
+ if r is not None:
+ return r
+
+ if t == BaseType(BaseTy.Scalar):
+ return NamedCType(binds, BaseCType(opmath_type(scalar_t)))
+ elif t == BaseType(BaseTy.Tensor):
+ return NamedCType(binds, BaseCType(opmath_type(scalar_t)))
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Only Tensors ever get passed directly to operator()
+#
+# NB: CUDA only
+# (Actually, this works for CPU too)
+def ufunctor_apply_type(
+ t: Type, *, binds: ArgName, scalar_t: BaseCppType
+) -> NamedCType:
+ if t == BaseType(BaseTy.Tensor):
+ return NamedCType(binds, BaseCType(scalar_t))
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# The actual ufunc template function the user writes. Everything here
+# is done in the computation type. compute_t is opmath_t in CUDA and scalar_t
+# in CPU
+def ufunc_type(t: Type, *, binds: ArgName, compute_t: CType) -> NamedCType:
+ r = cpp.valuetype_type(t, binds=binds, symint=False)
+ if r is not None:
+ return r
+
+ if t == BaseType(BaseTy.Scalar):
+ return NamedCType(binds, compute_t)
+ elif t == BaseType(BaseTy.Tensor):
+ return NamedCType(binds, compute_t)
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+def ufunctor_ctor_argument(a: Argument, scalar_t: BaseCppType) -> Binding:
+ return Binding(
+ nctype=ufunctor_ctor_type(a.type, binds=a.name, scalar_t=scalar_t),
+ name=a.name,
+ default=None,
+ argument=a,
+ )
+
+
+def ufunctor_apply_argument(a: Argument, scalar_t: BaseCppType) -> Binding:
+ return Binding(
+ nctype=ufunctor_apply_type(a.type, binds=a.name, scalar_t=scalar_t),
+ name=a.name,
+ default=None,
+ argument=a,
+ )
+
+
+def ufunc_argument(a: Argument, compute_t: CType) -> Binding:
+ return Binding(
+ nctype=ufunc_type(a.type, binds=a.name, compute_t=compute_t),
+ name=a.name,
+ default=None,
+ argument=a,
+ )
+
+
+@dataclass(frozen=True)
+class UfunctorBindings:
+ ctor: list[Binding]
+ apply: list[Binding]
+
+
+# ufunctors are a CUDA-only concept representing functors that take some of
+# their arguments on a host-side constructor, and the rest in the device-side
+# apply. E.g.,
+#
+# template
+# struct CUDAFunctorOnSelf_add {
+# using opmath_t = at::opmath_type;
+# opmath_t other_;
+# opmath_t alpha_;
+# CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha) : other_(other), alpha_(alpha) {}
+# __device__ scalar_t operator()(scalar_t self) {
+# return ufunc::add(static_cast(self), other_, alpha_);
+# }
+# };
+#
+# The ctor refers to the constructor CUDAFunctorOnSelf_add, while apply refers
+# to the operator() definition
+def ufunctor_arguments(
+ g: NativeFunctionsGroup, *, scalar_tensor_idx: int | None, scalar_t: BaseCppType
+) -> UfunctorBindings:
+ ctor = []
+ apply = []
+ for a in g.functional.func.arguments.flat_non_out:
+ if a.type.is_tensor_like():
+ if scalar_tensor_idx == 0:
+ # put it in the ctor anyway
+ ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t))
+ scalar_tensor_idx = None
+ else:
+ if scalar_tensor_idx is not None:
+ scalar_tensor_idx -= 1
+ apply.append(ufunctor_apply_argument(a, scalar_t=scalar_t))
+ else:
+ ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t))
+ assert scalar_tensor_idx is None
+ return UfunctorBindings(ctor=ctor, apply=apply)
+
+
+# ufuncs are the inner loop template functions that you wrote in ufunc/add.h
+# which do the actual computation in question. E.g.,
+#
+# template
+# C10_HOST_DEVICE T add(T self, T other, T alpha) __ubsan_ignore_undefined__ {
+# return self + alpha * other;
+# }
+#
+# In this file, we refer to T as compute_t which is bound by caller
+def ufunc_arguments(g: NativeFunctionsGroup, *, compute_t: CType) -> list[Binding]:
+ return [
+ ufunc_argument(a, compute_t=compute_t)
+ for a in g.functional.func.arguments.flat_non_out
+ ]
+
+
+# Stubs are the DispatchStub trampolines that CPU kernels use to get to their
+# vectorized versions. E.g.,
+#
+# using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
+# DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub);
+def stub_arguments(g: NativeFunctionsGroup) -> list[Binding]:
+ # stubs drop all tensor arguments (they are implicit in the TensorIterator
+ # argument and keep everything else)
+ return [
+ r
+ for a in g.out.func.arguments.flat_non_out
+ if not a.type.is_tensor_like()
+ for r in structured.argument(a)
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/unboxing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/unboxing.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1249692aeeabbb95f4c4ecb6a8dfdd9015901eb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/api/unboxing.py
@@ -0,0 +1,241 @@
+from __future__ import annotations
+
+from torchgen.api import cpp
+from torchgen.api.types import Binding, CppSignatureGroup, CType
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ ListType,
+ NativeFunction,
+ OptionalType,
+ Type,
+)
+
+
+# This file generates the code for unboxing wrappers, i.e., the glue logic to unbox a boxed operator and convert the
+# ivalues from stack to correct arguments to the unboxed kernel, based on corresponding JIT schema. This codegen is
+# an alternative way to generate unboxing wrappers similar to the existing C++ metaprogramming approach but gets the
+# job done statically. These generated unboxing wrappers will be useful under the scenario where we need to register
+# a fixed set of operators known at compile time and thus can save some time in runtime initialization phase.
+#
+# Here's an example on how the codegen works:
+#
+# - Function Schema (source of truth)
+#
+# aten::empty.names(int[] size, *, Dimname[]? names,
+# ScalarType? dtype=None, Layout? layout=None,
+# Device? device=None, bool? pin_memory=None,
+# MemoryFormat? memory_format=None) -> Tensor
+# - Argument Conversion
+# Generates C++ code to convert an ivalue (from stack) to its underlying C++ type.
+# - int[] size
+# ```cpp
+# const c10::List size_list_in = (std::move(peek(stack, 0, 7))).toList();
+#
+# std::vector size_vec;
+# for (c10::IValue size_elem: size_list_in) {
+# int64_t size_base = size_elem.to();
+# size_vec.push_back(size_base);
+# }
+# at::ArrayRef size_list_out(size_vec);
+# ~~~~~~~~~~~~~ <-- The converted argument from ivalues in the stack.
+# Will be passed to unboxed kernel.
+# ```
+# - Dimname[]? names
+# ```cpp
+# ::std::optional names_opt = (std::move(peek(stack, 1, 7))).toOptional();
+# ::std::optional> names_opt_out;
+# if (names_opt.has_value()) {
+# ~~~~~~~~~~~ <-- Unwrapping optional shell
+# const c10::IValue names_opt_in = names_opt.value();
+# const c10::List names_list_in = names_opt_in.toList();
+#
+# std::vector names_vec;
+# for (c10::IValue names_elem: names_list_in) {
+# ~~~~~~~~~~~~~~~~~~~~~~~~~ <-- Unrolling list, then convert elements one by one.
+# at::Dimname names_base = names_elem.to();
+# names_vec.push_back(names_base);
+# }
+# at::ArrayRef names_list_out(names_vec);
+#
+# names_opt_out = ::std::optional>(names_list_out);
+# } else {
+# names_opt_out = ::std::optional>();
+# }
+# ```
+# - ScalarType? dtype (similarly for the rest of the arguments)
+# ```cpp
+# ::std::optional dtype_opt = (std::move(peek(stack, 2, 7))).toOptional();
+# ::std::optional dtype_opt_out;
+# if (dtype_opt.has_value()) {
+# const c10::IValue dtype_opt_in = dtype_opt.value();
+# at::ScalarType dtype_base = dtype_opt_in.to();
+# ~~~~~~~~~~~~~~~~~~~~ <-- For base types, convert ivalue to it
+# directly using ".to()" API.
+# dtype_opt_out = ::std::optional(dtype_base);
+# } else {
+# dtype_opt_out = ::std::optional();
+# }
+# ```
+#
+# - Unboxed Kernel Call
+# ```cpp
+# auto result_ = torch::empty(
+# size_list_out,
+# names_opt_out,
+# options,
+# memory_format_opt_out
+# );
+# ```
+#
+# - Push Result Back to Stack
+# ```cpp
+# drop(stack, 7);
+# pack(stack, std::move(result_));
+# ```
+connector = "\n\t"
+
+
+# Return unboxing function name for a NativeFunction
+def name(f: NativeFunction) -> str:
+ return f.func.name.unambiguous_name()
+
+
+# Convert all the arguments in a NativeFunction to C++ code
+def convert_arguments(f: NativeFunction) -> tuple[list[Binding], list[str]]:
+ # we need the 'self' argument so method needs to be False
+ args = (
+ CppSignatureGroup.from_native_function(f, method=False)
+ .most_faithful_signature()
+ .arguments()
+ )
+ code_list = [
+ f"c10::IValue {args[i].name} = std::move(peek(stack, {i}, {len(args)}));"
+ for i in range(len(args))
+ ] + [""]
+ binding_list = []
+ for arg in args:
+ # expecting only Argument
+ if not isinstance(arg.argument, Argument):
+ raise Exception( # noqa: TRY002
+ f"Unexpected argument type, expecting `Argument` but got {arg}"
+ )
+ argument: Argument = arg.argument
+ unboxed_name, _, code, decl = argumenttype_ivalue_convert(
+ argument.type,
+ argument.name,
+ mutable=argument.is_write,
+ )
+ code_list.extend(decl)
+ code_list.extend(code)
+ binding_list.append(arg.with_name(unboxed_name))
+ return binding_list, code_list
+
+
+# Takes in the type, name and mutability corresponding to an argument, and generates a tuple of:
+# (1) the C++ code necessary to unbox the argument
+# (2) A Binding corresponding to the newly created unboxed variable, including variable name and its CType
+def argumenttype_ivalue_convert(
+ t: Type, arg_name: str, *, mutable: bool = False
+) -> tuple[str, CType, list[str], list[str]]:
+ # Unboxing is for mobile, which doesn't care about SymInts
+ ctype = cpp.argumenttype_type(
+ t=t, mutable=mutable, binds=arg_name, symint=False
+ ).type
+
+ if isinstance(t, BaseType):
+ out_name = f"{arg_name}_base"
+ code, decl = _gen_code_base_type(
+ arg_name=arg_name, out_name=out_name, ctype=ctype
+ )
+ elif isinstance(t, OptionalType):
+ out_name = f"{arg_name}_opt_out"
+ code, decl = _gen_code_optional_type(
+ arg_name=arg_name,
+ out_name=out_name,
+ t=t,
+ ctype=ctype,
+ )
+ elif isinstance(t, ListType):
+ out_name = f"{arg_name}_list_out"
+ code, decl = _gen_code_list_type(
+ arg_name=arg_name,
+ out_name=out_name,
+ t=t,
+ ctype=ctype,
+ )
+ else:
+ raise Exception(f"Cannot handle type {t}. arg_name: {arg_name}") # noqa: TRY002
+ return out_name, ctype, code, decl
+
+
+def _gen_code_base_type(
+ arg_name: str, out_name: str, ctype: CType
+) -> tuple[list[str], list[str]]:
+ return [
+ f"{ctype.cpp_type(strip_ref=True)} {out_name} = {arg_name}.to<{ctype.cpp_type(strip_ref=True)}>();"
+ ], []
+
+
+def _gen_code_optional_type(
+ arg_name: str, out_name: str, t: OptionalType, ctype: CType
+) -> tuple[list[str], list[str]]:
+ in_name = f"{arg_name}_opt_in"
+ res_name, _, res_code, decl = argumenttype_ivalue_convert(t.elem, in_name)
+ return (
+ f"""
+auto {arg_name}_opt = {arg_name}.toOptional();
+{ctype.cpp_type(strip_ref=True)} {out_name};
+if ({arg_name}_opt.has_value()) {{
+ const c10::IValue {in_name} = {arg_name}_opt.value();
+ {connector.join(res_code)}
+ {out_name} = {ctype.cpp_type(strip_ref=True)}({res_name});
+}} else {{
+ {out_name} = {ctype.cpp_type(strip_ref=True)}();
+}}
+ """.split("\n"),
+ decl,
+ )
+
+
+def _gen_code_list_type(
+ arg_name: str, out_name: str, t: ListType, ctype: CType
+) -> tuple[list[str], list[str]]:
+ in_name = f"{arg_name}_list_in"
+ elem_name = f"{arg_name}_elem"
+ code = [f"const c10::List {in_name} = {arg_name}.toList();"]
+ res_name, res_ctype, res_code, decl = argumenttype_ivalue_convert(t.elem, elem_name)
+ # handle list type with size, e.g., bool[4]
+ if isinstance(t.elem, BaseType) and t.elem.name == BaseTy.bool and t.size:
+ code.extend(
+ f"""
+{ctype.cpp_type(strip_ref=True)} {out_name} = as_array<{res_ctype.cpp_type(strip_ref=True)}, {t.size}>({in_name});
+ """.split("\n")
+ )
+ # we have to use c10::List for optional element. e.g., Tensor?[] -> c10::List<::std::optional>
+ elif isinstance(t.elem, OptionalType):
+ code.extend(
+ f"""
+{ctype.cpp_type(strip_ref=True)} {out_name};
+for (c10::IValue {elem_name}: {in_name}) {{
+ {connector.join(res_code)}
+ {out_name}.push_back({res_name});
+}}
+ """.split("\n")
+ )
+ else:
+ # use ArrayRef as default.
+ vec_name = arg_name + "_vec"
+ # need to bring vector instantiation out of scope so that ArrayRef has valid data
+ decl.append(f"std::vector<{res_ctype.cpp_type(strip_ref=True)}> {vec_name};")
+ code.extend(
+ f"""
+for (c10::IValue {elem_name}: {in_name}) {{
+ {connector.join(res_code)}
+ {vec_name}.push_back({res_name});
+}}
+{ctype.cpp_type(strip_ref=True)} {out_name}({vec_name});
+ """.split("\n")
+ )
+ return code, decl
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3db7b19d69fbcb8ce74e03dba7a53e85f2b17c20
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__init__.py
@@ -0,0 +1,19 @@
+from torchgen.dest.lazy_ir import (
+ generate_non_native_lazy_ir_nodes as generate_non_native_lazy_ir_nodes,
+ GenLazyIR as GenLazyIR,
+ GenLazyNativeFuncDefinition as GenLazyNativeFuncDefinition,
+ GenLazyShapeInferenceDefinition as GenLazyShapeInferenceDefinition,
+)
+from torchgen.dest.native_functions import (
+ compute_native_function_declaration as compute_native_function_declaration,
+)
+from torchgen.dest.register_dispatch_key import (
+ gen_registration_headers as gen_registration_headers,
+ gen_registration_helpers as gen_registration_helpers,
+ RegisterDispatchKey as RegisterDispatchKey,
+)
+from torchgen.dest.ufunc import (
+ compute_ufunc_cpu as compute_ufunc_cpu,
+ compute_ufunc_cpu_kernel as compute_ufunc_cpu_kernel,
+ compute_ufunc_cuda as compute_ufunc_cuda,
+)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00f43bd2399b542d19d235cf58de3256eab6573d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4d7a87f1f0b7d1396b8761d3fd6bc75bcbaa10f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..478a4c79b299246c2f4df60cdf43d2c14001ebd3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/native_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/native_functions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6018bd897c32ab4e5cb70f9a24135fc1f58d01fc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/native_functions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c222aa20682f3104621e4dadc6e89532f2ccac9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/ufunc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/ufunc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f73f4dfad6b21dc3f45d416c8b6ea2d676145a34
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/__pycache__/ufunc.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/lazy_ir.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/lazy_ir.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b296e9a3ffa994ced909992f4c6dd3c04deded2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/lazy_ir.py
@@ -0,0 +1,707 @@
+from __future__ import annotations
+
+import itertools
+from abc import ABC
+from dataclasses import dataclass
+from typing import Any
+
+import torchgen.api.dispatcher as dispatcher
+from torchgen.api.lazy import (
+ getValueT,
+ isValueType,
+ LazyArgument,
+ LazyIrProperties,
+ LazyIrSchema,
+ tensorListValueT,
+)
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+ BaseCType,
+ Binding,
+ deviceT,
+ DispatcherSignature,
+ kernel_signature,
+ NativeSignature,
+ OptionalCType,
+ VectorCType,
+)
+from torchgen.context import method_with_native_function
+from torchgen.dest.lazy_ts_lowering import ts_lowering_body
+from torchgen.model import (
+ Argument,
+ BackendIndex,
+ BackendMetadata,
+ BaseTy,
+ BaseType,
+ FunctionSchema,
+ ListType,
+ NativeFunction,
+ NativeFunctionsGroup,
+)
+
+
+def node_ctor_arg_rvalue_string(arg: LazyArgument) -> str:
+ """
+ Given a LazyArgument,
+ generate a c++ string for materializing an rvalue of that arg for passing into
+ a lazy Node constructor.
+ """
+
+ # TODO: Matching on CType seems wrong; should be matching on Type
+ if isValueType(arg.lazy_type):
+ if isinstance(arg.lazy_type, BaseCType):
+ if arg.is_wrapped_scalar:
+ return f"node_{arg.name}"
+ elif arg.lazy_type.type is tensorListValueT:
+ return f"lazy_{arg.name}_tensorlist"
+ elif arg.is_symint_or_list:
+ return f"GetSymIntValue({arg.name})"
+ return f"lazy_{arg.name}->GetIrValue()"
+ elif isinstance(arg.lazy_type, OptionalCType):
+ if arg.is_symint_or_list:
+ # TODO: I don't understand when you should put lazy_ in the name
+ # or not
+ return f"{arg.name} ? std::make_optional(GetSymIntValue(*{arg.name})) : ::std::nullopt"
+ elif arg.is_wrapped_scalar:
+ return f"node_{arg.name}"
+ return (
+ f"lazy_{arg.name} ? "
+ f"std::make_optional(lazy_{arg.name}->GetIrValue()) : "
+ "::std::nullopt"
+ )
+ else:
+ raise AssertionError(
+ f"TODO not sure if there are other valid types to handle here ({arg.lazy_type})"
+ )
+ else:
+ # NB: this is here because right now we aren't treating SymInt[] as a
+ # value type; when we do this needs to move above
+ # NB: we cannot test arg.lazy_type as we've already specified it is an
+ # int64_t and so we cannot distinguish between SymInt and int64_t
+ if isinstance(arg.orig_type, ListType) and arg.orig_type.elem == BaseType(
+ BaseTy.SymInt
+ ):
+ if arg.symint:
+ return f"GetSymIntArrayRefValue({arg.name})"
+ else:
+ return f"std::vector({arg.name}.begin(), {arg.name}.end())"
+ elif isinstance(arg.lazy_type, VectorCType) and isinstance(
+ arg.lazy_type.elem, BaseCType
+ ):
+ return f"std::vector<{arg.lazy_type.elem.type}>({arg.name}.begin(), {arg.name}.end())"
+ elif (
+ isinstance(arg.lazy_type, OptionalCType)
+ and isinstance(arg.lazy_type.elem, VectorCType)
+ and isinstance(arg.lazy_type.elem.elem, BaseCType)
+ ):
+ return f"torch::lazy::ToOptionalVector<{arg.lazy_type.elem.elem.type}>({arg.name})"
+ else:
+ return f"{arg.name}"
+
+
+def node_ctor_inputs(schema: LazyIrSchema) -> str:
+ """
+ Produce a formatted string with the arguments as passed into the constructor of a node class.
+ """
+ node_ctor_values = [
+ node_ctor_arg_rvalue_string(arg) for arg in schema.filtered_args()
+ ]
+ return ", ".join(node_ctor_values)
+
+
+def gen_fallback_code(
+ schema: LazyIrSchema,
+ sig: DispatcherSignature | NativeSignature,
+ overload_name: str,
+) -> str:
+ """
+ Generate code that falls back to eager conditioned on a predicate
+ """
+ dispatcher_sig = DispatcherSignature.from_schema(schema.func)
+ exprs = translate(sig.arguments(), dispatcher_sig.arguments())
+ fallback_args = ",\n ".join([a.expr for a in exprs])
+ if len(overload_name):
+ aten_op_str = f"ATEN_OP2({schema.aten_name}, {overload_name})"
+ else:
+ aten_op_str = f"ATEN_OP({schema.aten_name})"
+ return f"""
+ if (force_eager_fallback({aten_symbol(schema)})) {{
+ return at::native::call_fallback_fn_symint<<c_eager_fallback, {aten_op_str}>::call(
+ {fallback_args}
+ );
+ }}
+"""
+
+
+def aten_symbol(schema: LazyIrSchema) -> str:
+ missing_interned_strings = {
+ "sigmoid_backward",
+ }
+ if schema.aten_name in missing_interned_strings:
+ return f'c10::Symbol::fromQualString("aten::{schema.aten_name}")'
+
+ if not schema.aten_name.startswith("at::"):
+ return f"at::aten::{schema.aten_name}"
+ else:
+ return schema.aten_name
+
+
+# converts all tensor-like arguments to meta tensors. Returns:
+# (1) a string containing all of the logic that does the conversions.
+# (2) a context, to be used by translate(), with all of the relevant bindings.
+def convert_to_meta_tensors(sig: DispatcherSignature) -> tuple[str, list[Binding]]:
+ context: list[Binding] = []
+ unwrapped_tensor_args: list[str] = []
+ for arg in sig.arguments():
+ if isinstance(arg.argument, Argument) and arg.argument.type.is_tensor_like():
+ unwrapped_name = f"{arg.name}_meta"
+ unwrapped_tensor_args.append(
+ f"auto {unwrapped_name} = to_meta({arg.name});"
+ )
+ context.append(arg.with_name(unwrapped_name))
+ else:
+ context.append(arg)
+ unwrap_tensor_args_str = "\n ".join(unwrapped_tensor_args)
+ return unwrap_tensor_args_str, context
+
+
+@dataclass(frozen=True)
+class GenLazyIR(ABC):
+ backend_index: BackendIndex
+ backend_name: str
+ node_base: str
+ use_lazy_shape: bool
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]:
+ func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func
+ metadata = self.backend_index.get_kernel(
+ f.functional if isinstance(f, NativeFunctionsGroup) else f
+ )
+ schema = LazyIrSchema(
+ func, symint=metadata is not None and metadata.supports_symint()
+ )
+ return self.gen(schema)
+
+ # there is no lowering functionality generated unless this IR base class is subclassed and
+ # implemented as a backend-specific node
+ def lowering_function(self, schema: LazyIrSchema) -> str:
+ return ""
+
+ def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+ return ""
+
+ def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+ return f"""bool CanBeReused({node_ctor_args}) const {{
+ return false;
+ }}"""
+
+ def node_base_ctor_call(self, schema: LazyIrSchema) -> str:
+ value_args = schema.filtered_args(values=True, scalars=False)
+ # backends can customize the way the node base class constructor is called,
+ # as long as all of its arguments can be generated from information available from the schema
+ base_ctor_value_args_list = []
+ for arg in value_args:
+ if isinstance(arg.lazy_type, (BaseCType, VectorCType)):
+ base_ctor_value_args_list.append(f"{arg.name}")
+ elif isinstance(arg.lazy_type, OptionalCType):
+ base_ctor_value_args_list.append(f"{arg.name}.value_or(kNullValue)")
+ else:
+ raise AssertionError(
+ f"Unsupported type ({arg.lazy_type}) - add support if necessary"
+ )
+ base_ctor_value_args = ", ".join(base_ctor_value_args_list)
+
+ scalar_args = schema.filtered_args(values=False, scalars=True)
+
+ # Shape construction.
+ # Conditionally build shape depending on specified shape property
+ if schema.properties.ShapePrecompute:
+ shape_ctor_arg = "std::move(shapes),"
+ elif schema.properties.ShapeCompute:
+ shape_args = [a.name for a in value_args]
+ shape_args.extend(a.name for a in scalar_args)
+ shape_ctor_arg = f"compute_shape_{schema.name}({', '.join(shape_args)}),"
+ elif schema.properties.ShapeCache:
+ shape_args = [f"operand({i})" for i in range(len(value_args))]
+ shape_args.extend(a.name for a in scalar_args)
+ shape_ctor_arg = f"[&](){{ return compute_shape_{schema.name}({', '.join(shape_args)})[0]; }},"
+ else:
+ shape_ctor_arg = ""
+
+ scalar_hashes = ", ".join(f"{a.name}" for a in scalar_args)
+
+ return f"""{self.node_base}(
+ {schema.node_name}::ClassOpKind(),
+ OpList{{{base_ctor_value_args}}},
+ {shape_ctor_arg}
+ /* num_outputs */ {len(schema.returns)},
+ torch::lazy::MHash({scalar_hashes}))"""
+
+ def gen(self, schema: LazyIrSchema) -> list[str]:
+ opkind = schema.opkind or aten_symbol(schema)
+
+ # for now, we just want one IR class decl and soon after also the method defs
+ # and we use the functional version not out/inplace.
+ all_args = schema.filtered_args()
+ scalar_args = schema.filtered_args(values=False, scalars=True)
+
+ ctor_args = [f"const {i.lazy_type.cpp_type()}& {i.name}" for i in all_args]
+ reuse_ctor_args = ", ".join(ctor_args)
+ if self.use_lazy_shape and schema.properties.ShapePrecompute:
+ ctor_args.append("std::vector&& shapes")
+ node_ctor_args = ", ".join(ctor_args)
+
+ scalar_initializers = ",\n ".join(
+ [
+ # This code is just special casing the mapping from string_view -> strings
+ f"{a.name}({a.name}.has_value() ? ::std::make_optional(std::string(*{a.name})) : ::std::nullopt)"
+ if a.lazy_type.cpp_type() == "::std::optional"
+ else f"{a.name}({a.name})"
+ for a in scalar_args
+ ]
+ )
+ if len(scalar_initializers):
+ scalar_initializers = f",\n {scalar_initializers}"
+ scalar_decls = "\n ".join(
+ [
+ f"std::string {a.name};"
+ if a.lazy_type.cpp_type() == "c10::string_view"
+ else f"::std::optional {a.name};"
+ if a.lazy_type.cpp_type() == "::std::optional"
+ else f"{a.lazy_type.cpp_type()} {a.name};"
+ for a in scalar_args
+ ]
+ )
+ optional_values = [
+ arg.name
+ for arg in schema.filtered_args(values=True, scalars=False)
+ if isinstance(arg.lazy_type, OptionalCType)
+ ]
+ has_optional_decls = "\n ".join(
+ [f"bool has_{value}: 1;" for value in optional_values]
+ )
+ has_optional_defs = "\n ".join(
+ [f"has_{value} = !!{value};" for value in optional_values]
+ )
+ members_to_string = []
+ for arg in scalar_args:
+ if isinstance(arg.lazy_type, OptionalCType):
+ value = f"{arg.name}.value()"
+ if arg.is_generator:
+ value = '"torch.Generator()"'
+ members_to_string.append(
+ f"""if ({arg.name}.has_value()) {{
+ ss << ", {arg.name}=" << {value};
+ }} else {{
+ ss << ", {arg.name}=null";
+ }}"""
+ )
+ else:
+ members_to_string.append(f'ss << ", {arg.name}=" << {arg.name};')
+ members_to_string_str = "\n ".join(members_to_string)
+
+ return [
+ f"""\
+class {schema.node_name} : public {self.node_base} {{
+ public:
+ static torch::lazy::OpKind ClassOpKind() {{
+ return torch::lazy::OpKind({opkind});
+ }}
+
+ {schema.node_name}({node_ctor_args})
+ : {self.node_base_ctor_call(schema)}{scalar_initializers}
+ {{
+ {has_optional_defs}
+ }}
+
+ std::string ToString() const override {{
+ std::stringstream ss;
+ ss << {self.node_base}::ToString();
+ {members_to_string_str}
+ return ss.str();
+ }}
+
+ {self.create_function(schema, reuse_ctor_args)}
+
+ {self.can_be_reused_function(schema, reuse_ctor_args)}
+
+ {self.lowering_function(schema)}
+
+ {scalar_decls}
+ {has_optional_decls}
+
+}};
+
+""",
+ ]
+
+
+@dataclass(frozen=True)
+class GenTSLazyIR(GenLazyIR):
+ def lowering_function(self, schema: LazyIrSchema) -> str:
+ signature = """
+ torch::lazy::TSOpVector Lower(
+ std::shared_ptr function,
+ torch::lazy::TSLoweringContext* loctx) const override"""
+
+ if schema.properties.LowerDeclOnly:
+ return f"{signature};"
+ elif schema.properties.Lower:
+ return f"""{signature} {{
+ {ts_lowering_body(schema)}
+ }}
+ """
+ else:
+ return ""
+
+ def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+ signature = f"static NodePtr Create({node_ctor_args})"
+ if schema.properties.CreateFnDeclOnly:
+ return f"{signature};"
+ elif not schema.properties.CreateFn:
+ return ""
+ return f"""{signature} {{
+ return ReuseOrMakeNode<{schema.node_name}>(data);
+ }}"""
+
+ def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
+ signature = f"bool CanBeReused({node_ctor_args}) const"
+ if schema.properties.CanBeReusedDeclOnly:
+ return f"{signature};"
+ elif not schema.properties.CanBeReused:
+ return ""
+ value_comparison = []
+ for arg in itertools.chain(schema.positional_values, schema.keyword_values):
+ if isinstance(arg.lazy_type, OptionalCType):
+ value_comparison.append(
+ f"nullable_operand(i++) == {arg.name}.value_or(kNullValue)"
+ )
+ else:
+ value_comparison.append(f"operand(i++) == {arg.name}")
+ for arg in itertools.chain(schema.positional_scalars, schema.keyword_scalars):
+ if isinstance(arg.lazy_type, OptionalCType):
+ value_comparison.append(
+ f"((!this->{arg.name}&&!{arg.name}) || (this->{arg.name}&&{arg.name} && *(this->{arg.name}) == *{arg.name}))"
+ )
+ else:
+ value_comparison.append(f"this->{arg.name} == {arg.name}")
+ value_comparison_str = " &&\n ".join(value_comparison)
+
+ return f"""{signature} {{
+ size_t i = 0;
+ return ({value_comparison_str});
+ }}"""
+
+
+@dataclass(frozen=True)
+class GenLazyNativeFuncDefinition:
+ class_method_name: str
+ backend_index: BackendIndex
+ tensor_class: str
+ gen_forced_fallback_code: bool
+ backend_namespace: str
+ get_tensorlist: str
+ get_tensor_or_wrap_number: str
+ try_get_tensor: str
+ metrics_counter: str
+ create_tensor: str
+ create_from_first_tensor: bool
+ create_aten_from_ltc_tensor: str
+ tuple_aten_from_ltc_tensors: str
+ lazy_tensor_ptr: str
+ get_device_fn: str
+
+ def lazy_tensor_decls(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+ value_args = schema.filtered_args(values=True, scalars=False)
+ # Generates lazy_{name} variables for LazyTensors wrapping input tensors
+ lazy_tensor_decls: list[str] = []
+ for arg in value_args:
+ if arg.is_wrapped_scalar:
+ if isinstance(arg.lazy_type, OptionalCType):
+ lazy_tensor_decls.append(
+ f"""auto node_{arg.name} = {arg.name} ?
+ std::make_optional(torch::lazy::LazyGraphExecutor::Get()->
+ GetIrValueForScalarFromCodegen(*{arg.name}, *common_device)):
+ ::std::nullopt;"""
+ )
+ else:
+ lazy_tensor_decls.append(
+ f"""auto node_{arg.name} = torch::lazy::LazyGraphExecutor::Get()->
+ GetIrValueForScalarFromCodegen({arg.name}, *common_device);"""
+ )
+ elif arg.is_symint_or_list:
+ continue # values are extracted in isValueType
+ elif isinstance(arg.lazy_type, BaseCType):
+ if arg.lazy_type.type is tensorListValueT:
+ lazy_tensor_decls.append(
+ f"auto lazy_{arg.name}_tensorlist = "
+ f"{self.backend_namespace}::{self.get_tensorlist}({arg.name});"
+ )
+ else:
+ lazy_tensor_decls.append(
+ f"{self.lazy_tensor_ptr} lazy_{arg.name} = "
+ f"{self.backend_namespace}::{self.get_tensor_or_wrap_number}({arg.name}, *common_device);"
+ )
+ elif isinstance(arg.lazy_type, OptionalCType):
+ assert arg.lazy_type.elem == BaseCType(getValueT()), arg.lazy_type.elem
+ # TODO(alanwaketan): Maybe we want to apply GetLtcTensorOrCreateForWrappedNumber here, but hold it
+ # until we encounter a real world example.
+ lazy_tensor_decls.append(
+ f"{self.lazy_tensor_ptr} lazy_{arg.name} = "
+ f"{self.backend_namespace}::{self.try_get_tensor}({arg.name}.value_or(at::Tensor()));"
+ )
+ else:
+ raise AssertionError(
+ f"TODO not sure if there are other valid types to handle here ({arg.lazy_type})"
+ )
+ return ("\n ").join(lazy_tensor_decls)
+
+ def force_eager_fallback(
+ self,
+ func: NativeFunction,
+ schema: LazyIrSchema,
+ metadata: BackendMetadata,
+ sig: DispatcherSignature | NativeSignature,
+ ) -> str:
+ if self.gen_forced_fallback_code:
+ return gen_fallback_code(
+ schema, sig, overload_name=func.func.name.overload_name
+ )
+ return ""
+
+ def metrics(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+ return f"{self.metrics_counter};"
+
+ def get_device(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+ value_args = schema.filtered_args(values=True, scalars=False)
+ scalar_args = schema.filtered_args(values=False, scalars=True)
+ value_types_names = [f"{a.name}" for a in value_args if not a.is_wrapped_scalar]
+ optional_device = OptionalCType(BaseCType(deviceT))
+ optional_devices = [
+ a.name for a in scalar_args if a.lazy_type == optional_device
+ ]
+ assert (
+ len(value_types_names) > 0 or len(optional_devices) > 0
+ ), "Expected at least one Value or Device type"
+ get_device_str = (
+ f"{self.get_device_fn}({', '.join(value_types_names + optional_devices)})"
+ )
+ return f"""auto common_device = {get_device_str};
+ TORCH_INTERNAL_ASSERT(common_device);
+ """
+
+ def shape_inference(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+ metadata = self.backend_index.get_kernel(func)
+ assert metadata is not None
+ all_args = schema.filtered_args()
+ returns_length = len(schema.returns)
+ # call the meta kernel if it exists, to compute output shape/dtype for our IR
+ # Note [Generated LTC Shape Functions]
+ # LTC uses meta tensors from core to do shape inference when possible, and otherwise
+ # we generate a shape function declaration that needs to be manually implemented.
+ # How do we detect which ops are eligible to use meta tensors?
+ # In general we should be able to use meta tensors not just on structured operators,
+ # but also on composite operators that are implemented in terms of structured kernels.
+ # We don't currently have a way of knowing at codegen time which ops are implemented that way.
+ # This is the case for all view and view_copy operators however, so we're going to
+ # use them specifically for all of the view_copy ops (instead of manually writing shape rules for all of them).
+ is_view_copy_op = "view_copy" in func.tags
+ is_structured = func.structured or func.structured_delegate is not None
+ if is_structured or is_view_copy_op:
+ meta_out = """
+std::vector shapes{torch::lazy::Shape(out_meta.scalar_type(), out_meta.sizes().vec())};"""
+ if returns_length > 1:
+
+ def this_shape(i: int) -> str:
+ return f"torch::lazy::Shape(std::get<{i}>(out_meta).scalar_type(), std::get<{i}>(out_meta).sizes().vec())"
+
+ shapes_str = ",".join([this_shape(i) for i in range(returns_length)])
+ meta_out = "std::vector shapes{" + shapes_str + "};"
+
+ # Convert tensor args to the meta device and call it.
+ # (We can't pass in the input tensors directly, because they are "functional wrappers".
+ # If any of the meta kernels call a tensor op and redispatch, we don't want to hit the functionalize kernels.)
+ # Even at::meta:: functions might redispatch, e.g. if they call into view ops.
+ dispatcher_sig = DispatcherSignature.from_schema(func.func)
+ meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig)
+ meta_call_args = [
+ e.expr
+ for e in translate(
+ meta_call_ctx, dispatcher_sig.arguments(), method=False
+ )
+ ]
+ if is_view_copy_op:
+ # view_copy ops always have a CompositeExplicitAutogradNonFunctional kernel
+ assert func.has_composite_explicit_autograd_non_functional_kernel
+ dispatch_ns = "compositeexplicitautogradnonfunctional"
+ else:
+ dispatch_ns = "meta"
+ aten_name = schema.aten_name
+ # TODO: this is trolling
+ if func.func.has_symint() and metadata.supports_symint():
+ aten_name += "_symint"
+ shape_str = f"""\
+ {meta_conversion_str}
+ auto out_meta = at::{dispatch_ns}::{aten_name}({', '.join(meta_call_args)});
+ {meta_out}"""
+ else:
+ shape_sig = ComputeShapeSignature(
+ metadata.kernel, func, symint=metadata.supports_symint()
+ )
+ shape_str = f"""
+ auto shapes = {shape_sig.shape_call};"""
+
+ shape_str += f"""
+ TORCH_INTERNAL_ASSERT(shapes.size() == {returns_length});"""
+
+ # Calculating which dimensions are symbolic
+ func_schema_str = "aten::" + str(func.func)
+ shape_str += f"""
+ if(torch::lazy::symbolicShapeEnabled()){{
+ std::vector inputs = {{ {', '.join(str(a.name) for a in all_args)} }};
+ const char* schema_str = "{func_schema_str}";
+ applySymbolicShapesOnLT(schema_str, inputs, shapes);
+ }}
+ """
+ return shape_str
+
+ def build_ir_node(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+ node_ctor_input_str = node_ctor_inputs(schema)
+ return f"""torch::lazy::NodePtr node = torch::lazy::ReuseNode<{schema.node_name}>({node_ctor_input_str});
+ if (!node) {{
+ {self.shape_inference(func, schema)}
+ node = torch::lazy::MakeNode<{schema.node_name}>({node_ctor_input_str}, std::move(shapes));
+ CacheNode(node);
+ }}
+ """
+
+ def create_lazy_tensor(self, first_tensor_name: str | None = None) -> str:
+ # xla uses an instance method for tensor creation, for the time being
+ if self.create_from_first_tensor:
+ # TODO(whc) remove this if XLA switches to using static method for creation
+ assert (
+ first_tensor_name is not None
+ ), "Requires first tensor to create lazy tensor"
+ return f"{first_tensor_name}.{self.create_tensor}"
+ return f"{self.backend_namespace}::{self.create_tensor}"
+
+ def return_aten_tensor(self, func: NativeFunction, schema: LazyIrSchema) -> str:
+ returns_length = len(schema.returns)
+ value_args = schema.filtered_args(values=True, scalars=False)
+ value_types_names = [f"{a.name}" for a in value_args if not a.is_wrapped_scalar]
+ first_tensor_name = value_types_names[0] if len(value_types_names) > 0 else None
+ bridge_str = f"""auto result = {self.create_aten_from_ltc_tensor}(
+ {self.create_lazy_tensor(first_tensor_name)}(std::move(node), *common_device));"""
+
+ if returns_length > 1:
+ assert (
+ len(value_types_names) > 0
+ ), "Code below assumes there is at least one tensor arg"
+ bridge_str = f"""std::vector<{self.lazy_tensor_ptr}> lazy_tensors;
+ for (int i = 0; i < {returns_length}; i++) {{
+ lazy_tensors.push_back({self.create_lazy_tensor(first_tensor_name)}({getValueT()}(node, i), *common_device));
+ }}
+ auto result = {self.tuple_aten_from_ltc_tensors}<{returns_length}>(lazy_tensors);"""
+
+ if schema.name.name.inplace or func.func.is_out_fn():
+ assert returns_length == 1, (
+ "We assumed there was no such case where an op is an in-place variant "
+ f"and has tuple outputs, but got tuple of len {returns_length}."
+ )
+ bridge_str = f"""lazy_{first_tensor_name}->SetInPlaceIrValue(node);
+ auto& result = {first_tensor_name};"""
+
+ bridge_str += """
+ return result;"""
+ return bridge_str
+
+ @method_with_native_function
+ def __call__(self, func: NativeFunction) -> list[str]:
+ sig = kernel_signature(func, self.backend_index)
+ metadata = self.backend_index.get_kernel(func)
+ assert metadata is not None
+ schema = LazyIrSchema(func.func, symint=metadata.supports_symint())
+ return [
+ f"""\
+ {sig.decl(name=f"{self.class_method_name}::{metadata.kernel}")} {{
+ {self.force_eager_fallback(func, schema, metadata, sig)}
+ {self.metrics(func, schema)}
+ {self.get_device(func, schema)}
+ {self.lazy_tensor_decls(func, schema)}
+ {self.build_ir_node(func, schema)}
+ {self.return_aten_tensor(func, schema)}
+ }}\n
+ """
+ ]
+
+
+class ComputeShapeSignature:
+ """
+ Here we use the base name as the suffix of the signature to avoid generating for in-place variants.
+ """
+
+ def __init__(self, kernel_name: str, f: NativeFunction, *, symint: bool) -> None:
+ self.__schema = LazyIrSchema(f.func, symint=symint)
+ self.__dispatch_args = ", ".join(
+ [a.decl() for a in dispatcher.arguments(f.func, symint=symint)]
+ )
+ self.__call_args = ", ".join(
+ [f"{arg.name}" for arg in self.__schema.filtered_args(generator=True)]
+ )
+ self.__kernel_name = kernel_name
+
+ def __decl_suffix(self) -> str:
+ return f"{self.__kernel_name}({self.__dispatch_args})"
+
+ def __call_suffix(self) -> str:
+ return f"{self.__kernel_name}({self.__call_args})"
+
+ @property
+ def shape_decl(self) -> str:
+ return f"TORCH_API std::vector compute_shape_{self.__decl_suffix()}"
+
+ @property
+ def shape_call(self) -> str:
+ return f"torch::lazy::compute_shape_{self.__call_suffix()}"
+
+
+@dataclass(frozen=True)
+class GenLazyShapeInferenceDefinition:
+ backend_index: BackendIndex
+ tensor_class: str
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> list[str]:
+ metadata = self.backend_index.get_kernel(f)
+ assert metadata is not None
+
+ # See Note [Generated LTC Shape Functions]
+ is_view_copy_op = "view_copy" in f.tags
+ is_structured = f.structured or f.structured_delegate is not None
+ if is_structured or is_view_copy_op:
+ return []
+ else:
+ shape_sig = ComputeShapeSignature(
+ metadata.kernel, f, symint=metadata.supports_symint()
+ )
+ return ["\n".join([f"{shape_sig.shape_decl};"])]
+
+
+def generate_non_native_lazy_ir_nodes(
+ non_native: list[dict[str, Any]], gen_lazy_ir: GenLazyIR
+) -> list[str]:
+ """Generate the non-native lazy IR node classes"""
+ nodes = []
+ for op in non_native:
+ # Set default properties for Non-Native IRs
+ properties = LazyIrProperties("ShapeCache", "CanBeReused", "LowerDeclOnly")
+ for p in op.get("properties", []):
+ setattr(properties, p, True)
+
+ # non-native is assumed to want symint bindings if you wrote symint
+ schema = LazyIrSchema(FunctionSchema.parse(op["func"]), properties, symint=True)
+ schema.opkind = op.get("opkind")
+ nodes.append(gen_lazy_ir.gen(schema)[0])
+
+ return nodes
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/lazy_ts_lowering.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/lazy_ts_lowering.py
new file mode 100644
index 0000000000000000000000000000000000000000..1efbd63d7e7722d39c314afdf5474f80a5994c28
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/lazy_ts_lowering.py
@@ -0,0 +1,48 @@
+from torchgen.api.lazy import LazyArgument, LazyIrSchema
+from torchgen.api.types import OptionalCType
+
+
+def ts_lowering_body(schema: LazyIrSchema) -> str:
+ # for now, we just want one IR class decl and soon after also the method defs
+ # and we use the functional version not out/inplace.
+ emplace_arguments = []
+
+ def get_value(arg: LazyArgument) -> str:
+ if isinstance(arg.lazy_type, OptionalCType):
+ return f"has_{arg.name} ? loctx->GetOutputOp(operand(i++)) : nullptr"
+ return "loctx->GetOutputOp(operand(i++))"
+
+ for arg in schema.positional_args:
+ if arg.is_lazy_value:
+ emplace_arguments.append(get_value(arg))
+ continue
+ emplace_arguments.append(f'"{arg.name}", {arg.name}')
+
+ emplace_arguments_str = "\n ".join(
+ [f"arguments.emplace_back({a});" for a in emplace_arguments]
+ )
+ emplace_kwarg_values = [
+ f'"{arg.name}", {get_value(arg)}' for arg in schema.keyword_values
+ ]
+ emplace_kwarg_scalars = [
+ f'"{arg.name}", {arg.name}' for arg in schema.keyword_scalars
+ ]
+ emplace_kwarguments = "\n ".join(
+ [
+ f"kwarguments.emplace_back({a});"
+ for a in emplace_kwarg_values + emplace_kwarg_scalars
+ ]
+ )
+ return f"""\
+ std::vector arguments;
+ std::vector kwarguments;
+ arguments.reserve({len(emplace_arguments)});
+ kwarguments.reserve({len(emplace_kwarg_values + emplace_kwarg_scalars)});
+ size_t i = 0;
+ {emplace_arguments_str}
+ {emplace_kwarguments}
+ torch::lazy::TSOpVector {schema.aten_name}_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments);
+ TORCH_CHECK_EQ({schema.aten_name}_out.size(), {len(schema.returns)});
+
+ return {schema.aten_name}_out;
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/native_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/native_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3527d72e088d37c4cddc44fa7e48c51d0d9816e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/native_functions.py
@@ -0,0 +1,84 @@
+from __future__ import annotations
+
+import torchgen.api.meta as meta
+import torchgen.api.structured as structured
+from torchgen.api.types import kernel_signature
+from torchgen.context import with_native_function_and_index
+from torchgen.model import BackendIndex, NativeFunction, NativeFunctionsGroup
+from torchgen.utils import mapMaybe
+
+
+def torch_api_key_word_prefix(bankend_index: BackendIndex) -> str:
+ if bankend_index.external:
+ return ""
+
+ # Although Intel GPU ATen library is out-of-tree, it still utilizes torchgen to produce structrued
+ # kernels. Regarding these produced structured kernels, they should be visible for the Intel GPU ATen
+ # library. Therefore, we need to add "TORCH_XPU_API" prefix to these structured kernels,
+ # rather than "TORCH_API". Because the semantic of "TORCH_API" is "hidden" for out-of-tree backends.
+ # For other in-tree backends like cpu and cuda, they still use "TORCH_API" prefix with "visible" semantic.
+ device_torch_api_key_word_mapping = {
+ "XPU": "TORCH_XPU_API",
+ }
+
+ return (
+ device_torch_api_key_word_mapping.get(
+ bankend_index.dispatch_key.name, "TORCH_API"
+ )
+ + " "
+ )
+
+
+@with_native_function_and_index
+def gen_unstructured(f: NativeFunction, backend_index: BackendIndex) -> str | None:
+ sig = kernel_signature(f, backend_index)
+ metadata = backend_index.get_kernel(f)
+ if metadata is None:
+ return None
+ if "legacy::" in metadata.kernel:
+ return None
+ else:
+ prefix = "static" if backend_index.external else "TORCH_API"
+ return f"{prefix} {sig.decl(name=metadata.kernel)};"
+
+
+@with_native_function_and_index
+def gen_structured(g: NativeFunctionsGroup, backend_index: BackendIndex) -> list[str]:
+ meta_name = meta.name(g)
+ out_args = structured.impl_arguments(g)
+ metadata = backend_index.get_kernel(g)
+ if metadata is None:
+ return []
+ prefix = torch_api_key_word_prefix(backend_index)
+ return [
+ f"""\
+struct {prefix}structured_{metadata.kernel} : public at::meta::structured_{meta_name} {{
+void impl({', '.join(a.decl() for a in out_args)});
+}};
+"""
+ ]
+
+
+# Generates NativeFunctions.h, a list of forward declarations of all
+# actual kernel definitions we keep in aten/src/ATen/native/
+@with_native_function_and_index
+def compute_native_function_declaration(
+ g: NativeFunctionsGroup | NativeFunction, backend_index: BackendIndex
+) -> list[str]:
+ metadata = backend_index.get_kernel(g)
+ if isinstance(g, NativeFunctionsGroup):
+ if metadata is not None and metadata.structured:
+ if backend_index.external:
+ # Structured hasn't been tested with external backends yet.
+ raise AssertionError(
+ "Structured external backend functions are not implemented yet."
+ )
+ else:
+ return gen_structured(g, backend_index)
+ else:
+ return list(
+ mapMaybe(lambda f: gen_unstructured(f, backend_index), g.functions())
+ )
+ else:
+ x = gen_unstructured(g, backend_index)
+ return [] if x is None else [x]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/register_dispatch_key.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/register_dispatch_key.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9dd0b205004e97049449878e648e8a60281077c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/register_dispatch_key.py
@@ -0,0 +1,1006 @@
+from __future__ import annotations
+
+import itertools
+import textwrap
+from dataclasses import dataclass
+from typing import Literal, TYPE_CHECKING
+
+import torchgen.api.cpp as cpp
+import torchgen.api.meta as meta
+import torchgen.api.structured as structured
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+ BaseCType,
+ Binding,
+ ConstRefCType,
+ CppSignature,
+ CppSignatureGroup,
+ DispatcherSignature,
+ Expr,
+ kernel_signature,
+ MutRefCType,
+ NamedCType,
+ NativeSignature,
+ tensorT,
+)
+from torchgen.context import method_with_native_function, native_function_manager
+from torchgen.model import (
+ Argument,
+ BackendIndex,
+ DeviceCheckType,
+ DispatchKey,
+ gets_generated_out_inplace_wrapper,
+ is_cuda_dispatch_key,
+ NativeFunction,
+ NativeFunctionsGroup,
+ SchemaKind,
+ TensorOptionsArguments,
+)
+from torchgen.utils import assert_never, mapMaybe, Target
+
+
+if TYPE_CHECKING:
+ from torchgen.selective_build.selector import SelectiveBuilder
+
+
+def gen_registration_headers(
+ backend_index: BackendIndex,
+ per_operator_headers: bool,
+ rocm: bool,
+) -> list[str]:
+ if per_operator_headers:
+ headers = ["#include "]
+ else:
+ headers = ["#include "]
+
+ if backend_index.dispatch_key in (DispatchKey.CPU, DispatchKey.Meta):
+ headers.append("#include ")
+ elif backend_index.dispatch_key == DispatchKey.CUDA:
+ if rocm:
+ headers.append("#include ")
+ else:
+ headers.append("#include ")
+ elif backend_index.dispatch_key == DispatchKey.MPS:
+ headers.append("#include ")
+ elif backend_index.dispatch_key == DispatchKey.XPU:
+ # XPU specific, this header resides in third_party/torch-xpu-ops
+ headers.append("#include ")
+ elif per_operator_headers:
+ headers += [
+ "#include ",
+ "#include ",
+ "#include ",
+ "#include ",
+ ]
+ else:
+ headers.append("#include ")
+
+ headers.append("#include ")
+ return headers
+
+
+def gen_empty_impl_names(
+ backend_index: BackendIndex,
+) -> tuple[str | None, str | None]:
+ empty_impl = None
+ empty_strided_impl = None
+
+ if backend_index.dispatch_key in (
+ DispatchKey.Meta,
+ DispatchKey.CPU,
+ DispatchKey.CUDA,
+ DispatchKey.MPS,
+ DispatchKey.XPU,
+ ):
+ dispatch = str(backend_index.dispatch_key).lower()
+ empty_impl = f"at::detail::empty_{dispatch}"
+ empty_strided_impl = f"at::detail::empty_strided_{dispatch}"
+ elif backend_index.dispatch_key in (
+ DispatchKey.CompositeExplicitAutogradNonFunctional,
+ DispatchKey.QuantizedCPU,
+ DispatchKey.QuantizedCUDA,
+ DispatchKey.XPU,
+ ):
+ empty_impl = "at::empty"
+ empty_strided_impl = "at::empty_strided"
+
+ return empty_impl, empty_strided_impl
+
+
+def gen_create_out_helper(backend_index: BackendIndex) -> list[str]:
+ if backend_index.dispatch_key == DispatchKey.Meta:
+ empty_options = "options.device(at::kMeta)"
+ else:
+ empty_options = "options"
+
+ empty_impl, empty_strided_impl = gen_empty_impl_names(backend_index)
+ if empty_impl is None:
+ return []
+
+ return [
+ f"""
+Tensor create_out(IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{
+ if (strides.empty()) {{
+ return {empty_impl}(sizes, {empty_options});
+ }} else {{
+ return {empty_strided_impl}(sizes, strides, {empty_options});
+ }}
+}}
+"""
+ ]
+
+
+def gen_maybe_create_proxy_helper(backend_index: BackendIndex) -> list[str]:
+ _, empty_strided_impl = gen_empty_impl_names(backend_index)
+ return (
+ []
+ if empty_strided_impl is None
+ else [
+ f"""
+std::optional maybe_create_proxy(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{
+ if (out.strides() != strides) {{
+ return {empty_strided_impl}(sizes, strides, options);
+ }}
+ return std::nullopt;
+}}
+"""
+ ]
+ )
+
+
+def gen_resize_out_helper(backend_index: BackendIndex) -> list[str]:
+ if backend_index.dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional:
+ # The function isn't used by this key (since only functional ops have a kernel for this key),
+ # so we need to not include it to avoid a defined-but-not-used error.
+ return []
+ return [
+ """
+void resize_out(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {
+ TORCH_CHECK(options.dtype() == out.dtype(),
+ "Expected out tensor to have dtype ", options.dtype(), ", but got ", out.dtype(), " instead");
+ TORCH_CHECK(options.device() == out.device(),
+ "Expected out tensor to have device ", options.device(), ", but got ", out.device(), " instead");
+ const bool resized = at::native::resize_output(out, sizes);
+ // Only restride if a resize occurred; otherwise we ignore the (advisory)
+ // strides from the meta function and directly use the output tensor's
+ // preexisting strides
+ if (resized) {
+ if (!strides.empty()) {
+ TORCH_INTERNAL_ASSERT(!options.memory_format_opt().has_value());
+ // TODO: avoid the redispatch here
+ out.as_strided_(sizes, strides);
+ } else if (options.memory_format_opt().has_value()) {
+ out.unsafeGetTensorImpl()->empty_tensor_restride(*options.memory_format_opt());
+ }
+ }
+}
+"""
+ ]
+
+
+def gen_check_inplace_helper(backend_index: BackendIndex) -> list[str]:
+ return [
+ """
+void check_inplace(const Tensor &self, IntArrayRef sizes, const TensorOptions &options) {
+ // These checks are needed on those operators that:
+ // 1) don't use 'TensorIterator' (e.g. 'addmm' and 'baddbmm')
+ // 2) have particular typing rules (e.g. 'cumsum' and 'cumprod')
+ // For other operators (e.g. 'add'), 'TensorIterator' already checks
+ // these things separately.
+ TORCH_CHECK(options.dtype() == self.dtype(),
+ "Bad in-place call: ",
+ "input tensor dtype ", self.dtype(), " and output tensor dtype ", options.dtype(), " should match");
+ TORCH_CHECK(options.device() == self.device(),
+ "Bad in-place call: ",
+ "input tensor device ", self.device(), " and output tensor device ", options.device(), " should match");
+ TORCH_CHECK(sizes == self.sizes(),
+ "Bad in-place call: ",
+ "input tensor size ", self.sizes(), " and output tensor size ", sizes, " should match");
+}
+"""
+ ]
+
+
+def gen_registration_helpers(backend_index: BackendIndex) -> list[str]:
+ return [
+ 'C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-function")',
+ *gen_create_out_helper(backend_index),
+ *gen_resize_out_helper(backend_index),
+ *gen_check_inplace_helper(backend_index),
+ *gen_maybe_create_proxy_helper(backend_index),
+ "C10_DIAGNOSTIC_POP()",
+ ]
+
+
+# Generates Register{dispatch}.cpp (e.g., RegisterCPU.cpp).
+#
+# - The primary function of this file is to register all of the
+# implementations for the given dispatch key to the dispatcher,
+# so they are available for use in PyTorch. If dispatch is
+# None, we generate schema (def) registrations and catchall
+# registrations.
+# - The secondary function of this file is to generate a wrapper
+# around functions. In CPUType these wrappers do nothing
+# (and should be removed), but in other cases they handle
+# DeviceGuard. A small extra benefit of wrappers is they
+# are not overloaded, so they can be used in the registration
+# API without having to disambiguate which overload you want
+# (as would be the case if you directly registered native::
+# functions).
+# - The tertiary function of this file is to generate *static*
+# cpp API bindings which can be used to bypass dispatcher
+# directly to kernels, but with user-friendly cpp-style API
+@dataclass(frozen=True)
+class RegisterDispatchKey:
+ backend_index: BackendIndex
+
+ target: Literal[
+ Target.ANONYMOUS_DEFINITION,
+ Target.NAMESPACED_DEFINITION,
+ Target.NAMESPACED_DECLARATION,
+ Target.REGISTRATION,
+ ]
+
+ # Selector object to determine which operators to generate
+ # registration code for.
+ selector: SelectiveBuilder
+
+ # Whether or not we are actually code-genning for ROCm
+ rocm: bool
+
+ # Whether or not to generate symint registrations or not. External users
+ # of codegen who don't care about symints can set this to false to get
+ # non-SymInt codegen
+ symint: bool
+
+ # The class that all unstructured native functions live under. This is used to improve
+ # compiler error messages when a kernel writer adds a native function with the wrong signature.
+ # This is only used in unstructured kernels, since structured kernels already live in a class.
+ # Finally, this field is currently Optional because it is only used by external backends.
+ # It would be nice if we can add the same logic to in-tree kernels too, but that requires updating
+ # all of the existing kernel signatures scattered across aten/src/ATen/native.
+ class_method_name: str | None
+
+ # Only set to true in lightweight dispatch. If lightweight dispatch is enabled we are registering
+ # operators into JIT op registry, thus we need to avoid generating code to register into the dispatcher.
+ skip_dispatcher_op_registration: bool
+
+ @staticmethod
+ def gen_device_check(
+ type: DeviceCheckType, args: list[Argument], method_name: str
+ ) -> str:
+ if type == DeviceCheckType.NoCheck:
+ return " // No device check\n"
+
+ device_check = "std::optional common_device = std::nullopt;\n"
+ device_check += "(void)common_device; // Suppress unused variable warning\n"
+ for arg in args:
+ # Only tensor like arguments are eligible
+ if arg.type.is_tensor_like():
+ device_check += f"""
+ c10::impl::check_and_update_common_device(common_device, {arg.name}, "{method_name}", "{arg.name}");"""
+ return device_check
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]:
+ if isinstance(f, NativeFunctionsGroup):
+ g: NativeFunctionsGroup = f
+ # Note: We call gen_structured() if the operator is marked structured, regardless of the backend.
+ # gen_structured() has special logic to handle auto-generated kernels.
+ if g.structured:
+ return self.gen_structured(g)
+ else:
+ return list(
+ mapMaybe(lambda f: self.gen_unstructured(f, g), g.functions())
+ )
+ elif isinstance(f, NativeFunction):
+ r = self.gen_unstructured(f)
+ return [] if r is None else [r]
+ else:
+ assert_never(f)
+
+ def wrapper_kernel_sig(
+ self, f: NativeFunction
+ ) -> NativeSignature | DispatcherSignature:
+ # The prefix is just to ensure uniqueness. The Dispatcher API doesn't guarantee unique kernel names.
+ return DispatcherSignature.from_schema(
+ f.func,
+ prefix=f"wrapper_{self.backend_index.dispatch_key}_{f.func.name.overload_name}_",
+ symint=self.symint,
+ )
+
+ def gen_out_inplace_wrapper(
+ self, f: NativeFunction, g: NativeFunctionsGroup | None
+ ) -> str | None:
+ if g is None:
+ return None
+ k = f.func.kind()
+ if k is SchemaKind.inplace:
+ copy_op = "at::_copy_from"
+ elif k is SchemaKind.out:
+ copy_op = "at::_copy_from_and_resize"
+ else:
+ raise AssertionError("gen_out_inplace_wrapper called on a functional op")
+
+ sig = self.wrapper_kernel_sig(f)
+ name = sig.name()
+
+ func_res = f"{name}_tmp"
+ return_names = cpp.return_names(f)
+ if len(return_names) > 1:
+ updates = "\n ".join(
+ f"{copy_op}(std::get<{i}>({func_res}), {ret_name});"
+ for i, ret_name in enumerate(return_names)
+ )
+ returns = f'{sig.returns_type().cpp_type()}({", ".join(return_names)})'
+ elif len(return_names) == 1:
+ ret_name = return_names[0]
+ updates = f"{copy_op}({func_res}, {ret_name});"
+ returns = ret_name
+ else:
+ assert len(f.func.arguments.out) == 1
+ returns = ""
+ out_arg = f.func.arguments.out[0]
+ if out_arg.type.is_list_like():
+ updates = f"""\
+ for (int64_t i = 0; i < {func_res}.size(); ++i) {{
+ {copy_op}({func_res}[i], {out_arg.name}[i]);
+ }}"""
+ else:
+ updates = f"{copy_op}({func_res}, {out_arg.name});"
+
+ functional_sig = self.wrapper_kernel_sig(g.functional)
+ wrapper_name = sig.name()
+
+ return f"""\
+{sig.defn(name=wrapper_name)} {{
+ auto {func_res} = {functional_sig.name()}({", ".join(e.expr for e in translate(sig.arguments(), functional_sig.arguments()))});
+ {updates}
+ return {returns};
+}}
+"""
+
+ def gen_structured(self, g: NativeFunctionsGroup) -> list[str]:
+ metadata = self.backend_index.get_kernel(g)
+ if self.backend_index.dispatch_key == DispatchKey.Meta:
+ assert not self.backend_index.has_kernel(g.out), (
+ "Do not explicitly specify Meta dispatch key on structured "
+ "functions, they will be automatically generated for you"
+ )
+ elif (
+ self.backend_index.dispatch_key
+ == DispatchKey.CompositeExplicitAutogradNonFunctional
+ ):
+ assert not self.backend_index.has_kernel(g.out), (
+ "Do not explicitly specify CompositeExplicitAutograd dispatch key on structured "
+ "functions, they will be automatically generated for you"
+ )
+ elif metadata is None or not metadata.structured:
+ return list(mapMaybe(lambda f: self.gen_unstructured(f, g), g.functions()))
+ structured_gen = StructuredRegisterDispatchKey(
+ self.backend_index,
+ self.target,
+ self.selector,
+ self.rocm,
+ self.symint,
+ self.class_method_name,
+ self.skip_dispatcher_op_registration,
+ g,
+ )
+ return list(mapMaybe(structured_gen.gen_one, g.functions()))
+
+ def gen_unstructured(
+ self, f: NativeFunction, g: NativeFunctionsGroup | None = None
+ ) -> str | None:
+ with native_function_manager(f):
+ inplace_meta = False
+ gets_out_inplace_wrapper = False
+ if not self.backend_index.has_kernel(f):
+ if (
+ self.backend_index.dispatch_key == DispatchKey.Meta
+ and f.func.kind() is SchemaKind.inplace
+ and
+ # Defer to composites for meta implementation
+ not f.has_composite_kernel
+ and
+ # Inplace list operations are not supported
+ len(f.func.returns) == 1
+ ):
+ inplace_meta = True
+ elif (
+ not self.backend_index.use_out_as_primary
+ and g is not None
+ and gets_generated_out_inplace_wrapper(f, g, self.backend_index)
+ ):
+ # We want to generate inplace/out wrappers, that don't have a kernel for the backend.
+ gets_out_inplace_wrapper = True
+ else:
+ return None
+ if f.manual_kernel_registration:
+ return None
+
+ if (
+ self.target is Target.REGISTRATION
+ and not self.selector.is_native_function_selected(f)
+ ):
+ return None
+
+ sig = self.wrapper_kernel_sig(f)
+
+ name = sig.name()
+ returns_type = sig.returns_type().cpp_type()
+ args = sig.arguments()
+ args_str = ", ".join(a.defn() for a in args)
+
+ # See Note [Direct dispatch bindings]
+ cpp_sig_group = CppSignatureGroup.from_native_function(
+ f, method=False, fallback_binding=False
+ )
+
+ # TODO: dedupe this with the structured codegen
+ if self.target is Target.NAMESPACED_DECLARATION:
+ result = ""
+ for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+ result += f"TORCH_API {cpp_sig.decl()};\n"
+ return result
+ elif self.target is Target.NAMESPACED_DEFINITION:
+
+ def generate_defn(cpp_sig: CppSignature) -> str:
+ return f"""
+{cpp_sig.defn()} {{
+return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))});
+}}
+"""
+
+ result = ""
+ for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+ result += generate_defn(cpp_sig)
+ return result
+
+ elif self.target is Target.ANONYMOUS_DEFINITION:
+ # short circuit for inplace_meta
+ if inplace_meta:
+ assert f.func.arguments.self_arg is not None
+ self_arg_name = f.func.arguments.self_arg.argument.name
+ # TODO: handle in place on tensor list
+ return f"""
+{returns_type} {name}({args_str}) {{
+ TORCH_CHECK_NOT_IMPLEMENTED({self_arg_name}.is_meta(),
+ "Cannot inplace into non-meta tensor with meta tensor argument");
+ return {self_arg_name};
+}}
+"""
+
+ # short circuit for generated inplace/out wrappers
+ if gets_out_inplace_wrapper:
+ return self.gen_out_inplace_wrapper(f, g)
+
+ metadata = self.backend_index.get_kernel(f)
+ if metadata is None:
+ return None
+ if self.class_method_name is None:
+ impl_name = f"{metadata.cpp_namespace}::{metadata.kernel}"
+ else:
+ impl_name = f"{metadata.cpp_namespace}::{self.class_method_name}::{metadata.kernel}"
+
+ kernel_sig = kernel_signature(f, self.backend_index)
+
+ args_exprs_str = ", ".join(
+ e.expr
+ for e in translate(
+ sig.arguments(), kernel_sig.arguments(), method=False
+ )
+ )
+
+ device_check = " // No device check\n"
+ # Backends that require device guards presumably also require device checks.
+ if self.backend_index.device_guard:
+ device_check_args = itertools.chain(
+ f.func.arguments.out, f.func.arguments.flat_positional
+ )
+ device_check = RegisterDispatchKey.gen_device_check(
+ f.device_check, list(device_check_args), name
+ )
+
+ device_guard = "// DeviceGuard omitted" # default
+ if f.device_guard and self.backend_index.device_guard:
+ has_tensor_options = any(
+ isinstance(a, TensorOptionsArguments)
+ for a in f.func.arguments.non_out
+ )
+ if has_tensor_options:
+ # kernel is creating a tensor
+ device_guard = """
+ const DeviceGuard device_guard(device_or_default(device));"""
+
+ # CUDA requires special handling
+ if is_cuda_dispatch_key(self.backend_index.dispatch_key):
+ device_guard = f"globalContext().lazyInitDevice(c10::DeviceType::CUDA);\n{device_guard}"
+ else:
+ # kernel is operating on existing tensors
+
+ # There is precedence for which argument we use to do
+ # device guard. This describes the precedence order.
+ self_arg = (
+ [f.func.arguments.self_arg.argument]
+ if f.func.arguments.self_arg is not None
+ else []
+ )
+ candidate_args = itertools.chain(
+ self_arg,
+ f.func.arguments.out,
+ f.func.arguments.flat_positional,
+ )
+
+ # Only tensor like arguments are eligible
+ device_of = next(
+ (
+ f"{a.name}"
+ for a in candidate_args
+ if a.type.is_tensor_like()
+ ),
+ None,
+ )
+ if device_of is not None:
+ device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));"
+
+ return f"""\
+namespace {{
+
+{returns_type} {name}({args_str}) {{
+ {device_check}
+
+ {device_guard}
+ return {impl_name}({args_exprs_str});
+}}
+
+}} // anonymous namespace
+"""
+
+ elif self.target is Target.REGISTRATION:
+ if f.manual_kernel_registration or self.skip_dispatcher_op_registration:
+ return None
+ else:
+ payload = f"TORCH_FN({name})"
+ return f'm.impl("{f.func.name}",\n{payload});\n'
+ else:
+ assert_never(self.target)
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# STRUCTURED
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+@dataclass(frozen=True)
+class StructuredRegisterDispatchKey(RegisterDispatchKey):
+ g: NativeFunctionsGroup
+
+ def gen_class_set_output_functions(
+ self, k: SchemaKind, parent_class: str, generate_super: bool
+ ) -> str:
+ if generate_super:
+ set_output_super = f"{parent_class}::set_output_raw_strided(output_idx, sizes, strides, options, names);"
+ else:
+ set_output_super = ""
+
+ def gen_set_output_function(name: str, maybe_create_proxy: bool) -> str:
+ return f"""
+void set_output_{name}(
+ int64_t output_idx, IntArrayRef sizes, IntArrayRef strides,
+ TensorOptions options, DimnameList names
+) override {{
+{textwrap.indent(self.gen_class_set_output_body(k, maybe_create_proxy), " ")}
+ if (!names.empty()) {{
+ namedinference::propagate_names(outputs_[output_idx], names);
+ }}
+ // super must happen after, so that downstream can use maybe_get_output
+ // to retrieve the output
+{textwrap.indent(set_output_super, " ")}
+}}
+"""
+
+ return f"""
+{gen_set_output_function("strided", maybe_create_proxy=True)}
+{gen_set_output_function("raw_strided", maybe_create_proxy=False)}
+"""
+
+ def gen_class_set_output_body(self, k: SchemaKind, maybe_create_proxy: bool) -> str:
+ if self.backend_index.dispatch_key in [
+ DispatchKey.CUDA,
+ DispatchKey.MPS,
+ DispatchKey.XPU,
+ DispatchKey.CompositeExplicitAutogradNonFunctional,
+ ]:
+ maybe_set_guard = """
+auto current_device = guard_.current_device();
+if (C10_UNLIKELY(current_device.has_value())) {
+ TORCH_INTERNAL_ASSERT(*current_device == options.device(),
+ "structured kernels don't support multi-device outputs");
+} else {
+ guard_.reset_device(options.device());
+}
+"""
+ maybe_set_guard_line = maybe_set_guard + "\n"
+ else:
+ maybe_set_guard_line = maybe_set_guard = ""
+
+ if maybe_create_proxy:
+ create_proxy = """
+auto maybe_proxy = maybe_create_proxy(out, sizes, strides, options);
+if (C10_UNLIKELY(maybe_proxy.has_value())) {
+ proxy_outputs_[output_idx] = std::move(maybe_proxy).value();
+}
+"""
+ else:
+ create_proxy = ""
+
+ if k is SchemaKind.functional:
+ assert self.backend_index.dispatch_key in (
+ DispatchKey.Meta,
+ DispatchKey.CPU,
+ DispatchKey.CUDA,
+ DispatchKey.MPS,
+ DispatchKey.XPU,
+ DispatchKey.CompositeExplicitAutogradNonFunctional,
+ )
+ return f"""{maybe_set_guard_line}
+outputs_[output_idx] = create_out(sizes, strides, options);"""
+ elif k is SchemaKind.inplace:
+ return f"""{maybe_set_guard_line}
+const auto& out = outputs_[output_idx].get();
+check_inplace(out, sizes, options);
+{create_proxy}"""
+ elif k is SchemaKind.out:
+ return f"""{maybe_set_guard_line}
+const auto& out = outputs_[output_idx].get();
+resize_out(out, sizes, strides, options);
+{create_proxy}"""
+ elif k is SchemaKind.mutable or k is SchemaKind.scratch:
+ raise AssertionError(
+ f"{k} structured operators are currently not supported"
+ )
+ else:
+ assert_never(k)
+
+ # returns the definition of a ctor, as well as how to construct
+ # this class to a variable named op
+ def gen_class_ctor(self, k: SchemaKind, class_name: str, returns: int) -> str:
+ if k is SchemaKind.functional:
+ return ""
+ elif k is SchemaKind.inplace:
+ # TODO: Make sure out argument is guaranteed to be self
+ return f"{class_name}(Tensor& self) : outputs_{{std::ref(self)}} {{}}"
+ elif k is SchemaKind.out:
+ out_args = ", ".join(f"Tensor& out{i}" for i in range(returns))
+ out_refs = ", ".join(f"std::ref(out{i})" for i in range(returns))
+ return f"{class_name}({out_args}) : outputs_{{ {out_refs} }} {{}}"
+ elif k is SchemaKind.mutable or k is SchemaKind.scratch:
+ raise AssertionError(
+ f"{k} structured operators are currently not supported"
+ )
+ else:
+ assert_never(k)
+
+ def gen_class(
+ self,
+ f: NativeFunction,
+ k: SchemaKind,
+ *,
+ class_name: str,
+ parent_class: str,
+ generate_super: bool,
+ ) -> str:
+ if k is SchemaKind.functional:
+ output_type = "Tensor"
+ output_value = "outputs_[output_idx]"
+ proxy_field = ""
+ elif k is SchemaKind.inplace:
+ output_type = "std::reference_wrapper"
+ output_value = "proxy_outputs_[output_idx].has_value() ? *proxy_outputs_[output_idx] : outputs_[output_idx].get()"
+ proxy_field = f"std::array<::std::optional, {len(f.func.returns)}> proxy_outputs_;"
+ elif k is SchemaKind.out:
+ output_type = "std::reference_wrapper"
+ output_value = "proxy_outputs_[output_idx].has_value() ? *proxy_outputs_[output_idx] : outputs_[output_idx].get()"
+ proxy_field = f"std::array<::std::optional, {len(f.func.returns)}> proxy_outputs_;"
+ else:
+ raise RuntimeError(f"Unsupported SchemaKind {k}")
+
+ if self.backend_index.dispatch_key == DispatchKey.CUDA:
+ if self.rocm:
+ guard_field = "c10::hip::OptionalHIPGuardMasqueradingAsCUDA guard_;"
+ else:
+ guard_field = "c10::cuda::OptionalCUDAGuard guard_;"
+ elif (
+ self.backend_index.dispatch_key
+ == DispatchKey.CompositeExplicitAutogradNonFunctional
+ ):
+ guard_field = "c10::OptionalDeviceGuard guard_;"
+ elif self.backend_index.dispatch_key == DispatchKey.MPS:
+ # TODO: Move to OptionalMPSGuard.
+ guard_field = "c10::OptionalDeviceGuard guard_;"
+ elif self.backend_index.dispatch_key == DispatchKey.XPU:
+ guard_field = "c10::OptionalDeviceGuard guard_;"
+ else:
+ guard_field = ""
+
+ indent = " " * 4
+ class_ctor_str = self.gen_class_ctor(k, class_name, len(f.func.returns))
+ lines = (
+ f"struct {class_name} final : public {parent_class} {{",
+ f"{textwrap.indent(class_ctor_str, indent)}",
+ f"{textwrap.indent(self.gen_class_set_output_functions(k, parent_class, generate_super), indent)}",
+ " const Tensor& maybe_get_output(int64_t output_idx) override {",
+ f" return {output_value};\n", # type: ignore[possibly-undefined] # TODO: audit
+ " }",
+ # type: ignore[possibly-undefined] # TODO: audit
+ f" std::array<{output_type}, {len(f.func.returns)}> outputs_;",
+ f"{textwrap.indent(proxy_field, indent)}", # type: ignore[possibly-undefined] # TODO: audit
+ f"{textwrap.indent(guard_field, indent)}",
+ "};",
+ )
+ return "\n".join(line for line in lines if line)
+
+ @method_with_native_function
+ def gen_one(self, f: NativeFunction) -> str | None:
+ assert not f.manual_kernel_registration
+
+ if (
+ self.target is Target.REGISTRATION
+ and not self.selector.is_native_function_selected(f)
+ ):
+ return None
+
+ # TODO: Now, there is something interesting going on here. In the code below,
+ # we generate CompositeExplicitAutogradNonFunctional implementations of functional and inplace
+ # based on the out implementation. But in fact, out is definable by
+ # functional too (just not very efficiently), and this is honestly the
+ # MORE likely situation for a backend implementor. How do we pick?
+ # Well, taking a page from Haskell type classes and default methods,
+ # we could conceivably register a circular definition (out in terms
+ # of functional, and functional in terms of out) and just require
+ # someone to implement one or the other. We'd have to do a little bit
+ # of work to not register one of these "weak" definitions unless there
+ # is a strong definition somewhere in the DAG! So it's not implemented yet.
+ if (
+ self.backend_index.dispatch_key
+ == DispatchKey.CompositeExplicitAutogradNonFunctional
+ and f.func.kind() is SchemaKind.out
+ ):
+ # Never generate a default implementation for out, that's what you
+ # have to define as a backend implementor
+ return None
+
+ # Note [Direct dispatch bindings]
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ # Signature of the non-dispatched function we'll expose in a header
+ # (e.g., at::cpu::add). We don't generate methods (TODO: do this
+ # when CPUTensor class is a thing); nor do we generate fallback
+ # bindings for manual_cpp_binding functions.
+ cpp_sig_group = CppSignatureGroup.from_native_function(
+ f, method=False, fallback_binding=False
+ )
+
+ # Signature of the wrapper function we'll register to the dispatcher
+ kern = self.backend_index.get_kernel(f)
+ sig = NativeSignature(
+ f.func,
+ prefix=f"wrapper_{self.backend_index.dispatch_key}_",
+ symint=kern is not None and kern.supports_symint(),
+ )
+
+ if self.target is Target.NAMESPACED_DECLARATION:
+ result = ""
+ for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+ result += f"TORCH_API {cpp_sig.decl()};\n"
+ return result
+
+ elif self.target is Target.NAMESPACED_DEFINITION:
+
+ def generate_defn(cpp_sig: CppSignature) -> str:
+ return f"""
+{cpp_sig.defn()} {{
+return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))});
+}}
+"""
+
+ result = ""
+ for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
+ result += generate_defn(cpp_sig)
+ return result
+
+ elif self.target is Target.ANONYMOUS_DEFINITION:
+ k = f.func.kind()
+
+ # Construct the body of the wrapper function with signature sig
+ sig_body = []
+ # We'll use context to keep track of any variables we've brought
+ # into scope while generating code
+ context: list[Binding | Expr] = list(sig.arguments())
+
+ # Initialize the class corresponding to this structured
+ # operator; feeding it the output argument(s) if it is known
+ if self.backend_index.dispatch_key is DispatchKey.Meta:
+ class_name = f"structured_{meta.name(self.g)}_meta_{k.name}"
+ parent_class = f"at::meta::structured_{meta.name(self.g)}"
+ elif (
+ self.backend_index.dispatch_key
+ is DispatchKey.CompositeExplicitAutogradNonFunctional
+ ):
+ # TODO: dedup this branch
+ class_name = f"structured_{meta.name(self.g)}_default_backend_{k.name}"
+ parent_class = f"at::meta::structured_{meta.name(self.g)}"
+ else:
+ metadata = self.backend_index.get_kernel(self.g)
+ assert metadata is not None
+ class_name = f"structured_{metadata.kernel}_{k.name}"
+ parent_class = f"{metadata.cpp_namespace}::structured_{metadata.kernel}"
+
+ if self.backend_index.device_guard:
+ device_check_args = itertools.chain(
+ f.func.arguments.out, f.func.arguments.flat_positional
+ )
+ sig_body.append(
+ RegisterDispatchKey.gen_device_check(
+ f.device_check, list(device_check_args), sig.name()
+ )
+ )
+
+ if k is SchemaKind.functional:
+ sig_body.append(f"{class_name} op;")
+ elif k is SchemaKind.inplace:
+ sig_body.append(f"{class_name} op(self);")
+ elif k is SchemaKind.out:
+ out_args_str = ", ".join(a.name for a in f.func.arguments.out)
+ sig_body.append(f"{class_name} op({out_args_str});")
+
+ # Translate the input native arguments into structured
+ # arguments for the meta call
+ meta_exprs = ", ".join(
+ e.expr
+ for e in translate(
+ context, structured.meta_arguments(self.g), method=False
+ )
+ )
+
+ if self.g.out.precomputed:
+ # If this function group has precomputed elements, the meta function
+ # returns a struct containing them which must be saved so that it
+ # can be unpacked when generating code to call the impl.
+ sig_body.append(f"auto precompute = op.meta({meta_exprs});")
+
+ # Put all of the contents of the precompute struct into the context
+ # so that translate will be able to return the correct args for the
+ # call to the impl.
+ precomputed_values = [
+ *self.g.out.precomputed.replace.values(),
+ self.g.out.precomputed.add,
+ ]
+ for precomputed_elems in precomputed_values:
+ context.extend(
+ Expr(
+ expr=f"precompute.{arg.name}",
+ type=structured.argument_type(arg, binds=arg.name),
+ )
+ for arg in precomputed_elems
+ )
+
+ # Add a use of the precompute struct so FB internal compilers don't
+ # complain that there is an unused variable.
+ sig_body.append("(void)precompute;")
+ else:
+ sig_body.append(f"op.meta({meta_exprs});")
+
+ # After running meta, op.outputs_ is guaranteed to be valid;
+ # add it to the context
+ out_args = structured.out_arguments(self.g)
+ for i, out_arg in enumerate(out_args):
+ assert ConstRefCType(BaseCType(tensorT)) == out_arg.nctype.type
+
+ if k is SchemaKind.out:
+ expr = f"op.maybe_get_output({i})"
+ else:
+ expr = f"op.outputs_[{i}]"
+
+ context.append(
+ Expr(
+ expr=expr,
+ # TODO: Stop hardcoding that the output type is a Tensor. Note
+ # that for the codegen here this is fine because outputs_ is
+ # hardcoded to be tensor already
+ type=NamedCType(
+ out_arg.nctype.name, MutRefCType(BaseCType(tensorT))
+ ),
+ )
+ )
+
+ # With the expanded context, do the impl call (if not a meta
+ # function)
+ if (
+ self.backend_index.dispatch_key
+ == DispatchKey.CompositeExplicitAutogradNonFunctional
+ ):
+ # TODO: https://github.com/pytorch/pytorch/issues/53023
+ out_sig_group = CppSignatureGroup.from_native_function(
+ self.g.out, method=False, fallback_binding=f.manual_cpp_binding
+ )
+ out_sig = out_sig_group.most_faithful_signature()
+ api_name = out_sig.name()
+ out_exprs = ", ".join(
+ e.expr
+ for e in translate(context, out_sig.arguments(), method=False)
+ )
+ # TODO: I think this means structured won't work with method
+ # only functions (but maybe you're saved by faithful? iunno.)
+ # NB: Originally I wrote this as an at::redispatch call, but
+ # I got in trouble because that meant I needed a DispatchKeySet
+ # in the wrapper function, which meant I needed a DispatchKeySet
+ # in the DispatchKeyFunctions declarations, but the defined API
+ # there does NOT permit a dispatch key set. I think you can
+ # probably unwind this by calling some function to do the TLS
+ # fetch and get the DispatchKeySet when you don't have it, but
+ # I didn't do it for this version
+ sig_body.append(f"at::{api_name}({out_exprs});")
+ elif self.backend_index.dispatch_key != DispatchKey.Meta:
+ impl_exprs = ", ".join(
+ e.expr
+ for e in translate(
+ context, structured.impl_arguments(self.g), method=False
+ )
+ )
+ sig_body.append(f"op.impl({impl_exprs});")
+
+ # Go over each output, and check if there is a proxy created for it.
+ # If so, copy it over to the original output.
+ if k is SchemaKind.out or k is SchemaKind.inplace:
+ for i in range(len(f.func.returns)):
+ sig_body.append(
+ f"if (op.proxy_outputs_[{i}].has_value()) op.outputs_[{i}].get().copy_(*op.proxy_outputs_[{i}]);"
+ )
+
+ # Destructively return the final tensors
+ # TODO: Do this in translate instead
+ if k is SchemaKind.functional:
+ if len(f.func.returns) == 1:
+ ret_expr = "std::move(op.outputs_[0])" # small optimization
+ else:
+ moved = ", ".join(
+ f"std::move(op.outputs_[{i}])"
+ for i in range(len(f.func.returns))
+ )
+ ret_expr = f"std::make_tuple({moved})"
+ elif k is SchemaKind.inplace:
+ ret_expr = "self"
+ elif k is SchemaKind.out:
+ if len(f.func.returns) == 1:
+ ret_expr = f.func.arguments.out[0].name
+ else:
+ refs = ", ".join(a.name for a in f.func.arguments.out)
+ ret_expr = f"std::forward_as_tuple({refs})"
+ sig_body.append(f"return {ret_expr};") # type: ignore[possibly-undefined] # TODO: audit
+
+ sig_body_str = "\n".join(sig_body)
+
+ # For an overview of what this template code looks like, see
+ # https://github.com/pytorch/rfcs/pull/9
+ return f"""\
+{self.gen_class(
+f, k,
+class_name=class_name,
+parent_class=parent_class,
+generate_super=self.g.out.structured_inherits is not None
+)}
+
+{sig.defn()} {{
+{sig_body_str}
+}}
+"""
+
+ elif self.target is Target.REGISTRATION:
+ return f'm.impl("{f.func.name}", TORCH_FN({sig.name()}));'
+ else:
+ assert_never(self.target)
+ # Silence mypy's "Missing return statement" error
+ return None
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/ufunc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/ufunc.py
new file mode 100644
index 0000000000000000000000000000000000000000..598bc8236c799ad4975ed3c21f5658085f2bb4e4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/dest/ufunc.py
@@ -0,0 +1,553 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+import torchgen.api.ufunc as ufunc
+from torchgen.api.translate import translate
+from torchgen.api.types import (
+ BaseCType,
+ Binding,
+ CType,
+ Expr,
+ NamedCType,
+ opmath_t,
+ scalar_t,
+ StructuredImplSignature,
+ VectorizedCType,
+)
+from torchgen.context import with_native_function
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ DispatchKey,
+ NativeFunctionsGroup,
+ ScalarType,
+ UfuncKey,
+)
+from torchgen.utils import OrderedSet
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from torchgen.api.ufunc import UfunctorBindings
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# CUDA STUFF
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+# NB: not bothering to generate dispatch stub forward declaration in header,
+# we can just paste it whereever necessary
+
+# TODO: use BackendIndex
+# dispatch_key: DispatchKey # only CPU/CUDA right now
+
+
+# Represents functors for implementing CUDA ufuncs.
+# Functors are templated by scalar_t because when USERS instantiate functors
+# they are templated. A functor looks something like this:
+#
+# template
+# struct CUDAFunctorOnSelf_add {
+# using opmath_t = at::opmath_type;
+# opmath_t other_;
+# opmath_t alpha_;
+# CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha)
+# : other_(other), alpha_(alpha) {}
+# __device__ scalar_t operator()(scalar_t self) {
+# return ufunc::add(static_cast(self), other_, alpha_);
+# }
+# };
+#
+@dataclass(frozen=True)
+class UfunctorSignature:
+ g: NativeFunctionsGroup
+ scalar_tensor_idx: int | None
+ name: str
+
+ def arguments(self) -> UfunctorBindings:
+ return ufunc.ufunctor_arguments(
+ self.g, scalar_tensor_idx=self.scalar_tensor_idx, scalar_t=scalar_t
+ )
+
+ def fields(self) -> list[Binding]:
+ # fields are renamed to have a trailing underscore, as is conventional
+ return [b.rename(f"{b.name}_") for b in self.arguments().ctor]
+
+ def returns_type(self) -> CType:
+ # TODO: don't hardcode; return type will be inferred based on tags on
+ # the native function
+ return BaseCType(scalar_t)
+
+ def decl_fields(self) -> str:
+ return "\n".join(f"{f.type} {f.name};" for f in self.fields())
+
+ def inline_defn_ctor(self) -> str:
+ args_str = ", ".join(a.decl() for a in self.arguments().ctor)
+ # NB: hypothetically could do this with translate but the
+ # transition here is very regular
+ init_str = ", ".join(f"{a.name}_({a.name})" for a in self.arguments().ctor)
+ return f"{self.name}({args_str}) : {init_str} {{}}"
+
+ def decl_apply(self) -> str:
+ args_str = ", ".join(a.decl() for a in self.arguments().apply)
+ return f"{self.returns_type().cpp_type()} operator()({args_str}) const"
+
+
+@dataclass(frozen=True)
+class UfuncSignature:
+ g: NativeFunctionsGroup
+ name: str
+ compute_t: CType
+
+ def arguments(self) -> list[Binding]:
+ return ufunc.ufunc_arguments(self.g, compute_t=self.compute_t)
+
+ def call(self, ctx: Sequence[Binding | Expr]) -> str:
+ return f"{self.name}({', '.join(a.expr for a in translate(ctx, self.arguments()))})"
+
+
+# steps:
+# 1. take the functional signature
+# 2. use api.ufunc to convert it to template signature. this establishes
+# the type of the template function
+# 3. use api.ufunc (II) to generate a split struct / operator() signature.
+# this establish context in which we call the template signature
+#
+# StructuredImplSignature context
+# ~> functor constructor sig
+#
+# Functor constructor context
+# ~> functor fields sig
+#
+# Functor apply context (functor fields + functor apply sig)
+# ~> template sig
+#
+
+
+def eligible_for_binary_scalar_specialization(g: NativeFunctionsGroup) -> bool:
+ num_tensors = sum(
+ 1 for a in g.functional.func.arguments.flat_non_out if a.type.is_tensor_like()
+ )
+ return num_tensors == 2
+
+
+def compute_ufunc_cuda_functors(
+ g: NativeFunctionsGroup,
+) -> tuple[dict[ScalarType, dict[UfuncKey, UfunctorSignature]], str]:
+ # First, build the functors.
+ ufunctor_sigs: dict[ScalarType, dict[UfuncKey, UfunctorSignature]] = {}
+ ufunctors: list[str] = []
+ loops = g.out.ufunc_inner_loop
+ scalar_tensor_idx_lookup = {
+ UfuncKey.CUDAFunctorOnSelf: 1,
+ UfuncKey.CUDAFunctorOnOther: 0,
+ UfuncKey.CUDAFunctor: None,
+ }
+ if eligible_for_binary_scalar_specialization(g):
+ keys = [
+ UfuncKey.CUDAFunctorOnSelf,
+ UfuncKey.CUDAFunctorOnOther,
+ UfuncKey.CUDAFunctor,
+ ]
+ else:
+ keys = [UfuncKey.CUDAFunctor]
+ for k in [UfuncKey.CUDAFunctorOnSelf, UfuncKey.CUDAFunctorOnOther]:
+ assert k not in loops, f"cannot use {k} on non-binary function"
+ for k in keys:
+ # If the key was directly defined, skip functor codegen; we assume the
+ # user already done it for us
+ if k in loops:
+ ufunctor_sig = UfunctorSignature(
+ g, scalar_tensor_idx=scalar_tensor_idx_lookup[k], name=loops[k].name
+ )
+ for dtype in loops[k].supported_dtypes:
+ ufunctor_sigs.setdefault(dtype, {})[k] = ufunctor_sig
+ continue
+
+ # Note [ScalarOnly and Generic must match names for CUDA]
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ # Otherwise, look in ANY of the generic entries. For simplicity of
+ # codegen, both ScalarOnly and Generic are defined, the ufunc name
+ # must match (if they didn't match, we'd have to generate distinct
+ # functors per dtype, which is awful, so we're not going to do it unless
+ # someone really forces us to)
+ ufunc_name = None
+ supported_dtypes: OrderedSet[ScalarType] = OrderedSet()
+ for lk in [UfuncKey.ScalarOnly, UfuncKey.Generic]:
+ if lk not in loops:
+ continue
+ if ufunc_name is None:
+ ufunc_name = loops[lk].name
+ else:
+ # See Note [ScalarOnly and Generic must match names for CUDA]
+ assert (
+ ufunc_name == loops[lk].name
+ ), "ScalarOnly and Generic must have same ufunc name"
+ supported_dtypes |= loops[lk].supported_dtypes
+ assert ufunc_name is not None
+
+ name = f"{k}_{ufunc_name}"
+ ufunctor_sig = UfunctorSignature(
+ g, scalar_tensor_idx=scalar_tensor_idx_lookup[k], name=name
+ )
+ for dtype in supported_dtypes:
+ ufunctor_sigs.setdefault(dtype, {})[k] = ufunctor_sig
+
+ ufunc_sig = UfuncSignature(
+ g, name=f"ufunc::{ufunc_name}", compute_t=BaseCType(opmath_t)
+ )
+ apply_ctx = ufunctor_sig.fields() + ufunctor_sig.arguments().apply
+ ufunctors.append(
+ f"""
+template
+struct {ufunctor_sig.name} {{
+ using opmath_t = at::opmath_type;
+ {ufunctor_sig.decl_fields()}
+ {ufunctor_sig.inline_defn_ctor()}
+ __device__ {ufunctor_sig.decl_apply()} {{
+ return {ufunc_sig.call(apply_ctx)};
+ }}
+}};
+"""
+ )
+
+ return ufunctor_sigs, "\n".join(ufunctors)
+
+
+@dataclass(frozen=True)
+class BinaryScalarSpecializationConfig:
+ scalar_idx: int
+ ctor_tensor: str
+ ufunc_key: UfuncKey
+
+
+BinaryScalarSpecializationConfigs = [
+ BinaryScalarSpecializationConfig(
+ scalar_idx=0,
+ ctor_tensor="self",
+ ufunc_key=UfuncKey.CUDAFunctorOnOther,
+ ),
+ BinaryScalarSpecializationConfig(
+ scalar_idx=1,
+ ctor_tensor="other",
+ ufunc_key=UfuncKey.CUDAFunctorOnSelf,
+ ),
+]
+
+
+def compute_ufunc_cuda_dtype_body(
+ g: NativeFunctionsGroup,
+ dtype: ScalarType,
+ inner_loops: dict[UfuncKey, UfunctorSignature],
+ parent_ctx: Sequence[Binding],
+) -> str:
+ body = "using opmath_t = at::opmath_type;"
+ body += "if (false) {}\n" # for ease of codegen
+ for config in BinaryScalarSpecializationConfigs:
+ if config.ufunc_key not in inner_loops:
+ continue
+ ufunctor_sig = inner_loops[config.ufunc_key]
+ scalar_idx = config.scalar_idx + 1
+ # Make a copy and at the same time widen the type (not permissible
+ # without copy; we don't want to mutate the input argument anyway)
+ ctx: list[Expr | Binding] = list(parent_ctx)
+ ctx.append(
+ Expr(
+ expr=f"iter.scalar_value({scalar_idx})",
+ type=NamedCType(config.ctor_tensor, BaseCType(opmath_t)),
+ )
+ )
+ ufunctor_ctor_exprs_str = ", ".join(
+ a.expr for a in translate(ctx, ufunctor_sig.arguments().ctor)
+ )
+
+ # NB: ufunctor must be allocated before iter.remove_operand is called,
+ # as it relies on iter
+ body += f"""\
+else if (iter.is_cpu_scalar({scalar_idx})) {{
+ {ufunctor_sig.name} ufunctor({ufunctor_ctor_exprs_str});
+ iter.remove_operand({scalar_idx});
+ gpu_kernel(iter, ufunctor);
+}}"""
+
+ ufunctor_sig = inner_loops[UfuncKey.CUDAFunctor]
+ ufunctor_ctor_exprs_str = ", ".join(
+ a.expr for a in translate(parent_ctx, ufunctor_sig.arguments().ctor)
+ )
+ body += f"""
+else {{
+ gpu_kernel(iter, {ufunctor_sig.name}({ufunctor_ctor_exprs_str}));
+}}
+ """
+ return body
+
+
+@with_native_function
+def compute_ufunc_cuda(g: NativeFunctionsGroup) -> str:
+ # First, build the functors, indexing them by dtype
+ ufunctor_sigs, ufunctors = compute_ufunc_cuda_functors(g)
+
+ # Next, build the conditionals
+ sig = StructuredImplSignature(g, ufunc.kernel_name(g, DispatchKey.CUDA))
+ dtype_cases = []
+ for dtype, inner_ufunc_sigs in ufunctor_sigs.items():
+ dtype_cases.append(
+ f"""
+AT_DISPATCH_CASE(at::ScalarType::{dtype},
+ [&]() {{
+ {compute_ufunc_cuda_dtype_body(g, dtype, inner_ufunc_sigs, sig.arguments())}
+ }}
+)
+"""
+ )
+
+ dtype_cases_str = "\n".join(dtype_cases)
+
+ stub_sig = StubSignature(g)
+
+ return f"""
+{ufunctors}
+
+{stub_sig.type_defn()};
+{stub_sig.dispatch_decl()}
+
+{stub_sig.kernel_defn()} {{
+ AT_DISPATCH_SWITCH(iter.common_dtype(), "{sig.name}",
+ {dtype_cases_str}
+ );
+}}
+REGISTER_DISPATCH({stub_sig.name}, &{stub_sig.kernel_name})
+
+{sig.defn()} {{
+ {stub_sig.direct_call(sig.arguments())};
+}}
+"""
+
+
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+#
+# CPU STUFF
+#
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+
+
+@dataclass(frozen=True)
+class StubSignature:
+ g: NativeFunctionsGroup
+
+ @property
+ def name(self) -> str:
+ return f"{str(self.g.functional.func.name.name)}_stub"
+
+ @property
+ def kernel_name(self) -> str:
+ return f"{str(self.g.functional.func.name.name)}_kernel"
+
+ @property
+ def type_name(self) -> str:
+ return f"{str(self.g.functional.func.name.name)}_fn"
+
+ def arguments(self) -> list[Binding]:
+ return ufunc.stub_arguments(self.g)
+
+ def type(self) -> str:
+ cpp_args = self.arguments()
+ return f"void(*)(TensorIteratorBase&, {', '.join(a.type for a in cpp_args)})"
+
+ def dispatch_decl(self) -> str:
+ return f"DECLARE_DISPATCH({self.type_name}, {self.name})"
+
+ def dispatch_defn(self) -> str:
+ return f"DEFINE_DISPATCH({self.name})"
+
+ def kernel_defn(self) -> str:
+ return f"void {self.kernel_name}(TensorIteratorBase& iter, {', '.join(a.defn() for a in self.arguments())})"
+
+ def type_defn(self) -> str:
+ return f"using {self.type_name} = {self.type()}"
+
+ # must be called from context where this is TensorIteratorBase*
+ def call(self, ctx: Sequence[Binding]) -> str:
+ return f"{self.name}(device_type(), *this, {', '.join(a.expr for a in translate(ctx, self.arguments()))})"
+
+ # used in CUDA to skip the unnecessary dynamic dispatch
+ def direct_call(self, ctx: Sequence[Binding]) -> str:
+ return f"{self.kernel_name}(*this, {', '.join(a.expr for a in translate(ctx, self.arguments()))})"
+
+
+@with_native_function
+def compute_ufunc_cpu(g: NativeFunctionsGroup) -> str:
+ stub_sig = StubSignature(g)
+ sig = StructuredImplSignature(g, ufunc.kernel_name(g, DispatchKey.CPU))
+
+ return f"""
+{stub_sig.type_defn()};
+{stub_sig.dispatch_decl()}
+{stub_sig.dispatch_defn()};
+
+{sig.defn()} {{
+ {stub_sig.call(sig.arguments())};
+}}
+"""
+
+
+def compute_ufunc_cpu_dtype_body(
+ g: NativeFunctionsGroup,
+ dtype: ScalarType,
+ inner_loops: dict[UfuncKey, UfuncSignature],
+ parent_ctx: Sequence[Binding],
+) -> str:
+ assert UfuncKey.CPUScalar in inner_loops, f"{dtype}, {inner_loops.keys()}"
+ assert inner_loops.keys() <= {UfuncKey.CPUScalar, UfuncKey.CPUVector}
+ scalar_loop = inner_loops[UfuncKey.CPUScalar]
+ vec_loop = None
+ if UfuncKey.CPUVector in inner_loops:
+ vec_loop = inner_loops[UfuncKey.CPUVector]
+
+ # NB: We DON'T use translate here, because translate is
+ # incapable of CSE'ing the scalar accesses in case it is also
+ # used by Vectorized; also, the unpacking here is very simple
+ # and only affects Scalar; everything else is implicitly captured
+ # by the lambda
+
+ # Setup scalar in scope
+ body = []
+ ctx = []
+ for b in parent_ctx:
+ if isinstance(b.argument, Argument) and b.argument.type != BaseType(
+ BaseTy.Scalar
+ ):
+ continue
+ body.append(f"auto _s_{b.name} = {b.name}.to();")
+ ctx.append(Expr(f"_s_{b.name}", NamedCType(b.nctype.name, BaseCType(scalar_t))))
+ if vec_loop is not None:
+ for b in parent_ctx:
+ if isinstance(b.argument, Argument) and b.argument.type != BaseType(
+ BaseTy.Scalar
+ ):
+ continue
+ body.append(
+ f"auto _v_{b.name} = at::vec::Vectorized(_s_{b.name});"
+ )
+ ctx.append(
+ Expr(
+ f"_v_{b.name}",
+ NamedCType(b.nctype.name, VectorizedCType(BaseCType(scalar_t))),
+ )
+ )
+
+ # Setup lambda signature
+ # NB: simplified version of ufunctor_arguments
+ scalar_bindings = []
+ vec_bindings = []
+ for a in g.functional.func.arguments.flat_non_out:
+ if not a.type.is_tensor_like():
+ continue
+ assert a.type == BaseType(BaseTy.Tensor)
+ scalar_bindings.append(
+ Binding(
+ name=a.name,
+ nctype=NamedCType(a.name, BaseCType(scalar_t)),
+ argument=a,
+ )
+ )
+ if vec_loop is not None:
+ vec_bindings.append(
+ Binding(
+ name=a.name,
+ nctype=NamedCType(a.name, VectorizedCType(BaseCType(scalar_t))),
+ argument=a,
+ )
+ )
+
+ def with_ctx(b: Sequence[Binding]) -> list[Expr | Binding]:
+ r: list[Expr | Binding] = []
+ r.extend(ctx)
+ r.extend(b)
+ return r
+
+ body_str = "\n".join(body)
+ if vec_loop is not None:
+ return f"""
+{body_str}
+cpu_kernel_vec(iter,
+ [=]({', '.join(b.decl() for b in scalar_bindings)}) {{ return {scalar_loop.call(with_ctx(scalar_bindings))}; }},
+ [=]({', '.join(b.decl() for b in vec_bindings)}) {{ return {vec_loop.call(with_ctx(vec_bindings))}; }}
+);
+"""
+ else:
+ return f"""
+{body_str}
+cpu_kernel(iter,
+ [=]({', '.join(b.decl() for b in scalar_bindings)}) {{ return {scalar_loop.call(with_ctx(scalar_bindings))}; }}
+);
+"""
+
+
+@with_native_function
+def compute_ufunc_cpu_kernel(g: NativeFunctionsGroup) -> str:
+ stub_sig = StubSignature(g)
+
+ # Reindex the ufunc by dtypes; processing generic/scalaronly as well
+ loops = g.out.ufunc_inner_loop
+ ufunc_sigs: dict[ScalarType, dict[UfuncKey, UfuncSignature]] = {}
+ for k in [UfuncKey.CPUScalar, UfuncKey.CPUVector]:
+ lks = []
+ # ORDER MATTERS: this specifies overriding precedence
+ if k in loops: # should happen rarely
+ lks.append(k)
+ if UfuncKey.ScalarOnly in loops and k is UfuncKey.CPUScalar:
+ lks.append(UfuncKey.ScalarOnly)
+ if UfuncKey.Generic in loops:
+ lks.append(UfuncKey.Generic)
+ # TODO: don't hardcode ufunc:: namespace here, should be centralized smh
+ for lk in lks:
+ for dtype in loops[lk].supported_dtypes:
+ compute_t: CType
+ if k is UfuncKey.CPUScalar:
+ compute_t = BaseCType(scalar_t)
+ elif k is UfuncKey.CPUVector:
+ compute_t = VectorizedCType(BaseCType(scalar_t))
+ else:
+ raise AssertionError
+ inner_ufunc_sigs = ufunc_sigs.setdefault(dtype, {})
+ if k not in inner_ufunc_sigs:
+ inner_ufunc_sigs[k] = UfuncSignature(
+ g, name=f"ufunc::{loops[lk].name}", compute_t=compute_t
+ )
+
+ # Build the conditionals
+ dtype_cases = []
+ for dtype, inner_ufunc_sigs in ufunc_sigs.items():
+ dtype_cases.append(
+ f"""
+AT_DISPATCH_CASE(at::ScalarType::{dtype},
+ [&]() {{
+ {compute_ufunc_cpu_dtype_body(g, dtype, inner_ufunc_sigs, stub_sig.arguments())}
+ }}
+)
+"""
+ )
+
+ dtype_cases_str = "\n".join(dtype_cases)
+ return f"""
+namespace {{
+
+{stub_sig.kernel_defn()} {{
+ AT_DISPATCH_SWITCH(iter.common_dtype(), "{stub_sig.name}",
+ {dtype_cases_str}
+ );
+}}
+
+}} // anonymous namespace
+
+{stub_sig.type_defn()};
+{stub_sig.dispatch_decl()}
+REGISTER_DISPATCH({stub_sig.name}, &{stub_sig.kernel_name})
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35554d529c7e917eb866b1b6f4cd05e99b6b037b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/model.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/model.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96c0bda79941ac102e55f479e8cebc711b425eb8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/model.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/parse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/parse.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b96cda3451036b4de564323c2ad94d86e1ad779
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/__pycache__/parse.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a760a8f29516cc6d51b22932fa424da3f1f3369
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/custom_ops.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/custom_ops.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30b5d04e37ef5f8721c8e60113af2eb2bc0f88ca
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/custom_ops.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/et_cpp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/et_cpp.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70b9e734d25986323291738c8e475fb29f583360
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/et_cpp.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/unboxing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/unboxing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36a99158663223be4e3cd82fa719a7f47133a462
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/__pycache__/unboxing.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/custom_ops.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/custom_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..3871b2f5c9f193d581d46a9778bd3d3c20df3f07
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/custom_ops.py
@@ -0,0 +1,151 @@
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+from torchgen import dest
+
+
+# disable import sorting to avoid circular dependency.
+from torchgen.api.types import DispatcherSignature # usort: skip
+from torchgen.context import method_with_native_function
+from torchgen.model import BaseTy, BaseType, DispatchKey, NativeFunction, Variant
+from torchgen.utils import concatMap, Target
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from torchgen.executorch.model import ETKernelIndex
+ from torchgen.selective_build.selector import SelectiveBuilder
+
+
+# Generates RegisterKernelStub.cpp, which provides placeholder kernels for custom operators. This will be used at
+# model authoring side.
+@dataclass(frozen=True)
+class ComputeNativeFunctionStub:
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> str | None:
+ if Variant.function not in f.variants:
+ return None
+
+ sig = DispatcherSignature.from_schema(
+ f.func, prefix=f"wrapper_CPU_{f.func.name.overload_name}_", symint=False
+ )
+ assert sig is not None
+ if len(f.func.returns) == 0:
+ ret_name = ""
+ elif len(f.func.returns) == 1:
+ if f.func.arguments.out:
+ ret_name = f.func.arguments.out[0].name
+ else:
+ ret_name = next(
+ (
+ a.name
+ for a in f.func.arguments.flat_non_out
+ if a.type == f.func.returns[0].type
+ ),
+ "",
+ )
+ if not ret_name:
+ # if return type is tensor
+ if f.func.returns[0].type == BaseType(BaseTy.Tensor):
+ # Returns an empty tensor
+ ret_name = "at::Tensor()"
+ else:
+ raise Exception( # noqa: TRY002
+ f"Can't handle this return type {f.func}"
+ ) # noqa: TRY002
+ elif len(f.func.arguments.out) == len(f.func.returns):
+ # Returns a tuple of out arguments
+ tensor_type = "at::Tensor &"
+ comma = ", "
+ ret_name = f"""::std::tuple<{comma.join([tensor_type] * len(f.func.returns))}>(
+ {comma.join([r.name for r in f.func.arguments.out])}
+ )"""
+ else:
+ assert all(
+ a.type == BaseType(BaseTy.Tensor) for a in f.func.returns
+ ), f"Only support tensor returns but got {f.func.returns}"
+ # Returns a tuple of empty tensors
+ tensor_type = "at::Tensor"
+ comma = ", "
+ ret_name = f"""::std::tuple<{comma.join([tensor_type] * len(f.func.returns))}>(
+ {comma.join(["at::Tensor()" for _ in f.func.returns])}
+ )"""
+ ret_str = f"return {ret_name};" if len(f.func.returns) > 0 else ""
+ return f"""
+{sig.defn()} {{
+ {ret_str}
+}}
+ """
+
+
+def gen_custom_ops_registration(
+ *,
+ native_functions: Sequence[NativeFunction],
+ selector: SelectiveBuilder,
+ kernel_index: ETKernelIndex,
+ rocm: bool,
+) -> tuple[str, str]:
+ """
+ Generate custom ops registration code for dest.RegisterDispatchKey.
+
+ :param native_functions: a sequence of `NativeFunction`
+ :param selector: for selective build.
+ :param kernel_index: kernels for all the ops.
+ :param rocm: bool for dest.RegisterDispatchKey.
+ :return: generated C++ code to register custom operators into PyTorch
+ """
+
+ # convert kernel index to BackendIndex. This is because we can't handle ETKernelIndex yet.
+ # TODO larryliu: evaluate if this code is still needed. If yes let it handle ETKernelIndex.
+
+ dispatch_key = DispatchKey.CPU
+ backend_index = kernel_index._to_backend_index()
+ static_init_dispatch_registrations = ""
+ ns_grouped_native_functions: dict[str, list[NativeFunction]] = defaultdict(list)
+ for native_function in native_functions:
+ ns_grouped_native_functions[native_function.namespace].append(native_function)
+
+ for namespace, functions in ns_grouped_native_functions.items():
+ if len(functions) == 0:
+ continue
+ dispatch_registrations_body = "\n".join(
+ list(
+ concatMap(
+ dest.RegisterDispatchKey(
+ backend_index,
+ Target.REGISTRATION,
+ selector,
+ rocm=rocm,
+ symint=False,
+ class_method_name=None,
+ skip_dispatcher_op_registration=False,
+ ),
+ functions,
+ )
+ )
+ )
+ static_init_dispatch_registrations += f"""
+TORCH_LIBRARY_IMPL({namespace}, {dispatch_key}, m) {{
+{dispatch_registrations_body}
+}}"""
+ anonymous_definition = "\n".join(
+ list(
+ concatMap(
+ dest.RegisterDispatchKey(
+ backend_index,
+ Target.ANONYMOUS_DEFINITION,
+ selector,
+ rocm=rocm,
+ symint=False,
+ class_method_name=None,
+ skip_dispatcher_op_registration=False,
+ ),
+ native_functions,
+ )
+ )
+ )
+ return anonymous_definition, static_init_dispatch_registrations
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/et_cpp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/et_cpp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4b8fe5e4539b80e550641d695831060f1959bde
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/et_cpp.py
@@ -0,0 +1,372 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from torchgen import local
+from torchgen.api.types import (
+ ArgName,
+ BaseCType,
+ Binding,
+ ConstRefCType,
+ CType,
+ MutRefCType,
+ NamedCType,
+ SpecialArgName,
+ TupleCType,
+ VectorCType,
+ voidT,
+)
+from torchgen.executorch.api.types import (
+ ArrayRefCType,
+ BaseTypeToCppMapping,
+ OptionalCType,
+ scalarT,
+ tensorListT,
+ tensorT,
+)
+from torchgen.model import (
+ Argument,
+ Arguments,
+ BaseTy,
+ BaseType,
+ ListType,
+ NativeFunction,
+ OptionalType,
+ Return,
+ SelfArgument,
+ TensorOptionsArguments,
+ Type,
+)
+from torchgen.utils import assert_never
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+
+"""
+This file describes the translation of JIT schema to the public C++ API, which is what people use when they call
+functions like at::add. It also serves as a native function API, which is the signature of kernels,
+since in Executorch CppSignature is the same as NativeSignature.
+
+Difference between this file and torchgen.api.cpp.py:
+
+ - Executorch doesn't support TensorOptions, however in this file we still keep the logic here to be compatible with
+ torchgen.api.cpp, so that we can do stuff like ATen mode (running ATen kernels in Executorch).
+
+ - Executorch doesn't support Dimname.
+
+ - Executorch runtime doesn't support SymInt, will treat it as int.
+"""
+
+
+# Translation of "value types" in JIT schema to C++ API type. Value
+# types look the same no matter if they are argument types or return
+# types. Returns None if the type in question is not a value type.
+def valuetype_type(
+ t: Type,
+ *,
+ binds: ArgName,
+ remove_non_owning_ref_types: bool = False,
+) -> NamedCType | None:
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor or t.name == BaseTy.Scalar:
+ return None
+ # For SymInt we simply treat it as int.
+ elif str(t) == "SymInt":
+ return NamedCType(binds, BaseCType(BaseTypeToCppMapping[BaseTy.int]))
+ if remove_non_owning_ref_types:
+ if t.name == BaseTy.str:
+ raise AssertionError(
+ "string ref->value conversion: not implemented yet"
+ )
+ # All other BaseType currently map directly to BaseCppTypes.
+ return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
+ elif isinstance(t, OptionalType):
+ elem = valuetype_type(t.elem, binds=binds)
+ if elem is None:
+ return None
+ return NamedCType(binds, OptionalCType(elem.type))
+ elif isinstance(t, ListType):
+ if str(t.elem) == "bool":
+ assert t.size is not None
+ return NamedCType(
+ binds, ArrayRefCType(BaseCType(BaseTypeToCppMapping[BaseTy.bool]))
+ )
+ else:
+ return None
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Translation of types occurring in JIT arguments to a C++ argument type.
+# If remove_non_owning_ref_types is set, we'll guarantee that the outputed CType is not a non-owning reference type.
+# For example, we'll return std::vector instead of IntArrayRef.
+# See Note [translation from C++ reference to value types]
+def argumenttype_type(
+ t: Type,
+ *,
+ mutable: bool,
+ binds: ArgName,
+ remove_non_owning_ref_types: bool = False,
+) -> NamedCType:
+ # If it's a value type, do the value type translation
+ r = valuetype_type(
+ t,
+ binds=binds,
+ remove_non_owning_ref_types=remove_non_owning_ref_types,
+ )
+ if r is not None:
+ return r
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor:
+ if mutable and not local.use_const_ref_for_mutable_tensors():
+ return NamedCType(binds, MutRefCType(BaseCType(tensorT)))
+ else:
+ return NamedCType(binds, ConstRefCType(BaseCType(tensorT)))
+ elif t.name == BaseTy.Scalar:
+ return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
+ else:
+ raise AssertionError(f"base type should have been value type {t}")
+ elif isinstance(t, OptionalType):
+ if str(t.elem) == "Tensor":
+ if mutable and not local.use_const_ref_for_mutable_tensors():
+ return NamedCType(
+ binds, MutRefCType(BaseCType(tensorT))
+ ) # TODO: fix this discrepancy
+ else:
+ return NamedCType(
+ binds, ConstRefCType(OptionalCType(BaseCType(tensorT)))
+ )
+ elif str(t.elem) == "Scalar":
+ return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
+ elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
+ return NamedCType(binds, OptionalCType(elem.type))
+ elif isinstance(t, ListType):
+ # TODO: keeping these special cases for Tensor[] and Tensor?[] so that we can hookup with ATen kernels.
+ if str(t.elem) == "Tensor":
+ return NamedCType(binds, BaseCType(tensorListT))
+ elif str(t.elem) == "Dimname":
+ raise NotImplementedError("Executorch doesn't support Dimname")
+ elif str(t.elem) == "Tensor?":
+ return NamedCType(binds, ArrayRefCType(OptionalCType(BaseCType(tensorT))))
+ elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
+ return NamedCType(binds, ArrayRefCType(elem.type))
+ else:
+ raise AssertionError(f"unrecognized type {repr(t)}")
+
+
+# Translate a JIT argument into its C++ type
+def argument_type(a: Argument, *, binds: ArgName) -> NamedCType:
+ return argumenttype_type(a.type, mutable=a.is_write, binds=binds)
+
+
+# Translation of a (non-multi) return type from JIT to C++
+# N.B: returntype_type returns a CType, not a NamedCType.
+# This is mostly because of the mismatch between return types and return names.
+# e.g. a function with a return type of 'void' has 0 return names,
+# and a function with a return type of 'std::tuple' has >1 return name.
+def returntype_type(t: Type, *, mutable: bool) -> CType:
+ # placeholder is ignored
+ r = valuetype_type(t, binds="__placeholder__")
+ if r is not None:
+ return r.type
+
+ if isinstance(t, BaseType):
+ if t.name == BaseTy.Tensor:
+ if mutable:
+ if local.use_const_ref_for_mutable_tensors():
+ return ConstRefCType(BaseCType(tensorT))
+ else:
+ return MutRefCType(BaseCType(tensorT))
+ else:
+ # Note [Tensor Copy Returns]
+ # Currently, we use "Argument.is_write" to determine
+ # whether or not Tensor return types should be copies or references.
+ # If that ever changes, take a look at other locations of this note!
+ return BaseCType(tensorT)
+ elif t.name == BaseTy.Scalar:
+ return BaseCType(scalarT)
+ elif isinstance(t, ListType):
+ assert not mutable, "Native functions should never return a mutable tensor list. They should return void."
+ elem = returntype_type(t.elem, mutable=False)
+ assert t.size is None, f"fixed size list returns not supported: {t}"
+ return VectorCType(elem)
+
+ raise AssertionError(f"unrecognized return type {t}")
+
+
+# Translation of a single return to its C++ type
+def return_type(r: Return) -> CType:
+ return returntype_type(r.type, mutable=r.is_write)
+
+
+# Translation of a full (possibly multi) return from JIT to its C++ type
+def returns_type(rs: Sequence[Return]) -> CType:
+ if len(rs) == 0:
+ return BaseCType(voidT)
+ elif len(rs) == 1:
+ return return_type(rs[0])
+ else:
+ return TupleCType([return_type(r) for r in rs])
+
+
+def return_names(f: NativeFunction, *, fallback_name: str = "result") -> Sequence[str]:
+ returns: list[str] = []
+ for i, r in enumerate(f.func.returns):
+ # If we have an inplace function, the return argument is
+ # implicitly named self.
+ # TODO: Consider incorporating this into the data model
+ if f.func.name.name.inplace:
+ assert i == 0, "illegal inplace function with multiple returns"
+ name = "self"
+ # If we are out function, the name is the name of the
+ # corresponding output function (r.name will get recorded
+ # in field_name later.)
+ elif f.func.is_out_fn():
+ name = f.func.arguments.out[i].name
+ # If the return argument is explicitly named...
+ elif r.name:
+ name_conflict = any(
+ r.name == a.name for a in f.func.schema_order_arguments()
+ )
+ if name_conflict and not f.func.is_out_fn():
+ name = f"{r.name}_return"
+ else:
+ name = r.name
+ # If there is no explicit name and no fallback name was passed in, we just name the output result,
+ # unless it's a multi-return, in which case it's result0,
+ # result1, etc (zero-indexed)
+ else:
+ name = fallback_name if len(f.func.returns) == 1 else f"{fallback_name}{i}"
+ returns.append(name)
+ return returns
+
+
+JIT_TO_CPP_DEFAULT = {
+ "False": "false",
+ "True": "true",
+ "None": "torch::execustd::nullopt", # UGH this one is type directed
+ "[]": "{}",
+ "contiguous_format": "torch::executorch::MemoryFormat::Contiguous",
+ "long": "torch::executorch::kLong",
+}
+
+
+# Convert a JIT default into C++ expression representing the default
+def default_expr(d: str, t: Type) -> str:
+ if d == "None" and str(t) == "Tensor?":
+ return "{}"
+ if isinstance(t, BaseType) and t.name is BaseTy.str:
+ # Schema allows single quotes but C++ needs double
+ if len(d) >= 2 and d[0] == "'" and d[-1] == "'":
+ s = ""
+ i = 1
+ while i + 1 < len(d):
+ if d[i] != "\\":
+ if d[i] == '"':
+ s += '\\"'
+ else:
+ s += d[i]
+ i += 1
+ else:
+ if d[i + 1] == "'":
+ s += "'"
+ else:
+ s += d[i : i + 2]
+ i += 2
+
+ return f'"{s}"'
+
+ if isinstance(t, OptionalType):
+ if d == "None":
+ return "torch::executor::nullopt"
+
+ return default_expr(d, t.elem)
+
+ if isinstance(t, ListType):
+ if d.startswith("[") and d.endswith("]"):
+ return "{" + d[1:-1] + "}"
+ elif t.size is None:
+ # NOTE: Sized lists can have scalar defaults
+ raise ValueError(f"Expected a list default '[...]' but found: '{d}'")
+
+ return JIT_TO_CPP_DEFAULT.get(d, d)
+
+
+# Convert an argument into its C++ API form
+
+
+def argument(
+ a: Argument | TensorOptionsArguments | SelfArgument,
+ *,
+ cpp_no_default_args: set[str],
+ method: bool,
+ faithful: bool,
+ has_tensor_options: bool,
+) -> list[Binding]:
+ def sub_argument(
+ a: Argument | TensorOptionsArguments | SelfArgument,
+ ) -> list[Binding]:
+ return argument(
+ a,
+ cpp_no_default_args=cpp_no_default_args,
+ method=method,
+ faithful=faithful,
+ has_tensor_options=has_tensor_options,
+ )
+
+ if isinstance(a, Argument):
+ binds: ArgName
+ if a.name == "memory_format" and has_tensor_options:
+ binds = SpecialArgName.possibly_redundant_memory_format
+ else:
+ binds = a.name
+ default: str | None = None
+ if a.name not in cpp_no_default_args and a.default is not None:
+ default = default_expr(a.default, a.type)
+ return [
+ Binding(
+ nctype=argument_type(a, binds=binds),
+ name=a.name,
+ default=default,
+ argument=a,
+ )
+ ]
+ elif isinstance(a, TensorOptionsArguments):
+ raise NotImplementedError("Need to implement type resolution for TensorOptions")
+ elif isinstance(a, SelfArgument):
+ if method:
+ # Caller is responsible for installing implicit this in context!
+ return []
+ else:
+ return sub_argument(a.argument)
+ else:
+ assert_never(a)
+
+
+def arguments(
+ arguments: Arguments,
+ *,
+ faithful: bool,
+ method: bool,
+ cpp_no_default_args: set[str],
+) -> list[Binding]:
+ args: list[Argument | TensorOptionsArguments | SelfArgument] = []
+ if faithful:
+ args.extend(arguments.non_out)
+ args.extend(arguments.out)
+ else:
+ args.extend(arguments.out)
+ args.extend(arguments.non_out)
+ return [
+ r.no_default() if faithful else r
+ for a in args
+ for r in argument(
+ a,
+ faithful=faithful,
+ method=method,
+ has_tensor_options=arguments.tensor_options is not None,
+ cpp_no_default_args=cpp_no_default_args,
+ )
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..056b3b4416e32dbf1b8b0e0e785f5a3c3557cac3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__init__.py
@@ -0,0 +1,4 @@
+from torchgen.executorch.api.types.types import *
+
+
+from torchgen.executorch.api.types.signatures import * # usort: skip
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9056a575489113107b207f5ca56977a3d5d68814
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/signatures.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/signatures.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34c93d5077ec40ad4b4f2a8aee70e5084993a6a4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/signatures.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/types.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3a029365235f44be5f3b522a58077703ac3df56
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/__pycache__/types.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/signatures.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/signatures.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f8f90c0d5ef30fb828842b45f9412df169b4db7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/signatures.py
@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+import torchgen.api.cpp as aten_cpp
+from torchgen.executorch.api.types.types import contextArg
+
+
+if TYPE_CHECKING:
+ from torchgen.api.types import Binding, CType
+ from torchgen.model import FunctionSchema, NativeFunction
+
+
+@dataclass(frozen=True)
+class ExecutorchCppSignature:
+ """
+ This signature is merely a CppSignature with Executorch types (optionally
+ contains KernelRuntimeContext as well). The inline definition of
+ CppSignature is generated in Functions.h and it's used by unboxing
+ functions.
+ """
+
+ # The schema this signature is derived from
+ func: FunctionSchema
+
+ # The set of C++ arguments which should not have defaults applied to them
+ cpp_no_default_args: set[str]
+
+ # Allows you to prepend an arbitrary prefix to the signature name.
+ # This is useful for parts of the codegen that generate wrappers around kernels,
+ # and need to avoid naming collisions.
+ prefix: str = ""
+
+ def arguments(self, *, include_context: bool = True) -> list[Binding]:
+ return ([contextArg] if include_context else []) + et_cpp.arguments(
+ self.func.arguments,
+ faithful=True, # always faithful, out argument at the end
+ method=False, # method not supported
+ cpp_no_default_args=self.cpp_no_default_args,
+ )
+
+ def name(self) -> str:
+ return self.prefix + aten_cpp.name(
+ self.func,
+ faithful_name_for_out_overloads=True,
+ )
+
+ def decl(self, name: str | None = None, *, include_context: bool = True) -> str:
+ args_str = ", ".join(
+ a.decl() for a in self.arguments(include_context=include_context)
+ )
+ if name is None:
+ name = self.name()
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
+
+ def defn(self, name: str | None = None) -> str:
+ args = [a.defn() for a in self.arguments()]
+ args_str = ", ".join(args)
+ if name is None:
+ name = self.name()
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
+
+ def returns_type(self) -> CType:
+ return et_cpp.returns_type(self.func.returns)
+
+ @staticmethod
+ def from_native_function(
+ f: NativeFunction, *, prefix: str = ""
+ ) -> ExecutorchCppSignature:
+ return ExecutorchCppSignature(
+ func=f.func, prefix=prefix, cpp_no_default_args=f.cpp_no_default_args
+ )
+
+
+from torchgen.executorch.api import et_cpp
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/types.py
new file mode 100644
index 0000000000000000000000000000000000000000..5852e25ad70074fb9f8a74154d2ff8f99437cdfb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/types/types.py
@@ -0,0 +1,83 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from torchgen.api.types import (
+ BaseCppType,
+ BaseCType,
+ Binding,
+ boolT,
+ CType,
+ doubleT,
+ Expr,
+ longT,
+ MutRefCType,
+ NamedCType,
+)
+from torchgen.model import BaseTy
+
+
+halfT = BaseCppType("torch::executor", "Half")
+bfloat16T = BaseCppType("torch::executor", "BFloat16")
+stringT = BaseCppType("torch::executor", "string_view")
+scalarTypeT = BaseCppType("torch::executor", "ScalarType")
+tensorT = BaseCppType("torch::executor", "Tensor")
+tensorListT = BaseCppType("torch::executor", "TensorList")
+scalarT = BaseCppType("torch::executor", "Scalar")
+memoryFormatT = BaseCppType("torch::executor", "MemoryFormat")
+intArrayRefT = BaseCppType("torch::executor", "IntArrayRef")
+optionalT = BaseCppType("torch::executor", "optional")
+contextT = BaseCppType("torch::executor", "KernelRuntimeContext")
+
+contextExpr = Expr(
+ expr="context",
+ type=NamedCType(name="context", type=MutRefCType(BaseCType(contextT))),
+)
+
+contextArg = Binding(
+ name="context",
+ nctype=contextExpr.type,
+ argument=None, # type: ignore[arg-type]
+ default=None,
+)
+
+BaseTypeToCppMapping: dict[BaseTy, BaseCppType] = {
+ BaseTy.int: longT,
+ BaseTy.float: doubleT,
+ BaseTy.bool: boolT,
+ BaseTy.str: stringT,
+ BaseTy.ScalarType: scalarTypeT,
+ BaseTy.Tensor: tensorT,
+ BaseTy.Scalar: scalarT,
+ BaseTy.MemoryFormat: memoryFormatT,
+}
+
+
+@dataclass(frozen=True)
+class OptionalCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"torch::executor::optional<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"torch::executor::optional<{self.elem.cpp_type_registration_declarations()}>"
+
+ def remove_const_ref(self) -> CType:
+ return OptionalCType(self.elem.remove_const_ref())
+
+
+@dataclass(frozen=True)
+class ArrayRefCType(CType):
+ elem: CType
+
+ def cpp_type(self, *, strip_ref: bool = False) -> str:
+ # Do not pass `strip_ref` recursively.
+ return f"torch::executor::ArrayRef<{self.elem.cpp_type()}>"
+
+ def cpp_type_registration_declarations(self) -> str:
+ return f"torch::executor::ArrayRef<{self.elem.cpp_type_registration_declarations()}>"
+
+ def remove_const_ref(self) -> CType:
+ return ArrayRefCType(self.elem.remove_const_ref())
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/unboxing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/unboxing.py
new file mode 100644
index 0000000000000000000000000000000000000000..c905bb3a4350626175b2d018f7c4d3cdb6f2300f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/api/unboxing.py
@@ -0,0 +1,218 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Callable, TYPE_CHECKING
+
+from torchgen.model import (
+ Argument,
+ BaseTy,
+ BaseType,
+ ListType,
+ NativeFunction,
+ OptionalType,
+ Type,
+)
+
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from torchgen.api.types import Binding, CType, NamedCType
+
+
+connector = "\n\t"
+
+
+# Return unboxing function name for a NativeFunction
+def name(f: NativeFunction) -> str:
+ return f.func.name.unambiguous_name()
+
+
+@dataclass(frozen=True)
+class Unboxing:
+ """
+ Takes a sequence of Bindings and unbox EValues to these Bindings. Return generated code that performs correct unboxing.
+ A sample generated code:
+ // aten::mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ void mul_out(EValue** stack) {
+ EValue& self = *stack[0];
+ EValue& other = *stack[1];
+ EValue& out = *stack[2];
+ const torch::executor::Tensor & self_base = self.to();
+ const torch::executor::Tensor & other_base = other.to();
+ torch::executor::Tensor & out_base = out.to();
+
+ EXECUTORCH_SCOPE_PROF("native_call_mul.out");
+ torch::executor::mul_outf(self_base, other_base, out_base);
+
+
+ }
+ """
+
+ # this is a callable that converts a JIT argument, into its C++ type.
+ # Translates (type, mutability, binds) to NamedCType. E.g., torchgen.api.cpp.argumenttype_type.
+ argument_type_gen: Callable[
+ ...,
+ NamedCType,
+ ]
+
+ # Convert all the arguments in a NativeFunction to C++ code
+ def convert_arguments(
+ self, args: Sequence[Binding]
+ ) -> tuple[list[Binding], list[str]]:
+ code_list = [f"EValue& {args[i].name} = *stack[{i}];" for i in range(len(args))]
+ binding_list = []
+ for arg in args:
+ # expecting only Argument
+ if not isinstance(arg.argument, Argument):
+ raise Exception( # noqa: TRY002
+ f"Unexpected argument type, expecting `Argument` but got {arg}"
+ )
+ argument: Argument = arg.argument
+ unboxed_name, _, code, decl = self.argumenttype_evalue_convert(
+ argument.type, argument.name, mutable=argument.is_write
+ )
+ code_list.extend(decl)
+ code_list.extend(code)
+ binding_list.append(arg.with_name(unboxed_name))
+ return binding_list, code_list
+
+ def argumenttype_evalue_convert(
+ self, t: Type, arg_name: str, *, mutable: bool = False
+ ) -> tuple[str, CType, list[str], list[str]]:
+ """
+ Takes in the type, name and mutability corresponding to an argument, and generates a tuple of:
+ (1) the C++ code necessary to unbox the argument
+ (2) A Binding corresponding to the newly created unboxed variable, including variable name and its CType
+ :param t: a `Type` of an argument
+ :param arg_name: argument name
+ :param mutable: boolean for whether this argument type is mutable
+ :return: unboxed result
+ """
+ ctype = self.argument_type_gen(t, mutable=mutable, binds=arg_name).type
+
+ if isinstance(t, BaseType):
+ out_name = f"{arg_name}_base"
+ code, decl = self._gen_code_base_type(
+ arg_name=arg_name, out_name=out_name, ctype=ctype
+ )
+ elif isinstance(t, OptionalType):
+ out_name = f"{arg_name}_opt_out"
+ code, decl = self._gen_code_optional_type(
+ arg_name=arg_name, out_name=out_name, t=t, ctype=ctype
+ )
+ elif isinstance(t, ListType):
+ out_name = f"{arg_name}_list_out"
+ code, decl = self._gen_code_list_type(
+ arg_name=arg_name, out_name=out_name, t=t, ctype=ctype
+ )
+ else:
+ raise Exception( # noqa: TRY002
+ f"Cannot handle type {t}. arg_name: {arg_name}"
+ ) # noqa: TRY002
+ return out_name, ctype, code, decl
+
+ def _gen_code_base_type(
+ self, arg_name: str, out_name: str, ctype: CType
+ ) -> tuple[list[str], list[str]]:
+ return [
+ f"{ctype.cpp_type()} {out_name} = {arg_name}.to<{ctype.cpp_type(strip_ref=True)}>();"
+ ], []
+
+ def _gen_code_optional_type(
+ self, arg_name: str, out_name: str, t: OptionalType, ctype: CType
+ ) -> tuple[list[str], list[str]]:
+ in_name = f"{arg_name}_opt_in"
+ res_name, base_type, res_code, decl = self.argumenttype_evalue_convert(
+ t.elem, in_name
+ )
+ return (
+ f"""
+ auto {out_name} = {arg_name}.toOptional<{base_type.cpp_type(strip_ref=True)}>();
+ """.split("\n"),
+ decl,
+ )
+
+ def _gen_code_list_type(
+ self, arg_name: str, out_name: str, t: ListType, ctype: CType
+ ) -> tuple[list[str], list[str]]:
+ in_name = f"{arg_name}_list_in"
+ elem_name = f"{arg_name}_elem"
+ code = []
+ res_name, res_ctype, res_code, decl = self.argumenttype_evalue_convert(
+ t.elem, elem_name
+ )
+
+ if isinstance(t.elem, BaseType) and t.elem.name == BaseTy.Tensor:
+ code.extend(
+ f"""
+ auto {out_name} = {arg_name}.toTensorList();
+ """.split("\n")
+ )
+ elif isinstance(t.elem, BaseType) and (
+ t.elem.name == BaseTy.int or t.elem.name == BaseTy.SymInt
+ ):
+ code.extend(
+ f"""
+ auto {out_name} = {arg_name}.toIntList();
+ """.split("\n")
+ )
+ elif isinstance(t.elem, BaseType) and t.elem.name == BaseTy.float:
+ code.extend(
+ f"""
+ auto {out_name} = {arg_name}.toDoubleList();
+ """.split("\n")
+ )
+ elif isinstance(t.elem, BaseType) and t.elem.name == BaseTy.bool:
+ # handle list type with size, e.g., bool[4]
+ code.extend(
+ f"""
+#ifdef USE_ATEN_LIB
+std::array {out_name};
+auto {in_name} = {arg_name}.toBoolList();
+size_t _i = 0;
+for (auto {elem_name}: {in_name}) {{
+ {out_name}[_i++] = {elem_name};
+}}
+#else
+auto {out_name} = {arg_name}.toBoolList();
+#endif
+ """.split("\n")
+ )
+ # pytorch codegen:
+ # we have to use c10::List for optional element. e.g., Tensor?[] -> c10::List<::std::optional>
+ elif (
+ isinstance(t.elem, OptionalType)
+ and isinstance(t.elem.elem, BaseType)
+ and t.elem.elem.name == BaseTy.Tensor
+ ):
+ code.extend(
+ f"""
+#ifdef USE_ATEN_LIB
+auto {in_name} = {arg_name}.toListOptionalTensor();
+c10::List<::std::optional> {out_name};
+for (auto {elem_name}: {in_name}) {{
+ {out_name}.push_back({elem_name});
+}}
+#else
+auto {out_name} = {arg_name}.toListOptionalTensor();
+#endif
+ """.split("\n")
+ )
+ else:
+ # use ArrayRef as default.
+ vec_name = arg_name + "_vec"
+ # need to bring vector instantiation out of scope so that ArrayRef has valid data
+ decl.append(
+ f"std::vector<{res_ctype.cpp_type(strip_ref=True)}> {vec_name};"
+ )
+ code.extend(
+ f"""
+ for (EValue {elem_name}: {in_name}) {{
+ {connector.join(res_code)}
+ {vec_name}.push_back({res_name});
+ }}
+ {ctype.cpp_type(strip_ref=True)} {out_name}({vec_name});
+ """.split("\n")
+ )
+ return code, decl
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/model.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..450782186765ab2bb3f6b481cfb227ebe71255ff
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/model.py
@@ -0,0 +1,220 @@
+# Represents all kernels used by an Executorch model.
+# It maintains a dict[OperatorName, dict[ETKernelKey, BackendMetadata]] structure.
+
+from __future__ import annotations
+
+import itertools
+from collections import defaultdict, namedtuple
+from dataclasses import dataclass
+from enum import IntEnum
+
+from torchgen.model import (
+ BackendIndex,
+ BackendMetadata,
+ DispatchKey,
+ NativeFunction,
+ NativeFunctionsGroup,
+ OperatorName,
+)
+from torchgen.utils import assert_never
+
+
+KERNEL_KEY_VERSION = 1
+
+
+# TODO: Duplicated Subset from codegen.tool.gen_oplist, remove declaration in codegen
+class ScalarType(IntEnum):
+ Byte = 0
+ Char = 1
+ Short = 2
+ Int = 3
+ Long = 4
+ Float = 6
+ Double = 7
+ Bool = 11
+
+
+ETParsedYaml = namedtuple("ETParsedYaml", ["native_functions", "kernel_index"])
+
+
+@dataclass(frozen=True)
+class ETKernelKeyOpArgMeta:
+ arg_name: str
+ dtype: str
+ # The order of the dimensions if entry is a Tensor
+ dim_order: tuple[int, ...]
+
+ def to_native_string(self) -> str:
+ dtype_str = ScalarType[self.dtype].value
+ dim_str = str(self.dim_order)[1:-1].replace(" ", "")
+ return f"{dtype_str};{dim_str}"
+
+
+@dataclass(frozen=True)
+class ETKernelKey:
+ # Field undefined is default = True
+ arg_meta: tuple[ETKernelKeyOpArgMeta, ...] = ()
+
+ # Indicator for this kernel being used as a catch all
+ default: bool = False
+
+ version: int = KERNEL_KEY_VERSION
+
+ @staticmethod
+ def gen_from_yaml(
+ args: dict[str, tuple[str, str]],
+ type_alias_map: dict[str, list[str]], # TODO: Support unwrapped str val
+ dim_order_alias_map: dict[str, list[int]],
+ ) -> list[ETKernelKey]:
+ """Generate ETKernelKeys from arg kernel specs
+ Multiple ETKernelKeys are returned due to dtype permutations from utilizing
+ type_alias_map (actualizing each potential type permutation as a KernelKey)
+
+ Args:
+ args: Mapping from argument name to kernel specs
+ Kernel specs are a tuple of (dtype, dim_order).
+ Currently tuple entries must be aliased via the alias map arguments
+ type_alias_map: Mapping from type alias to potential type enums
+ i.e { T0 : [Double, Int] } means T0 can be either Double or Int
+ Used for lookup by args
+ dim_order_alias_map: Mapping from alias to a list of dimension orders
+ Used for lookup by args
+ """
+ # Cast to dim order to int
+ dim_order_alias_map = {
+ k: [int(alias) for alias in v] for k, v in dim_order_alias_map.items()
+ }
+ kernel_keys = []
+
+ # Get all used Dtype Alias
+ dtype_alias_used = set()
+ for type_alias, dim_order in args.values():
+ # Enforce usage of alias initially
+ # TODO: Support inlined arguments
+ assert type_alias in type_alias_map, "Undefined type alias: " + str(
+ type_alias
+ )
+ assert (
+ dim_order in dim_order_alias_map
+ ), f"Undefined dim_order alias: {dim_order}"
+ dtype_alias_used.add(type_alias)
+
+ # Generate all permutations of dtype alias values
+ alias_dtypes = [
+ [(alias, dtype) for dtype in type_alias_map[alias]]
+ for alias in dtype_alias_used
+ ]
+ alias_permutations = [
+ dict(permutation) for permutation in list(itertools.product(*alias_dtypes))
+ ]
+
+ # Using each alias value permutation, generate kernel keys
+ op_arg_cache = {}
+ for permutation in alias_permutations:
+ arg_list = []
+ for arg_name, arg_spec in args.items():
+ dtype = permutation[arg_spec[0]]
+ dim_order = dim_order_alias_map[arg_spec[1]] # type: ignore[assignment]
+ if (
+ cache_key := (arg_name, dtype, tuple(dim_order))
+ ) not in op_arg_cache:
+ op_arg_cache[cache_key] = ETKernelKeyOpArgMeta(*cache_key) # type: ignore[arg-type]
+
+ arg_list.append(op_arg_cache[cache_key])
+ kernel_keys.append(ETKernelKey(tuple(arg_list)))
+
+ return kernel_keys
+
+ def to_native_string(self) -> str:
+ if self.default:
+ return "default"
+ return (
+ "v"
+ + str(KERNEL_KEY_VERSION)
+ + "/"
+ + "|".join([arg.to_native_string() for arg in self.arg_meta])
+ )
+
+
+@dataclass(frozen=True)
+class ETKernelIndex:
+ index: dict[OperatorName, dict[ETKernelKey, BackendMetadata]]
+
+ def has_kernels(self, g: NativeFunction | NativeFunctionsGroup) -> bool:
+ m = self.get_kernels(g)
+ return m is not None
+
+ def get_kernels(
+ self, g: NativeFunction | NativeFunctionsGroup
+ ) -> dict[ETKernelKey, BackendMetadata]:
+ if isinstance(g, NativeFunction):
+ f = g
+ elif isinstance(g, NativeFunctionsGroup):
+ f = g.functional
+ else:
+ assert_never(g)
+ if f.func.name not in self.index:
+ return {}
+ return self.index[f.func.name]
+
+ @staticmethod
+ def grow_from_backend_indices(
+ kernel_index: dict[OperatorName, dict[ETKernelKey, BackendMetadata]],
+ backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
+ ) -> None:
+ for dk in backend_indices:
+ index = backend_indices[dk]
+ for op, backend_metadata in index.items():
+ if op in kernel_index:
+ kernel_index[op][ETKernelKey(default=True)] = backend_metadata
+ else:
+ kernel_index[op] = {ETKernelKey(default=True): backend_metadata}
+
+ @staticmethod
+ def from_backend_indices(
+ backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]],
+ ) -> ETKernelIndex:
+ kernel_index: dict[OperatorName, dict[ETKernelKey, BackendMetadata]] = (
+ defaultdict(dict)
+ )
+ ETKernelIndex.grow_from_backend_indices(kernel_index, backend_indices)
+ return ETKernelIndex(kernel_index)
+
+ def grow(
+ self, backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]]
+ ) -> ETKernelIndex:
+ ETKernelIndex.grow_from_backend_indices(self.index, backend_indices)
+ return self
+
+ def _to_backend_index(self) -> BackendIndex:
+ """
+ WARNING: this will be deprecated once all the codegen places know how to handle ETKernelIndex.
+ """
+ index: dict[OperatorName, BackendMetadata] = {}
+ for op in self.index:
+ kernel_dict = self.index[op]
+ assert (
+ len(kernel_dict.values()) == 1
+ ), f"Can't convert ETKernelIndex to BackendIndex because {op} has more than one kernels. Got {kernel_dict}"
+ index[op] = kernel_dict.get(
+ ETKernelKey(default=True),
+ BackendMetadata(kernel="", structured=False, cpp_namespace=""),
+ )
+ return BackendIndex(
+ dispatch_key=DispatchKey.CPU,
+ use_out_as_primary=False,
+ device_guard=False,
+ external=False,
+ index=index,
+ )
+
+ # Note duplicate ETKernelKey from index_b will clobber the metadata from index_a
+ @staticmethod
+ def merge_indices(index_a: ETKernelIndex, index_b: ETKernelIndex) -> ETKernelIndex:
+ combined = defaultdict(dict, index_a.index.copy())
+
+ for op, entry in index_b.index.items():
+ for key, metadata in entry.items():
+ combined[op][key] = metadata
+
+ return ETKernelIndex(combined)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/parse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/parse.py
new file mode 100644
index 0000000000000000000000000000000000000000..86b73e0ce1d709dd9960c1493111782de3881749
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/executorch/parse.py
@@ -0,0 +1,153 @@
+from __future__ import annotations
+
+from collections import defaultdict, namedtuple
+from typing import Any
+
+import yaml
+
+from torchgen.executorch.model import ETKernelIndex, ETKernelKey
+from torchgen.gen import LineLoader, parse_native_yaml
+from torchgen.model import (
+ BackendMetadata,
+ DispatchKey,
+ FunctionSchema,
+ NativeFunction,
+ OperatorName,
+)
+from torchgen.utils import NamespaceHelper
+
+
+# Parse native_functions.yaml into a sequence of NativeFunctions and ET Backend Indices.
+ETParsedYaml = namedtuple("ETParsedYaml", ["native_functions", "et_kernel_indices"])
+
+# Fields in native_functions.yaml used to determine which kernels should be used
+ET_FIELDS = ["kernels", "type_alias", "dim_order_alias"]
+
+
+def parse_from_yaml(ei: dict[str, object]) -> dict[ETKernelKey, BackendMetadata]:
+ """Given a loaded yaml representing kernel assignment information, extract the
+ mapping from `kernel keys` to `BackendMetadata` (the latter representing the kernel instance)
+
+ Args:
+ ei: Dict keys {kernels, type_alias, dim_order_alias}
+ See ETKernelKey for description of arguments
+ """
+ e = ei.copy()
+ if (kernels := e.pop("kernels", None)) is None:
+ return {}
+
+ type_alias: dict[str, list[str]] = e.pop("type_alias", {}) # type: ignore[assignment]
+ dim_order_alias: dict[str, list[str]] = e.pop("dim_order_alias", {}) # type: ignore[assignment]
+ dim_order_alias.pop("__line__", None)
+
+ kernel_mapping: dict[ETKernelKey, BackendMetadata] = {}
+
+ for entry in kernels: # type: ignore[attr-defined]
+ arg_meta = entry.get("arg_meta")
+ if arg_meta is not None:
+ arg_meta.pop("__line__")
+
+ kernel_name = entry.get("kernel_name")
+ namespace_helper = NamespaceHelper.from_namespaced_entity(
+ kernel_name, max_level=3
+ )
+ kernel_namespace = namespace_helper.get_cpp_namespace(default="at")
+ backend_metadata = BackendMetadata(
+ kernel=namespace_helper.entity_name,
+ structured=False,
+ cpp_namespace=(kernel_namespace + "::native"),
+ )
+
+ kernel_keys = (
+ [ETKernelKey((), default=True)]
+ if arg_meta is None
+ else ETKernelKey.gen_from_yaml(arg_meta, type_alias, dim_order_alias) # type: ignore[arg-type]
+ )
+
+ for kernel_key in kernel_keys:
+ assert kernel_key not in kernel_mapping, (
+ "Duplicate kernel key: " + str(kernel_key) + " " + str(e)
+ )
+ kernel_mapping[kernel_key] = backend_metadata
+
+ return kernel_mapping
+
+
+def parse_et_yaml_struct(es: object) -> ETKernelIndex:
+ """Given a loaded yaml representing a list of operators, for each op extract the mapping
+ of `kernel keys` to `BackendMetadata` (the latter representing the kernel instance
+ that should be used by the kernel key).
+ """
+ indices: dict[OperatorName, dict[ETKernelKey, BackendMetadata]] = {}
+ for ei in es: # type: ignore[attr-defined]
+ e = ei.copy()
+
+ funcs = e.pop("func")
+ assert isinstance(funcs, str), f"not a str: {funcs}"
+ namespace_helper = NamespaceHelper.from_namespaced_entity(
+ namespaced_entity=funcs, max_level=1
+ )
+ opname = FunctionSchema.parse(namespace_helper.entity_name).name
+
+ assert opname not in indices, f"Duplicate func found in yaml: {opname} already"
+
+ if len(index := parse_from_yaml(e)) != 0:
+ indices[opname] = index
+
+ return ETKernelIndex(indices)
+
+
+def extract_kernel_fields(es: object) -> dict[OperatorName, dict[str, Any]]:
+ """Given a loaded yaml representing a list of operators, extract the
+ kernel key related fields indexed by the operator name.
+ """
+ fields: dict[OperatorName, dict[str, Any]] = defaultdict(dict)
+ for ei in es: # type: ignore[attr-defined]
+ funcs = ei.get("func")
+ assert isinstance(funcs, str), f"not a str: {funcs}"
+ namespace_helper = NamespaceHelper.from_namespaced_entity(
+ namespaced_entity=funcs, max_level=1
+ )
+ opname = FunctionSchema.parse(namespace_helper.entity_name).name
+
+ for field in ET_FIELDS:
+ if (value := ei.get(field)) is not None:
+ fields[opname][field] = value
+
+ return fields
+
+
+def parse_et_yaml(
+ path: str,
+ tags_yaml_path: str,
+ ignore_keys: set[DispatchKey] | None = None,
+ skip_native_fns_gen: bool = False,
+) -> tuple[list[NativeFunction], dict[OperatorName, dict[str, Any]]]:
+ """Parse native_functions.yaml into NativeFunctions and an Operator Indexed Dict
+ of fields to persist from native_functions.yaml to functions.yaml
+ """
+ with open(path) as f:
+ es = yaml.load(f, Loader=LineLoader)
+
+ et_kernel = extract_kernel_fields(es)
+
+ # Remove ET specific fields from entries for BC compatibility
+ strip_et_fields(es)
+
+ native_yaml = parse_native_yaml(
+ path,
+ tags_yaml_path,
+ ignore_keys,
+ skip_native_fns_gen=skip_native_fns_gen,
+ loaded_yaml=es,
+ )
+ return native_yaml.native_functions, et_kernel
+
+
+def strip_et_fields(es: object) -> None:
+ """Given a loaded yaml representing a list of operators,
+ remove ET specific fields from every entries for BC compatibility
+ """
+ for entry in es: # type: ignore[attr-defined]
+ for field in ET_FIELDS:
+ entry.pop(field, None)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0f050611200d023e99c7894e291553f3399726e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9aa1c33b4c2c34fef08a1e0f79fd0d085424a955
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..612a445115c450888847f51d9de8b2ce3dcf9c66
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3d023618a08515a47c29cfcd2927dd73e9b1ad7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py
@@ -0,0 +1,389 @@
+#!/usr/bin/env python3
+
+from __future__ import annotations
+
+import os
+from enum import Enum
+from operator import itemgetter
+from pathlib import Path
+from typing import Any
+
+import torch
+from torch.jit.generate_bytecode import generate_upgraders_bytecode
+from torchgen.code_template import CodeTemplate
+from torchgen.operator_versions.gen_mobile_upgraders_constant import (
+ MOBILE_UPGRADERS_HEADER_DESCRIPTION,
+)
+
+
+class ByteCode(Enum):
+ instructions = 1
+ constants = 2
+ types = 3
+ operators = 4
+ register_size = 5
+
+
+EXCLUDED_OP_SET = [
+ "aten::full.names",
+ "aten::full.out",
+ "aten::full",
+]
+
+EXCLUE_UPGRADER_SET = ["full_0_4", "full_out_0_4"]
+
+ONE_INSTRUCTION = CodeTemplate(
+ """
+ Instruction{OpCode::${operator_name}, ${X}, ${N}},"""
+)
+
+INSTRUCTION_LIST = CodeTemplate(
+ """std::vector({
+ ${instruction_list}
+ }), // instructions list"""
+)
+
+ONE_CONSTANT = CodeTemplate(
+ """
+ c10::IValue(${constant}),"""
+)
+
+CONSTANT_LIST = CodeTemplate(
+ """std::vector({
+ ${constant_list}
+ }), // constants list"""
+)
+
+CONSTANTS_LIST_EMPTY = """std::vector(), // constants list"""
+
+ONE_TYPE = CodeTemplate("""c10::parseType("${type_str}"),""")
+
+TYPE_LIST = CodeTemplate(
+ """std::vector({
+ ${type_list}
+ }), // types list"""
+)
+
+TYPE_LIST_EMPTY = """std::vector(), // types list"""
+
+ONE_OPERATOTR_STRING = CodeTemplate(
+ """
+ OperatorString({"${operator_name}", "${overload_name}", ${num_of_args}}),"""
+)
+
+OPERATOR_STRING_LIST = CodeTemplate(
+ """
+ std::vector({
+ ${operator_string_list}
+ }), // operators list"""
+)
+
+ONE_UPGRADER_FUNCTION = CodeTemplate(
+ """
+ mobile::Function::registerFunc(
+ "${upgrader_name}",
+ ${instruction_list},
+ ${constant_list},
+ ${type_list},
+ ${register_size}
+ )"""
+)
+
+ONE_UPGRADER_SRC = CodeTemplate(
+ """
+ ByteCodeFunctionWithOperator({
+ ${bytecode_function},
+ ${operator_string_list}
+ }),"""
+)
+
+
+ONE_UPGRADER_IN_VERSION_MAP = CodeTemplate(
+ """Upgrader({${upgrader_min_version}, ${upgrader_max_version}, "${upgrader_name}", ${bytecode_func_index}})"""
+) # noqa: E501
+
+ONE_OPERATOR_IN_VERSION_MAP = CodeTemplate(
+ """
+ {std::string("${operator_name}"),
+ std::vector({
+ ${upgrader_list_in_version_map}
+ })},"""
+)
+
+
+OPERATOR_VERSION_MAP = CodeTemplate(
+ """
+const std::unordered_map>
+getOperatorVersionMapForMobile() {
+ static std::unordered_map>
+ operatorVersionMapForMobile({
+ ${operator_list_in_version_map}
+ });
+ return operatorVersionMapForMobile;
+}
+"""
+)
+
+
+UPGRADER_CPP_SRC = CodeTemplate(
+ MOBILE_UPGRADERS_HEADER_DESCRIPTION
+ + """
+#include
+#include
+
+namespace c10 {
+TypePtr parseType(const std::string& pythonStr);
+} // namespace c10
+
+namespace torch {
+namespace jit {
+
+// clang-format off
+
+// From operator_versions_map
+${operator_version_map}
+
+const std::vector& getUpgraderBytecodeList() {
+ auto generate_upgrader_bytecode_list = []() {
+ std::vector upgrader_function_list({
+ ${upgrader_bytecode}
+ });
+ for (const auto& upgrader_function : upgrader_function_list) {
+ for (const auto& op : upgrader_function.operators) {
+ upgrader_function.function.append_operator(
+ op.name,
+ op.overload_name,
+ op.num_specified_args);
+ }
+ }
+ return upgrader_function_list;
+ };
+ static std::vector upgraderBytecodeList =
+ generate_upgrader_bytecode_list();
+ return upgraderBytecodeList;
+}
+
+// clang-format on
+
+} // namespace jit
+} // namespace torch
+"""
+)
+
+UPGRADER_MOBILE_FILE_NAME = "upgrader_mobile.cpp"
+
+UPGRADER_ELEMENT = CodeTemplate(
+ """\
+Upgrader({${min_version}, ${max_version}, ${operator_name}, ${index}}),
+"""
+)
+
+PER_OPERATOR_UPGRADER_LIST = CodeTemplate(
+ """\
+{
+ std::string(${operator_name}),
+ std::vector({${upgrader_list}});
+}
+"""
+)
+
+
+def construct_instruction(instruction_list_from_yaml: list[Any]) -> str:
+ instruction_list_part = [
+ ONE_INSTRUCTION.substitute(
+ operator_name=instruction[0],
+ X=instruction[1],
+ N=instruction[2],
+ )
+ for instruction in instruction_list_from_yaml
+ ]
+ return INSTRUCTION_LIST.substitute(
+ instruction_list="".join(instruction_list_part).lstrip("\n")
+ )
+
+
+def construct_constants(constants_list_from_yaml: list[Any]) -> str:
+ constants_list_part = []
+ for constant_from_yaml in constants_list_from_yaml:
+ convert_constant = None
+ if isinstance(constant_from_yaml, str):
+ # Add quotes if it's string
+ convert_constant = f'"{constant_from_yaml}"'
+ elif isinstance(constant_from_yaml, bool):
+ convert_constant = "true" if constant_from_yaml else "false"
+ elif constant_from_yaml is None:
+ convert_constant = ""
+ elif isinstance(constant_from_yaml, int):
+ convert_constant = str(constant_from_yaml)
+ else:
+ raise ValueError(
+ f"The type of {constant_from_yaml} is {type(constant_from_yaml)}. "
+ "Please add change in construct_constants function in gen_mobile_upgraders.py."
+ )
+ constants_list_part.append(ONE_CONSTANT.substitute(constant=convert_constant))
+ if len(constants_list_part) == 0:
+ return CONSTANTS_LIST_EMPTY
+ return CONSTANT_LIST.substitute(
+ constant_list="".join(constants_list_part).lstrip("\n")
+ )
+
+
+def construct_operators(operator_list_from_yaml: list[Any]) -> str:
+ operator_list_part = [
+ ONE_OPERATOTR_STRING.substitute(
+ operator_name=operator[0],
+ overload_name=operator[1],
+ num_of_args=operator[2],
+ )
+ for operator in operator_list_from_yaml
+ ]
+ return OPERATOR_STRING_LIST.substitute(
+ operator_string_list="".join(operator_list_part).lstrip("\n")
+ )
+
+
+def construct_types(types_tr_list_from_yaml: list[Any]) -> str:
+ types_tr_list_part = [
+ ONE_TYPE.substitute(type_str=types_tr) for types_tr in types_tr_list_from_yaml
+ ]
+ if len(types_tr_list_part) == 0:
+ return TYPE_LIST_EMPTY
+ return TYPE_LIST.substitute(type_list="".join(types_tr_list_part).lstrip("\n"))
+
+
+def construct_register_size(register_size_from_yaml: int) -> str:
+ if not isinstance(register_size_from_yaml, int):
+ raise ValueError(
+ f"Input register size is {register_size_from_yaml} and"
+ "it's type is {type(register_size_from_yaml)}. An int type is expected."
+ )
+ return str(register_size_from_yaml)
+
+
+def construct_version_maps(
+ upgrader_bytecode_function_to_index_map: dict[str, Any],
+) -> str:
+ version_map = torch._C._get_operator_version_map()
+ sorted_version_map_ = sorted(version_map.items(), key=itemgetter(0)) # type: ignore[no-any-return]
+ sorted_version_map = dict(sorted_version_map_)
+
+ operator_list_in_version_map_part = []
+ for op_name in sorted_version_map:
+ upgraders_in_version_map_part = []
+ # TODO: remove the skip after these two operators schemas are fixed
+ if op_name in EXCLUDED_OP_SET:
+ continue
+ upgrader_ranges = torch._C._get_upgrader_ranges(op_name)
+ upgrader_entries = sorted_version_map[op_name]
+ assert len(upgrader_ranges) == len(upgrader_entries)
+ for idx, upgrader_entry in enumerate(upgrader_entries):
+ upgrader_name = upgrader_entry.upgrader_name
+ bytecode_function_index = upgrader_bytecode_function_to_index_map[
+ upgrader_name
+ ]
+ upgraders_in_version_map_part.append(
+ ONE_UPGRADER_IN_VERSION_MAP.substitute(
+ upgrader_min_version=upgrader_ranges[idx].min_version,
+ upgrader_max_version=upgrader_ranges[idx].max_version,
+ upgrader_name=upgrader_name,
+ bytecode_func_index=bytecode_function_index,
+ )
+ )
+ operator_list_in_version_map_part.append(
+ ONE_OPERATOR_IN_VERSION_MAP.substitute(
+ operator_name=op_name,
+ upgrader_list_in_version_map="".join(upgraders_in_version_map_part),
+ )
+ )
+ return OPERATOR_VERSION_MAP.substitute(
+ operator_list_in_version_map="".join(operator_list_in_version_map_part).lstrip(
+ "\n"
+ )
+ )
+
+
+def get_upgrader_bytecode_function_to_index_map(
+ upgrader_dict: list[dict[str, Any]],
+) -> dict[str, Any]:
+ upgrader_bytecode_function_to_index_map = {}
+ index = 0
+ for upgrader_bytecode in upgrader_dict:
+ for upgrader_name in upgrader_bytecode.keys():
+ if upgrader_name in EXCLUE_UPGRADER_SET:
+ continue
+ upgrader_bytecode_function_to_index_map[upgrader_name] = index
+ index += 1
+ return upgrader_bytecode_function_to_index_map
+
+
+def write_cpp(cpp_path: str, upgrader_dict: list[dict[str, Any]]) -> None:
+ upgrader_bytecode_function_to_index_map = (
+ get_upgrader_bytecode_function_to_index_map(upgrader_dict)
+ )
+ version_map_src = construct_version_maps(upgrader_bytecode_function_to_index_map)
+ all_upgrader_src_string = []
+ for upgrader_bytecode in upgrader_dict:
+ for upgrader_name, bytecode in upgrader_bytecode.items():
+ # TODO: remove the skip after these two operators schemas are fixed
+ if upgrader_name in EXCLUE_UPGRADER_SET:
+ continue
+ instruction_list_str = ""
+ constant_list_str = ""
+ type_list_str = ""
+ register_size_str = ""
+ operator_list_str = ""
+ for table_name, contents in bytecode.items():
+ element = ByteCode[table_name]
+ if element is ByteCode.instructions:
+ instruction_list_str = construct_instruction(contents)
+ elif element is ByteCode.constants:
+ constant_list_str = construct_constants(contents)
+ elif element is ByteCode.operators:
+ operator_list_str = construct_operators(contents)
+ elif element is ByteCode.types:
+ type_list_str = construct_types(contents)
+ elif element is ByteCode.register_size:
+ register_size_str = construct_register_size(contents)
+
+ one_upgrader_function_string = ONE_UPGRADER_FUNCTION.substitute(
+ upgrader_name=upgrader_name,
+ instruction_list=instruction_list_str,
+ constant_list=constant_list_str,
+ type_list=type_list_str,
+ register_size=register_size_str,
+ )
+ one_upgrader_src_string = ONE_UPGRADER_SRC.substitute(
+ bytecode_function=one_upgrader_function_string.lstrip("\n"),
+ operator_string_list=operator_list_str.lstrip("\n"),
+ )
+ all_upgrader_src_string.append(one_upgrader_src_string)
+
+ upgrader_file_content = UPGRADER_CPP_SRC.substitute(
+ operator_version_map=version_map_src,
+ upgrader_bytecode="".join(all_upgrader_src_string).lstrip("\n"),
+ )
+ print("writing file to : ", cpp_path + "/" + UPGRADER_MOBILE_FILE_NAME)
+ with open(os.path.join(cpp_path, UPGRADER_MOBILE_FILE_NAME), "wb") as out_file:
+ out_file.write(upgrader_file_content.encode("utf-8"))
+
+
+def sort_upgrader(upgrader_list: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ sorted_upgrader_list = sorted(
+ upgrader_list, key=lambda one_upgrader: next(iter(one_upgrader))
+ )
+ return sorted_upgrader_list
+
+
+def main() -> None:
+ upgrader_list = generate_upgraders_bytecode()
+ sorted_upgrader_list = sort_upgrader(upgrader_list)
+ for up in sorted_upgrader_list:
+ print("after sort upgrader : ", next(iter(up)))
+
+ pytorch_dir = Path(__file__).resolve().parents[2]
+ upgrader_path = pytorch_dir / "torch" / "csrc" / "jit" / "mobile"
+ write_cpp(str(upgrader_path), sorted_upgrader_list)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py
new file mode 100644
index 0000000000000000000000000000000000000000..923e39c4891e0562df75652d05673c4e393aff1b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py
@@ -0,0 +1,7 @@
+MOBILE_UPGRADERS_HEADER_DESCRIPTION = """/**
+ * @generated
+ * This is an auto-generated file. Please do not modify it by hand.
+ * To re-generate, please run:
+ * cd ~/pytorch && python torchgen/operator_versions/gen_mobile_upgraders.py
+ */
+"""
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/native/native_functions.yaml b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/native/native_functions.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9ad02bcd95c79b84f236ce4098529bdc21d35bab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/native/native_functions.yaml
@@ -0,0 +1,15795 @@
+# See README.md in this directory for more guidance
+
+# *********NB: _cast_* operators are DEPRECATED and will be removed
+# eventually. These were previously used before TorchScript IR supported
+# representing ScalarType's. They are now superseded by usage of
+# `aten::to()`. The ops remain here for backward compatibility purposes.
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Byte(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Char(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Double(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Float(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Int(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Long(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Short(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# DEPRECATED. DO NOT USE
+- func: _cast_Half(Tensor self, bool non_blocking=False) -> Tensor
+ variants: function
+
+# Computes the gradient of current tensor w.r.t. graph leaves.
+- func: _backward(Tensor self, Tensor[] inputs, Tensor? gradient=None, bool? retain_graph=None, bool create_graph=False) -> ()
+ manual_cpp_binding: True
+ variants: method
+
+# DEPRECATED. Sets the tensor data held by this `Variable` to be the same as
+# `new_data`. It requires that `new_data` and `Variable` have compatible tensor
+# type, by checking `_has_compatible_shallow_copy_type(this, new_data)`.
+#
+# This function is deprecated because it doesn't really make sense in a world
+# where Variables *are* Tensors (as opposed to them containing tensors, which
+# is what the previous interpretation was.)
+- func: set_data(Tensor(a!) self, Tensor new_data) -> ()
+ manual_cpp_binding: True
+ variants: method
+
+- func: data(Tensor self) -> Tensor
+ manual_cpp_binding: True
+ variants: method
+
+# True if this `Variable` is a leaf and thus does not have a `grad_fn`.
+- func: is_leaf(Tensor self) -> bool
+ manual_cpp_binding: True
+ variants: method
+
+# Returns the output index of this variable from the forward operation that
+# produced it. Conversely, it returns the input index of the gradient `Node` to
+# which this `Variable` is connected (because in the gradient computation,
+# inputs and outputs switch meaning). For example:
+#
+# y0, y1, y2 = f(x)
+# assert y0.output_nr == 0
+# assert y1.output_nr == 1
+# assert y2.output_nr == 2
+#
+- func: output_nr(Tensor self) -> int
+ manual_cpp_binding: True
+ variants: method
+
+- func: _version(Tensor self) -> int
+ manual_cpp_binding: True
+ variants: method
+
+- func: requires_grad_(Tensor(a!) self, bool requires_grad=True) -> Tensor(a!)
+ manual_cpp_binding: True
+ variants: method
+
+# Enables .grad attribute for non-leaf Tensors.
+- func: retain_grad(Tensor(a!) self) -> ()
+ manual_cpp_binding: True
+ variants: method
+
+- func: retains_grad(Tensor self) -> bool
+ manual_cpp_binding: True
+ variants: method
+
+- func: _fw_primal(Tensor(a) self, int level) -> Tensor(a)
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: _fw_primal
+
+- func: _make_dual(Tensor(a) primal, Tensor tangent, int level) -> Tensor(a)
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _make_dual
+
+- func: _unpack_dual(Tensor(a) dual, int level) -> (Tensor(a) primal, Tensor tangent)
+ variants: function
+
+# NOTE: [_new_zeros_with_same_feature_meta]
+# This function creates a new tensor with the layout and TensorOptions
+# of `other` but also takes into account the batch dimensions of `self`
+#
+# This function has a couple extra constraints because it is also used for `jvp`
+# in functorch.
+# - is used for forward AD because there is the restriction
+# that the primal and tangent must have the same layout
+# - We cannot assume that `self` and `other` have the same sizes or even dim
+# because in the inplace over view case, `other` is the base tensor, and
+# `self` is the forward grad with respect to the view, which can have an
+# entirely different shape
+# - takes the number of batch dims for `self` because we also handle
+# some batching logic. We handle that here instead of a batching rule because
+# we'd like to avoid calling as_strided in the batching rule (as to enable
+# nested vmap in functorch).
+# - needs to be CompositeExplicitAutograd for jvp support in functorch.
+# functorch currently relies on TensorWrapper which does not have storage
+# CompositeExplicitAutograd makes sure the TensorWrapper is unwrapped.
+# - this function may eventually take on another int argument to store the
+# the number of batch dims for other once we support that use case
+- func: _new_zeros_with_same_feature_meta(Tensor self, Tensor other, *, int self_num_batch_dims=0) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _new_zeros_with_same_feature_meta
+ autogen: _new_zeros_with_same_feature_meta.out
+
+# This function compares the storage numel of self with that of other, where
+# storage numel is computed as: `other.storage().nbytes() / other.itemsize()`.
+# We create this function for composite compliance purposes. The batching rule
+# always returns true because vmapped as_strided does not support accessing
+# storage locations not indexable by the input tensor.
+# See the note above for more information.
+- func: _has_same_storage_numel(Tensor self, Tensor other) -> bool
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _has_same_storage_numel
+
+- func: rename_(Tensor(a!) self, Dimname[]? names) -> Tensor(a!)
+ variants: method
+ tags: inplace_view
+
+- func: rename(Tensor(a) self, Dimname[]? names) -> Tensor(a)
+ variants: method
+
+- func: align_to(Tensor(a) self, Dimname[] names) -> Tensor(a)
+ variants: method
+
+- func: align_to.ellipsis_idx(Tensor(a) self, Dimname[] order, int ellipsis_idx) -> Tensor(a)
+ variants: method
+
+- func: align_as(Tensor self, Tensor other) -> Tensor
+ variants: method
+
+- func: align_tensors(Tensor[] tensors) -> Tensor[]
+
+# Not assert because it's a keyword; not Assert because FX already
+# took that syntax
+# TODO: need to specify this is side-effectful somehow
+- func: _assert_async(Tensor self) -> ()
+ dispatch:
+ CPU: _assert_async_cpu
+ CUDA: _assert_async_cuda
+
+- func: _assert_async.msg(Tensor self, str assert_msg) -> ()
+ dispatch:
+ CPU: _assert_async_msg_cpu
+ CUDA: _assert_async_msg_cuda
+
+- func: _assert_scalar(Scalar self, str assert_msg) -> ()
+ dispatch:
+ CompositeExplicitAutograd: _assert_scalar
+
+- func: _functional_assert_scalar(Scalar self, str assert_msg, Tensor dep_token) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _functional_assert_scalar
+
+- func: _functional_assert_async.msg(Tensor self, str assert_msg, Tensor dep_token) -> Tensor
+ dispatch:
+ CPU: _functional_assert_async_msg_cpu
+
+- func: _assert_tensor_metadata(Tensor a, SymInt[]? size=None, SymInt[]? stride=None, ScalarType? dtype=None, *, Device? device=None, Layout? layout=None) -> ()
+ dispatch:
+ CompositeExplicitAutograd: _assert_tensor_metadata
+ Meta: _assert_tensor_metadata_meta_symint
+
+- func: _print(str s) -> ()
+ dispatch:
+ CompositeExplicitAutograd: _print
+
+- func: sym_constrain_range(Scalar size, *, int? min=None, int? max=None) -> ()
+ dispatch:
+ CompositeExplicitAutograd: sym_constrain_range
+
+- func: sym_constrain_range_for_size(Scalar size, *, int? min=None, int? max=None) -> ()
+ dispatch:
+ CompositeExplicitAutograd: sym_constrain_range_for_size
+
+- func: _functional_sym_constrain_range(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _functional_sym_constrain_range
+
+- func: _functional_sym_constrain_range_for_size(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _functional_sym_constrain_range_for_size
+
+- func: _make_dep_token(*, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ dispatch:
+ CPU: _make_dep_token_cpu
+
+- func: refine_names(Tensor(a) self, Dimname[] names) -> Tensor(a)
+ variants: method
+
+- func: _use_cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank) -> bool
+ device_check: NoCheck # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss
+ dispatch:
+ CUDA: _use_cudnn_ctc_loss
+
+- func: _use_cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank) -> bool
+ device_check: NoCheck # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss
+ dispatch:
+ CUDA: _use_cudnn_ctc_loss_tensor
+
+- func: _cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor)
+ device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU
+ dispatch:
+ CUDA: _cudnn_ctc_loss
+ autogen: _cudnn_ctc_loss.out
+
+- func: _cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor)
+ device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU
+ dispatch:
+ CUDA: _cudnn_ctc_loss_tensor
+
+- func: _use_cudnn_rnn_flatten_weight() -> bool
+
+- func: _cudnn_rnn_flatten_weight(Tensor[] weight_arr, int weight_stride0, SymInt input_size, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, bool bidirectional) -> Tensor
+ dispatch:
+ CUDA: _cudnn_rnn_flatten_weight
+ autogen: _cudnn_rnn_flatten_weight.out
+
+- func: _cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+ # rnn_tanh may or may not redispatch to _cudnn_rnn based on algorithm and build. Thus it might hit dispatch or kernel device check.
+ # Disable dispatch time device check for consistent behavior.
+ device_check: NoCheck
+ dispatch:
+ CUDA: _cudnn_rnn
+ autogen: _cudnn_rnn.out
+ tags: nondeterministic_seeded
+
+- func: _cudnn_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[])
+ dispatch:
+ CUDA: _cudnn_rnn_backward
+ autogen: _cudnn_rnn_backward.out
+
+- func: _cudnn_init_dropout_state(float dropout, bool train, int dropout_seed, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+ dispatch:
+ CUDA: _cudnn_init_dropout_state
+ autogen: _cudnn_init_dropout_state.out
+ tags: nondeterministic_seeded
+
+- func: _debug_has_internal_overlap(Tensor self) -> int
+ variants: function
+
+- func: _fused_dropout(Tensor self, float p, Generator? generator=None) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CUDA: fused_dropout_cuda
+ tags: nondeterministic_seeded
+ autogen: _fused_dropout.out
+
+- func: _masked_scale(Tensor self, Tensor mask, float scale) -> Tensor
+ variants: function
+ dispatch:
+ CUDA: masked_scale_cuda
+ autogen: _masked_scale.out
+
+- func: native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: native_dropout_cpu
+ CUDA: native_dropout_cuda
+ NestedTensorCPU, NestedTensorCUDA: native_dropout_nested
+ tags: [nondeterministic_seeded, core]
+ autogen: native_dropout.out
+
+- func: native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor
+ dispatch:
+ CPU, NestedTensorCPU, NestedTensorCUDA: native_dropout_backward
+ CUDA: native_dropout_backward_cuda
+ autogen: native_dropout_backward.out
+ tags: pointwise
+
+- func: _sobol_engine_draw(Tensor quasi, int n, Tensor sobolstate, int dimension, int num_generated, ScalarType? dtype) -> (Tensor, Tensor)
+
+- func: _sobol_engine_ff_(Tensor(a!) self, int n, Tensor sobolstate, int dimension, int num_generated) -> Tensor(a!)
+
+- func: _sobol_engine_scramble_(Tensor(a!) self, Tensor ltm, int dimension) -> Tensor(a!)
+
+- func: _sobol_engine_initialize_state_(Tensor(a!) self, int dimension) -> Tensor(a!)
+
+- func: _reshape_from_tensor(Tensor self, Tensor shape) -> Tensor
+
+- func: _shape_as_tensor(Tensor self) -> Tensor
+
+- func: dropout(Tensor input, float p, bool train) -> Tensor
+ tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: feature_dropout(Tensor input, float p, bool train) -> Tensor
+ tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: feature_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: alpha_dropout(Tensor input, float p, bool train) -> Tensor
+ tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: feature_alpha_dropout(Tensor input, float p, bool train) -> Tensor
+ tags: [nondeterministic_seeded, maybe_aliasing_or_mutating]
+
+- func: feature_alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: abs(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: abs
+ SparseCPU, SparseCUDA: abs_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: abs_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_abs
+ tags: [core, pointwise]
+
+- func: abs_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: abs_
+ SparseCPU, SparseCUDA: abs_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: abs_sparse_csr_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_abs_
+
+- func: abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: abs_out
+ MPS: abs_out_mps
+ SparseCPU, SparseCUDA: abs_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: abs_sparse_csr_out
+ tags: pointwise
+
+# Note [Adding an alias]
+# To add an alias do the following:
+#
+# 1) Copy the original functions native_functions.yaml entry, but replace the
+# original function's name with their own and delete any dispatch
+# keys for the aliases. Specifying a dispatch key will prevent
+# autograd from recording the operations the alias performs, which
+# will stop it from "inheriting" the original operation's autograd behavior.
+# 2) Implement the corresponding functions and have them redispatch to the
+# original function.
+# 3) Add docstrings to the new function that reference the original function,
+# and document the method as usual (if it exists.)
+# (See torch/_torch_docs.py and docs/source/torch.rst if adding a function,
+# torch/_tensor_docs.py and docs/source/tensors.rst if adding a method,
+# or module-specific doc bindings (like torch/linalg/__init__.py) if
+# adding an alias in a namespace.)
+# 4) Update torch/overrides.py consistent with the original function.
+# 5) Update the alias_map in torch/csrc/jit/passes/normalize_ops.cpp.
+# 6) Add aliases argument to existing OpInfo/UnaryUfuncInfo or create new OpInfo/UnaryUfuncInfo entry
+# in op_db list in torch/testing/_internal/common_methods_invocations.py
+#
+# See torch.absolute, an alias for torch.abs, as an example.
+# Absolute, alias for abs
+
+- func: absolute(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: absolute_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: absolute.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: angle(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: angle
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: angle_sparse_csr
+ tags: pointwise
+
+- func: angle.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: angle_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: angle_sparse_csr_out
+ tags: pointwise
+
+- func: view_as_real(Tensor(a) self) -> Tensor(a)
+ variants: function
+ dispatch:
+ CPU, CUDA, MPS, Meta: view_as_real
+
+- func: view_as_complex(Tensor(a) self) -> Tensor(a)
+ variants: function
+ dispatch:
+ CPU, CUDA, MPS, Meta: view_as_complex
+
+- func: sgn(Tensor self) -> Tensor
+ variants: function, method
+ structured_delegate: sgn.out
+ dispatch:
+ SparseCPU, SparseCUDA: sgn_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sgn_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_sgn
+ tags: pointwise
+
+- func: sgn_(Tensor(a!) self) -> Tensor(a!)
+ variants: method
+ structured_delegate: sgn.out
+ dispatch:
+ SparseCPU, SparseCUDA: sgn_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sgn_sparse_csr_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_sgn_
+ tags: pointwise
+
+- func: sgn.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sgn_out
+ MPS: sgn_out_mps
+ SparseCPU, SparseCUDA: sgn_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sgn_sparse_csr_out
+ tags: pointwise
+
+- func: chalf(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor
+ variants: method
+
+- func: real(Tensor(a) self) -> Tensor(a)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: imag(Tensor(a) self) -> Tensor(a)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: _conj(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: _conj
+
+- func: conj(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+ manual_cpp_binding: True
+
+- func: _conj_physical(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: _conj_physical
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: conj_physical_sparse_csr
+ autogen: _conj_physical.out
+
+- func: conj_physical(Tensor self) -> Tensor
+ variants: function, method
+ tags: [pointwise, maybe_aliasing_or_mutating]
+
+- func: conj_physical.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: conj_physical_out
+ MPS: conj_physical_out_mps
+ SparseCPU, SparseCUDA: conj_physical_out_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: conj_physical_sparse_csr_out
+ tags: pointwise
+
+- func: conj_physical_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: conj_physical_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: conj_physical_sparse_csr_
+ tags: pointwise
+
+- func: resolve_conj(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+
+- func: resolve_neg(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+
+- func: _neg_view(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: _neg_view
+
+- func: acos(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: acos.out
+ tags: [core, pointwise]
+
+- func: acos_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: acos.out
+ tags: pointwise
+
+- func: acos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: acos_out
+ MPS: acos_out_mps
+ tags: pointwise
+
+# arccos, alias of acos
+- func: arccos(Tensor self) -> Tensor
+ variants: function, method
+
+- func: arccos_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: arccos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: avg_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, bool ceil_mode=False, bool count_include_pad=True) -> Tensor
+ tags: core
+ autogen: avg_pool1d.out
+
+- func: adaptive_avg_pool1d(Tensor self, int[1] output_size) -> Tensor
+ tags: core
+ autogen: adaptive_avg_pool1d.out
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool1d(Tensor self, int[1] output_size) -> (Tensor, Tensor)
+
+- func: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: add.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: add_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: add_sparse_csr
+ MkldnnCPU: mkldnn_add
+ ZeroTensor: add_zerotensor
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_add_Tensor
+ tags: [core, pointwise]
+
+- func: add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: add.out
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: add_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: add_sparse_csr_
+ MkldnnCPU: mkldnn_add_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_add__Tensor
+ tags: pointwise
+
+- func: add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ ufunc_inner_loop:
+ Generic: add (AllAndComplex, BFloat16, Half, ComplexHalf)
+ ScalarOnly: add (Bool)
+ dispatch:
+ SparseCPU, SparseMeta: add_out_sparse_cpu
+ SparseCUDA: add_out_sparse_cuda
+ SparseCsrCPU, SparseCsrMeta: add_out_sparse_compressed_cpu
+ SparseCsrCUDA: add_out_sparse_compressed_cuda
+ MkldnnCPU: mkldnn_add_out
+ MPS: add_out_mps
+ tags: pointwise
+
+- func: _add_relu.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+ variants: function
+ dispatch:
+ CPU: add_relu
+
+- func: _add_relu_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CPU: add_relu_
+
+- func: _add_relu.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CPU: add_relu_out
+
+- func: _add_relu.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+ variants: function
+ dispatch:
+ CPU: add_relu
+
+- func: _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CPU: add_relu_
+ autogen: _add_relu.Scalar_out
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: add
+ tags: [core, pointwise]
+
+- func: add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: add_
+ autogen: add.Scalar_out
+ tags: pointwise
+
+- func: addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ structured_delegate: addmv.out
+ variants: function, method
+
+- func: addmv_(Tensor(a!) self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+ structured_delegate: addmv.out
+ variants: function, method
+
+- func: addmv.out(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: addmv_out_cpu
+ CUDA: addmv_out_cuda
+ MPS: addmv_out_mps
+ XPU: addmv_out_xpu
+ SparseCsrCPU: addmv_out_sparse_compressed
+ SparseCsrCUDA: addmv_out_sparse_compressed_cuda
+
+- func: addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU, CUDA: addr
+ MPS: addr_mps
+ CompositeExplicitAutograd: math_addr
+
+- func: addr_(Tensor(a!) self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: addr_
+
+- func: addr.out(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: addr_out
+ MPS: addr_out_mps
+ CompositeExplicitAutograd: math_addr_out
+
+- func: affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: affine_grid_generator
+ autogen: affine_grid_generator.out
+
+- func: affine_grid_generator_backward(Tensor grad, SymInt[] size, bool align_corners) -> Tensor
+ variants: function
+
+- func: _is_all_true(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: _is_all_true
+
+- func: _is_any_true(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: _is_any_true
+
+# Note: this function is only for testing.
+- func: _test_check_tensor(Tensor self) -> Tensor
+ variants: function
+
+# Note; this function is only for testing
+- func: _test_functorch_fallback(Tensor self, Tensor other) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _test_functorch_fallback
+ autogen: _test_functorch_fallback.out
+
+- func: all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: all.out
+ variants: function, method
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_all
+
+
+- func: all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: all.dims_out
+ variants: function, method
+ cpp_no_default_args: ['dim']
+ dispatch:
+ CompositeExplicitAutograd: all_dims_default
+
+- func: all.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: all_out
+ MPS: all_out_mps
+
+- func: all.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: all_dims_out
+ CompositeExplicitAutograd: all_dims_out_default
+ cpp_no_default_args: ['dim']
+
+- func: all.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: all.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: allclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> bool
+ variants: function, method
+ tags: data_dependent_output
+ dispatch:
+ CompositeExplicitAutograd: allclose
+
+- func: any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: any.out
+ variants: function, method
+ tags: core
+
+- func: any.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: any.dims_out
+ variants: function, method
+ cpp_no_default_args: ['dim']
+ tags: core
+ dispatch:
+ CompositeExplicitAutograd: any_dims_default
+
+- func: any.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: any_out
+ MPS: any_out_mps
+
+- func: any.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: any_dims_out
+ CompositeExplicitAutograd: any_dims_out_default
+ cpp_no_default_args: ['dim']
+
+- func: any.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: any.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: arange(Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: arange
+
+- func: arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: arange
+
+# This operator should be named `arange.start_out` if following the naming convention. However that
+# name is already taken. Disabled because of CI job failures.
+# FIXME: enable this
+#- func: arange.start_out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!)
+# dispatch:
+# CompositeExplicitAutograd: arange_start_out
+
+- func: arange.start_step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: arange
+ cpp_no_default_args: ['step']
+ tags: core
+
+- func: arange.out(Scalar end, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: arange_out
+
+- func: arange.start_out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, Meta: arange_out
+ CUDA: arange_cuda_out
+ MPS: arange_mps_out
+ cpp_no_default_args: ['step']
+
+# This function is a temporary hack to allow tracing of arange like constructs with dynamic
+# bounds on arange. Normal arange is not traceable because it does not take any tensor inputs;
+# if the range you need is based on another tensor, calling this function directly will
+# preserve tracing. Get rid of this when arange can directly take tensors for bounds
+# (so that it can be traced directly).
+- func: _dim_arange(Tensor like, int dim) -> Tensor
+
+- func: argmax(Tensor self, int? dim=None, bool keepdim=False) -> Tensor
+ structured_delegate: argmax.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: core
+
+- func: argmax.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU, CUDA: argmax_out
+ MPS: argmax_out_mps
+
+- func: argmin(Tensor self, int? dim=None, bool keepdim=False) -> Tensor
+ structured_delegate: argmin.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: core
+
+- func: argmin.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU, CUDA: argmin_out
+ MPS: argmin_out_mps
+
+- func: acosh(Tensor self) -> Tensor
+ variants: function, method
+ structured_delegate: acosh.out
+ tags: [core, pointwise]
+
+- func: acosh_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+ structured_delegate: acosh.out
+ tags: pointwise
+
+- func: acosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: acosh_out
+ MPS: acosh_out_mps
+ tags: pointwise
+# arccosh, alias for acosh
+
+- func: arccosh(Tensor self) -> Tensor
+ variants: function, method
+
+- func: arccosh_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: arccosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: asinh(Tensor self) -> Tensor
+ variants: function, method
+ structured_delegate: asinh.out
+ dispatch:
+ SparseCPU, SparseCUDA: asinh_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asinh_sparse_csr
+ tags: [core, pointwise]
+
+- func: asinh_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+ structured_delegate: asinh.out
+ dispatch:
+ SparseCPU, SparseCUDA: asinh_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asinh_sparse_csr_
+ tags: pointwise
+
+- func: asinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: asinh_out
+ MPS: asinh_out_mps
+ SparseCPU, SparseCUDA: asinh_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asinh_sparse_csr_out
+ tags: pointwise
+
+# arcsinh, alias for asinh
+- func: arcsinh(Tensor self) -> Tensor
+ variants: function, method
+
+- func: arcsinh_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: arcsinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: atanh(Tensor self) -> Tensor
+ structured_delegate: atanh.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: atanh_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atanh_sparse_csr
+ tags: [core, pointwise]
+
+- func: atanh_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: atanh.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: atanh_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atanh_sparse_csr_
+ tags: pointwise
+
+- func: atanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: atanh_out
+ MPS: atanh_out_mps
+ SparseCPU, SparseCUDA: atanh_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atanh_sparse_csr_out
+ tags: pointwise
+# arctanh, alias for atanh
+
+- func: arctanh(Tensor self) -> Tensor
+ variants: function, method
+
+- func: arctanh_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: arctanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ ZeroTensor, CPU, CUDA: as_strided_tensorimpl
+ Meta: as_strided_tensorimpl_meta_symint
+ MPS: as_strided_tensorimpl_mps
+ QuantizedCPU, QuantizedCUDA: as_strided_qtensorimpl
+ device_check: NoCheck
+ device_guard: False
+ tags: core
+
+- func: as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: as_strided__symint
+
+- func: asin(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: asin.out
+ dispatch:
+ SparseCPU, SparseCUDA: asin_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asin_sparse_csr
+ tags: [core, pointwise]
+
+- func: asin_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: asin.out
+ dispatch:
+ SparseCPU, SparseCUDA: asin_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asin_sparse_csr_
+ tags: pointwise
+
+- func: asin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: asin_out
+ MPS: asin_out_mps
+ SparseCPU, SparseCUDA: asin_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: asin_sparse_csr_out
+ tags: pointwise
+
+# arcsin, alias of asin
+- func: arcsin(Tensor self) -> Tensor
+ variants: function, method
+
+- func: arcsin_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: arcsin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: atan(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: atan.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: atan_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atan_sparse_csr
+ tags: [core, pointwise]
+
+- func: atan_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: atan.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: atan_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atan_sparse_csr_
+ tags: pointwise
+
+- func: atan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: atan_out
+ MPS: atan_out_mps
+ SparseCPU, SparseCUDA: atan_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: atan_sparse_csr_out
+ tags: pointwise
+
+# arctan, alias of atan
+- func: arctan(Tensor self) -> Tensor
+ variants: function, method
+
+- func: arctan_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: arctan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: atleast_1d(Tensor self) -> Tensor
+ variants: function
+ tags: maybe_aliasing_or_mutating
+
+- func: atleast_1d.Sequence(Tensor[] tensors) -> Tensor[]
+
+- func: atleast_2d(Tensor self) -> Tensor
+ variants: function
+ tags: maybe_aliasing_or_mutating
+
+- func: atleast_2d.Sequence(Tensor[] tensors) -> Tensor[]
+ variants: function
+
+- func: atleast_3d(Tensor self) -> Tensor
+ variants: function
+ tags: maybe_aliasing_or_mutating
+
+- func: atleast_3d.Sequence(Tensor[] tensors) -> Tensor[]
+ variants: function
+
+- func: baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ variants: function, method
+ structured_delegate: baddbmm.out
+
+- func: baddbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+ variants: method
+ structured_delegate: baddbmm.out
+
+- func: baddbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU: baddbmm_out_cpu
+ CUDA: baddbmm_out_cuda
+ MPS: baddbmm_out_mps
+ XPU: baddbmm_out_xpu
+ SparseCsrCUDA: baddbmm_out_sparse_csr_cuda
+
+- func: bartlett_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: bartlett_window
+ autogen: bartlett_window.out
+
+- func: bartlett_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: bartlett_window
+ autogen: bartlett_window.periodic_out
+
+- func: batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor
+ tags: maybe_aliasing_or_mutating
+
+- func: quantized_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point) -> Tensor
+ dispatch:
+ QuantizedCPU: quantized_batch_norm
+ autogen: quantized_batch_norm.out
+
+- func: _batch_norm_impl_index(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> (Tensor, Tensor, Tensor, Tensor, int)
+ tags: maybe_aliasing_or_mutating
+
+- func: _batch_norm_impl_index_backward(int impl_index, Tensor input, Tensor grad_output, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var_transform, bool train, float eps, bool[3] output_mask, Tensor reservedSpace) -> (Tensor, Tensor, Tensor)
+
+# Sample bernoulli with values in `self` as probability.
+- func: bernoulli(Tensor self, *, Generator? generator=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: bernoulli
+ tags: nondeterministic_seeded
+
+- func: bernoulli.out(Tensor self, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: bernoulli_out
+ MPS: bernoulli_out_mps
+
+- func: bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: bernoulli_
+ MPS: bernoulli_mps_
+ autogen: bernoulli.Tensor, bernoulli.Tensor_out
+
+- func: bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: bernoulli_
+ MPS: bernoulli_mps_
+ autogen: bernoulli.float_out
+
+# Note [bernoulli.p schema]
+# We should probably just fix the overload ambiguity by appending a _functional to the C++ API name (BC breaking)
+# This out-of-place version isn't used explicitly, but needed by jit.
+# There is no default valid on `p` here because it would introduce ambiguity
+# with `bernoulli(Tensor self, *, Generator? generator=None)` declaration.
+- func: bernoulli.p(Tensor self, float p, *, Generator? generator=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: bernoulli
+
+- func: bilinear(Tensor input1, Tensor input2, Tensor weight, Tensor? bias=None) -> Tensor
+
+- func: binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ variants: function
+ dispatch:
+ CPU: binary_cross_entropy_cpu
+ CUDA: binary_cross_entropy_cuda
+ MPS: binary_cross_entropy_mps
+
+- func: binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ variants: function
+ dispatch:
+ CPU: binary_cross_entropy_out_cpu
+ CUDA: binary_cross_entropy_out_cuda
+ MPS: binary_cross_entropy_out_mps
+
+- func: binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
+ python_module: nn
+ variants: function
+ dispatch:
+ CPU: binary_cross_entropy_backward_cpu
+ CUDA: binary_cross_entropy_backward_cuda
+ MPS: binary_cross_entropy_backward_mps
+
+- func: binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ variants: function
+ dispatch:
+ CPU: binary_cross_entropy_backward_out_cpu
+ CUDA: binary_cross_entropy_backward_out_cuda
+ MPS: binary_cross_entropy_backward_out_mps
+
+- func: binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: binary_cross_entropy_with_logits
+ autogen: binary_cross_entropy_with_logits.out
+
+- func: bincount(Tensor self, Tensor? weights=None, int minlength=0) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: _bincount_cpu
+ CUDA: _bincount_cuda
+ MPS: _bincount_mps
+ tags: dynamic_output_shape
+ autogen: bincount.out
+
+- func: bitwise_not(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: bitwise_not.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: bitwise_not_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: bitwise_not.out
+ variants: method
+ tags: pointwise
+
+- func: bitwise_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: bitwise_not_out
+ MPS: bitwise_not_out_mps
+ tags: pointwise
+
+- func: copysign.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: copysign_out
+ tags: pointwise
+
+- func: copysign.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: copysign.out
+ tags: pointwise
+
+- func: copysign_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: copysign.out
+
+- func: copysign.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: copysign
+ tags: pointwise
+
+- func: copysign_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: copysign_
+
+- func: copysign.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: copysign_out
+ tags: pointwise
+
+- func: _lazy_clone(Tensor self) -> Tensor
+ # Like clone, but the copy takes place lazily, only if either the
+ # input or the output are written.
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: _lazy_clone
+
+- func: logical_not(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: logical_not
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_logical_not
+ tags: [core, pointwise]
+
+- func: logical_not_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: logical_not_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_logical_not_
+ tags: pointwise
+
+- func: logical_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: logical_not_out
+ MPS: logical_not_out_mps
+ tags: pointwise
+
+- func: logical_xor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: logical_xor
+ tags: [core, pointwise]
+
+- func: logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: logical_xor_
+ tags: pointwise
+
+- func: logical_xor.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: logical_xor_out
+ MPS: logical_xor_out_mps
+ tags: pointwise
+
+- func: logical_and(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: logical_and
+ tags: [core, pointwise]
+
+- func: logical_and_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: logical_and_
+ tags: pointwise
+
+- func: logical_and.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: logical_and_out
+ MPS: logical_and_out_mps
+ tags: pointwise
+
+- func: logical_or(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: logical_or
+ tags: [core, pointwise]
+
+- func: logical_or_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: logical_or_
+ tags: pointwise
+
+- func: logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: logical_or_out
+ MPS: logical_or_out_mps
+ tags: pointwise
+
+- func: blackman_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: blackman_window
+ autogen: blackman_window.out
+
+- func: blackman_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: blackman_window
+ autogen: blackman_window.periodic_out
+
+- func: bmm(Tensor self, Tensor mat2) -> Tensor
+ structured_delegate: bmm.out
+ variants: function, method
+ dispatch:
+ SparseCPU: bmm_sparse_cpu
+ SparseCUDA: bmm_sparse_cuda
+ NestedTensorCPU: bmm_nested
+ NestedTensorCUDA: bmm_nested_cuda
+ tags: core
+
+- func: bmm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU: bmm_out_cpu
+ CUDA: bmm_out_cuda
+ MPS: bmm_out_mps
+ XPU: bmm_out_xpu
+ SparseCPU: bmm_out_sparse_cpu
+ SparseCUDA: bmm_out_sparse_cuda
+ SparseCsrCUDA: bmm_out_sparse_csr_cuda
+
+- func: broadcast_tensors(Tensor[] tensors) -> Tensor[]
+ device_check: NoCheck
+ device_guard: False
+
+- func: broadcast_to(Tensor(a) self, SymInt[] size) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: broadcast_to_symint
+
+- func: _sparse_broadcast_to(Tensor(a) self, int[] size) -> Tensor(a)
+ variants: function
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_broadcast_to
+
+- func: cat(Tensor[] tensors, int dim=0) -> Tensor
+ structured_delegate: cat.out
+ dispatch:
+ SparseCPU, SparseCUDA: cat_sparse
+ QuantizedCPU: cat_quantized_cpu
+ NestedTensorCPU, NestedTensorCUDA: cat_nested
+ tags: core
+
+- func: cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ precomputed:
+ - dim -> int dim, int valid, bool all_contiguous, bool all_same_dtype, bool all_same_sizes_and_stride, MemoryFormat memory_format
+ dispatch:
+ CPU: cat_out_cpu
+ CUDA: cat_out_cuda
+ MPS: cat_out_mps
+ QuantizedCPU: cat_out_quantized_cpu
+
+- func: cat.names(Tensor[] tensors, Dimname dim) -> Tensor
+
+- func: cat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+# alias for torch.cat
+- func: concat(Tensor[] tensors, int dim=0) -> Tensor
+
+- func: concat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: concat.names(Tensor[] tensors, Dimname dim) -> Tensor
+
+- func: concat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+# alias for torch.cat
+- func: concatenate(Tensor[] tensors, int dim=0) -> Tensor
+
+- func: concatenate.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: concatenate.names(Tensor[] tensors, Dimname dim) -> Tensor
+
+- func: concatenate.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: block_diag(Tensor[] tensors) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: block_diag
+ autogen: block_diag.out
+
+- func: ceil(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: ceil.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: ceil_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ceil_sparse_csr
+ tags: [core, pointwise]
+
+- func: ceil_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: ceil.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: ceil_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ceil_sparse_csr_
+ tags: pointwise
+
+- func: ceil.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: ceil_out
+ MPS: ceil_out_mps
+ SparseCPU, SparseCUDA: ceil_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ceil_sparse_csr_out
+ tags: pointwise
+
+# alias for torch.linalg.multi_dot
+- func: chain_matmul(Tensor[] matrices) -> Tensor
+ variants: function
+
+# alias for torch.linalg.multi_dot
+- func: chain_matmul.out(Tensor[] matrices, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: unsafe_chunk(Tensor self, int chunks, int dim=0) -> Tensor[]
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ tags: maybe_aliasing_or_mutating
+
+- func: chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: chunk
+ NestedTensorCPU, NestedTensorCUDA: chunk_nested_tensor
+
+- func: tensor_split.sections(Tensor(a -> *) self, SymInt sections, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: tensor_split_sections_symint
+
+- func: tensor_split.indices(Tensor(a -> *) self, SymInt[] indices, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: tensor_split_indices_symint
+
+- func: tensor_split.tensor_indices_or_sections(Tensor(a -> *) self, Tensor tensor_indices_or_sections, int dim=0) -> Tensor(a)[]
+ variants: function, method
+
+- func: clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ['min']
+ structured_delegate: clamp.out
+ dispatch:
+ QuantizedCPU: clamp_quantized_cpu
+ tags: [core, pointwise]
+
+- func: clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor
+ variants: function, method
+ structured_delegate: clamp.Tensor_out
+ tags: [core, pointwise]
+
+- func: clamp_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ['min']
+ structured_delegate: clamp.out
+ tags: pointwise
+
+- func: clamp_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!)
+ variants: function, method
+ structured_delegate: clamp.Tensor_out
+ tags: pointwise
+
+- func: clamp.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ cpp_no_default_args: ['min']
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: clamp_out
+ MPS: clamp_out_mps
+ tags: pointwise
+
+- func: clamp.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: clamp_Tensor_out
+ MPS: clamp_Tensor_out_mps
+ tags: pointwise
+
+- func: clamp_max(Tensor self, Scalar max) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: clamp_max.out
+ tags: pointwise
+
+- func: clamp_max.Tensor(Tensor self, Tensor max) -> Tensor
+ variants: function, method
+ structured_delegate: clamp_max.Tensor_out
+ tags: pointwise
+
+- func: clamp_max_(Tensor(a!) self, Scalar max) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: clamp_max.out
+ tags: pointwise
+
+- func: clamp_max_.Tensor(Tensor(a!) self, Tensor max) -> Tensor(a!)
+ variants: function, method
+ structured_delegate: clamp_max.Tensor_out
+ tags: pointwise
+
+- func: clamp_max.out(Tensor self, Scalar max, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: clamp_max_out
+ MPS: clamp_max_out_mps
+ tags: pointwise
+
+- func: clamp_max.Tensor_out(Tensor self, Tensor max, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: clamp_max_Tensor_out
+ MPS: clamp_max_Tensor_out_mps
+ tags: pointwise
+
+- func: clamp_min(Tensor self, Scalar min) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: clamp_min.out
+ tags: pointwise
+
+- func: clamp_min.Tensor(Tensor self, Tensor min) -> Tensor
+ variants: function, method
+ structured_delegate: clamp_min.Tensor_out
+ tags: pointwise
+
+- func: clamp_min_(Tensor(a!) self, Scalar min) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: clamp_min.out
+ tags: pointwise
+
+- func: clamp_min_.Tensor(Tensor(a!) self, Tensor min) -> Tensor(a!)
+ variants: function, method
+ structured_delegate: clamp_min.Tensor_out
+ tags: pointwise
+
+- func: clamp_min.out(Tensor self, Scalar min, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: clamp_min_out
+ MPS: clamp_min_out_mps
+ tags: pointwise
+
+- func: clamp_min.Tensor_out(Tensor self, Tensor min, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: clamp_min_Tensor_out
+ MPS: clamp_min_Tensor_out_mps
+ tags: pointwise
+
+# clip is an alias for clamp
+- func: clip(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor
+ cpp_no_default_args: ['min']
+ variants: function, method
+ tags: pointwise
+
+- func: clip.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor
+ variants: function, method
+ tags: pointwise
+
+- func: clip_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!)
+ cpp_no_default_args: ['min']
+ variants: function, method
+ tags: pointwise
+
+- func: clip_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!)
+ variants: function, method
+ tags: pointwise
+
+- func: clip.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!)
+ cpp_no_default_args: ['min']
+ tags: pointwise
+
+- func: clip.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: cudnn_is_acceptable(Tensor self) -> bool
+ device_check: NoCheck
+ device_guard: False
+
+- func: complex(Tensor real, Tensor imag) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: complex
+
+- func: complex.out(Tensor real, Tensor imag, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: complex_out
+ MPS: complex_out_mps
+
+- func: polar(Tensor abs, Tensor angle) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: polar
+
+- func: polar.out(Tensor abs, Tensor angle, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: polar_out
+ MPS: polar_out_mps
+
+- func: constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: constant_pad_nd
+ MPS: constant_pad_nd_mps
+ autogen: constant_pad_nd.out
+ tags: core
+
+- func: contiguous(Tensor(a) self, *, MemoryFormat memory_format=contiguous_format) -> Tensor(a)
+ variants: method
+ manual_cpp_binding: True
+
+- func: convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: convolution
+ autogen: convolution.out
+ tags: core
+
+- func: convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CompositeExplicitAutograd, CUDA: convolution_backward
+ autogen: convolution_backward.out
+ tags: core
+
+- func: convolution_overrideable(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: convolution_overrideable
+ autogen: convolution_overrideable.out
+
+- func: convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+ dispatch:
+ CompositeExplicitAutograd: convolution_backward_overrideable
+ autogen: convolution_backward_overrideable.out
+
+- func: _convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _convolution
+ autogen: _convolution.out
+
+- func: _convolution.deprecated(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, int[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled) -> Tensor
+
+- func: _convolution_mode(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, str padding, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: _convolution_mode_symint
+
+- func: _convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor gO, Tensor weight, Tensor self, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+
+- func: conv1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] dilation=1, SymInt groups=1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: conv1d_symint
+
+- func: conv2d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1, SymInt groups=1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: conv2d_symint
+
+- func: conv3d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1, SymInt groups=1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: conv3d_symint
+
+- func: conv1d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, str padding="valid", SymInt[1] dilation=1, SymInt groups=1) -> Tensor
+ cpp_no_default_args: ['bias', 'stride', 'padding']
+ dispatch:
+ CompositeImplicitAutograd: conv1d_padding_symint
+
+- func: conv2d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, str padding="valid", SymInt[2] dilation=1, SymInt groups=1) -> Tensor
+ cpp_no_default_args: ['bias', 'stride', 'padding']
+ dispatch:
+ CompositeImplicitAutograd: conv2d_padding_symint
+
+- func: conv3d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, str padding="valid", SymInt[3] dilation=1, SymInt groups=1) -> Tensor
+ cpp_no_default_args: ['bias', 'stride', 'padding']
+ dispatch:
+ CompositeImplicitAutograd: conv3d_padding_symint
+
+- func: conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad=0) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: conv_tbc
+ autogen: conv_tbc.out
+
+- func: conv_tbc_backward(Tensor self, Tensor input, Tensor weight, Tensor bias, int pad) -> (Tensor, Tensor, Tensor)
+
+# NB: we inherit the goofy argument order from PyTorch torch.nn.functional
+- func: conv_transpose1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] output_padding=0, SymInt groups=1, SymInt[1] dilation=1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: conv_transpose1d_symint
+
+- func: conv_transpose2d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt groups=1, SymInt[2] dilation=1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: conv_transpose2d_symint
+
+- func: conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt groups=1, SymInt[3] dilation=1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: conv_transpose3d_symint
+
+- func: copy(Tensor self, Tensor src, bool non_blocking=False) -> Tensor
+ variants: function
+ dispatch:
+ Meta: copy_meta
+ CompositeExplicitAutogradNonFunctional: copy
+ tags: core
+
+- func: copy_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ MkldnnCPU: copy_mkldnn_
+ SparseCPU, SparseCUDA: copy_sparse_wrapper_
+ CompositeExplicitAutograd: copy_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: copy_sparse_compressed_
+ NestedTensorCPU, NestedTensorCUDA: copy_nested_
+ autogen: copy.out
+
+- func: _copy_from(Tensor self, Tensor dst, bool non_blocking=False) -> Tensor
+ dispatch:
+ MPS: _copy_from_mps
+ autogen: _copy_from.out
+
+# We need this to be able to properly copy from a CPU to an XLA tensor with different sizes.
+# See https://github.com/pytorch/xla/issues/2881
+- func: _copy_from_and_resize(Tensor self, Tensor dst) -> Tensor
+ dispatch:
+ MPS: _copy_from_and_resize_mps
+ autogen: _copy_from_and_resize.out
+
+- func: cos(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: cos.out
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_cos
+ tags: [core, pointwise]
+
+- func: cos_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: cos.out
+ tags: pointwise
+
+- func: cos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: cos_out
+ MPS: cos_out_mps
+ tags: pointwise
+
+- func: cosh(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: cosh.out
+ tags: [core, pointwise]
+
+- func: cosh_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: cosh.out
+ tags: pointwise
+
+- func: cosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: cosh_out
+ MPS: cosh_out_mps
+ tags: pointwise
+
+- func: cosine_embedding_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor
+
+- func: count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: count_nonzero_cpu
+ CUDA: count_nonzero_cuda
+ MPS: count_nonzero_mps
+ autogen: count_nonzero.dim_IntList_out
+
+- func: count_nonzero(Tensor self, int? dim=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: count_nonzero
+ autogen: count_nonzero.out
+
+- func: cov(Tensor self, *, int correction=1, Tensor? fweights=None, Tensor? aweights=None) -> Tensor
+ variants: function, method
+
+- func: corrcoef(Tensor self) -> Tensor
+ variants: function, method
+
+- func: cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid
+ dispatch:
+ CUDA: cudnn_affine_grid_generator_forward
+ autogen: cudnn_affine_grid_generator.out
+
+# TODO: Why do I have to call this grad?!
+- func: cudnn_affine_grid_generator_backward(Tensor grad, int N, int C, int H, int W) -> Tensor grad_theta
+ dispatch:
+ CUDA: cudnn_affine_grid_generator_backward
+ autogen: cudnn_affine_grid_generator_backward.out
+
+- func: cudnn_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: cudnn_batch_norm
+ autogen: cudnn_batch_norm.out
+
+# NB: You can only use this if you used cudnn_batch_norm training=True
+- func: cudnn_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon, Tensor reserveSpace) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: cudnn_batch_norm_backward
+ autogen: cudnn_batch_norm_backward.out
+
+- func: cudnn_convolution(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor
+ dispatch:
+ CUDA: cudnn_convolution
+
+- func: cudnn_convolution.out(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CUDA: cudnn_convolution_out
+
+- func: cudnn_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor
+ dispatch:
+ CUDA: cudnn_convolution_transpose
+ autogen: cudnn_convolution_transpose.out
+
+- func: _mps_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ MPS: _mps_convolution_transpose
+ autogen: _mps_convolution_transpose.out
+
+- func: mps_convolution_transpose_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[2] output_mask) -> (Tensor, Tensor)
+ dispatch:
+ MPS: mps_convolution_transpose_backward
+ autogen: mps_convolution_transpose_backward.out
+
+- func: cudnn_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ CUDA: cudnn_convolution_relu
+ autogen: cudnn_convolution_relu.out
+
+- func: cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ CUDA: cudnn_convolution_add_relu
+ autogen: cudnn_convolution_add_relu.out
+
+# NB: input is special cased in a way I don't quite understand
+- func: cudnn_grid_sampler(Tensor self, Tensor grid) -> Tensor output
+ dispatch:
+ CUDA: cudnn_grid_sampler_forward
+ autogen: cudnn_grid_sampler.out
+
+- func: cudnn_grid_sampler_backward(Tensor self, Tensor grid, Tensor grad_output) -> (Tensor grad_self, Tensor grad_grid)
+ dispatch:
+ CUDA: cudnn_grid_sampler_backward
+ autogen: cudnn_grid_sampler_backward.out
+
+- func: cummax(Tensor self, int dim) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: cummax
+
+- func: cummax.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: cummax_out
+
+- func: cummax.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: cummax.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+
+- func: _cummax_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
+ variants: function
+ dispatch:
+ CPU: cummax_helper_cpu
+ CUDA: cummax_helper_cuda
+
+- func: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: cummin
+
+- func: cummin.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: cummin_out
+
+- func: cummin.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: cummin.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+
+- func: _cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
+ variants: function
+ dispatch:
+ CPU: cummin_helper_cpu
+ CUDA: cummin_helper_cuda
+
+- func: cummaxmin_backward(Tensor grad, Tensor input, Tensor indices, int dim) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+
+- func: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+ structured_delegate: cumprod.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: cumprod_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!)
+ structured_delegate: cumprod.out
+ variants: method
+
+- func: cumprod.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: cumprod_out
+ MPS: cumprod_out_mps
+
+- func: cumprod.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: cumprod_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!)
+ variants: method
+
+- func: cumprod.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: cumprod_backward(Tensor grad, Tensor input, int dim, Tensor output) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+
+- func: cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+ structured_delegate: cumsum.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: core
+
+- func: cumsum_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!)
+ structured_delegate: cumsum.out
+ variants: method
+
+- func: cumsum.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: cumsum_out
+ MPS: cumsum_out_mps
+
+- func: cumsum.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: cumsum_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!)
+ variants: method
+
+- func: cumsum.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: cumulative_trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
+
+- func: cumulative_trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor
+
+- func: ctc_loss.IntList(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor
+
+# convenience function that converts to intlists for you
+- func: ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor
+
+- func: _ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)
+ dispatch:
+ CPU: ctc_loss_cpu
+ CUDA: ctc_loss_gpu
+ Meta: ctc_loss_meta
+ autogen: _ctc_loss.out
+ tags: dynamic_output_shape # the shape of second output is data dependent
+
+- func: _ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor)
+ dispatch:
+ CPU, CUDA: ctc_loss_tensor
+ autogen: _ctc_loss.Tensor_out
+ tags: dynamic_output_shape # the shape of second output is data dependent
+
+- func: _ctc_loss_backward(Tensor grad, Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, Tensor neg_log_likelihood, Tensor log_alpha, int blank, bool zero_infinity=False) -> Tensor
+ dispatch:
+ CPU: ctc_loss_backward_cpu
+ CUDA: ctc_loss_backward_gpu
+ autogen: _ctc_loss_backward.out
+
+- func: _ctc_loss_backward.Tensor(Tensor grad, Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, Tensor neg_log_likelihood, Tensor log_alpha, int blank, bool zero_infinity=False) -> Tensor
+ dispatch:
+ CPU, CUDA: ctc_loss_backward_tensor
+
+- func: diag_embed(Tensor self, int offset=0, int dim1=-2, int dim2=-1) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: diag_embed
+ autogen: diag_embed.out
+
+- func: diagflat(Tensor self, int offset=0) -> Tensor
+ variants: function, method
+
+- func: diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: diagonal
+ tags: core
+
+- func: linalg_diagonal(Tensor(a) A, *, int offset=0, int dim1=-2, int dim2=-1) -> Tensor(a)
+ python_module: linalg
+ variants: function
+
+- func: diagonal.Dimname(Tensor(a) self, *, Dimname outdim, Dimname dim1, Dimname dim2, int offset=0) -> Tensor(a)
+ variants: function, method
+
+- func: diagonal_backward(Tensor grad_output, SymInt[] input_sizes, int offset, int dim1, int dim2) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: diagonal_backward_symint
+ autogen: diagonal_backward.out
+
+- func: fill_diagonal_(Tensor(a!) self, Scalar fill_value, bool wrap=False) -> Tensor(a!)
+ variants: method
+
+- func: diff(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None) -> Tensor
+ variants: function, method
+
+- func: diff.out(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+
+- func: gradient.scalarint(Tensor self, *, Scalar? spacing=None, int? dim=None, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: gradient.scalararray(Tensor self, *, Scalar spacing, int[] dim, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: gradient.array(Tensor self, *, int[] dim, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: gradient.scalarrayint(Tensor self, *, Scalar[] spacing, int? dim=None, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: gradient.scalarrayarray(Tensor self, *, Scalar[] spacing, int[] dim, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: gradient.tensorarrayint(Tensor self, *, Tensor[] spacing, int? dim=None, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: gradient.tensorarray(Tensor self, *, Tensor[] spacing, int[] dim, int edge_order=1) -> Tensor[]
+ variants: function
+
+- func: div.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: div.out
+ dispatch:
+ SparseCPU, SparseCUDA: div_sparse
+ ZeroTensor: div_zerotensor
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_div_Tensor
+ tags: [core, pointwise]
+
+- func: div_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: div.out
+ dispatch:
+ SparseCPU, SparseCUDA: div_sparse_
+ tags: pointwise
+
+- func: div.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: div_out
+ MPS: div_out_mps
+ SparseCPU, SparseCUDA: div_out_sparse_zerodim
+ tags: pointwise
+
+- func: div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: div.out_mode
+ dispatch:
+ SparseCPU, SparseCUDA: div_sparse
+ tags: [core, pointwise]
+
+- func: div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: div.out_mode
+ dispatch:
+ SparseCPU, SparseCUDA: div_sparse_
+ tags: pointwise
+
+- func: div.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: div_out_mode
+ MPS: div_out_mode_mps
+ SparseCPU, SparseCUDA: div_out_sparse_zerodim
+ tags: pointwise
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: div.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: div
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_div_Scalar
+ tags: [core, pointwise]
+
+- func: div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: div_
+ autogen: div.Scalar_out
+ tags: pointwise
+
+- func: div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: div
+ tags: [core, pointwise]
+
+- func: div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: div_
+ autogen: div.Scalar_mode_out
+ tags: pointwise
+
+# divide, alias for div
+- func: divide.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+
+- func: divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: divide.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: function, method
+
+- func: divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: divide.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor
+ variants: function, method
+
+- func: divide_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!)
+ variants: method
+
+- func: divide.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!)
+
+- func: divide.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor
+ variants: function, method
+
+- func: divide_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!)
+ variants: method
+
+ # true_divide, an alias for div
+- func: true_divide.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: pointwise
+
+- func: true_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: true_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: true_divide.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: true_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: dot(Tensor self, Tensor tensor) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: dot
+ CUDA: dot_cuda
+ MPS: dot_mps
+
+- func: dot.out(Tensor self, Tensor tensor, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: dot_out
+
+- func: vdot(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: vdot
+ CUDA: vdot_cuda
+
+- func: vdot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: vdot_out
+
+- func: einsum(str equation, Tensor[] tensors, *, int[]? path=None) -> Tensor
+
+- func: embedding(Tensor weight, Tensor indices, SymInt padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: embedding_symint
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_embedding
+ autogen: embedding.out
+ tags: core
+
+- func: embedding_backward(Tensor grad, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq, bool sparse) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: embedding_backward_symint
+
+- func: embedding_dense_backward(Tensor grad_output, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq) -> Tensor
+ dispatch:
+ CPU: embedding_dense_backward_cpu
+ CUDA: embedding_dense_backward_cuda
+ MPS: embedding_dense_backward_mps
+ autogen: embedding_dense_backward.out
+ tags: core
+
+- func: embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!)
+ dispatch:
+ CPU: embedding_renorm_cpu_
+ CUDA: embedding_renorm_cuda_
+ autogen: embedding_renorm, embedding_renorm.out
+
+- func: embedding_sparse_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq) -> Tensor
+
+# NOTE [ embedding_bag Native Functions ]
+# The `_embedding_bag.*` variants assume that input tensors except for `weight`,
+# e.g. `indices` and `offsets` (and `offset2bag`), are contiguous.
+# We really only need to enforce this for `_embedding_bag` (the forward) because
+# the backward inputs are the same as forward ones.
+# The above `embedding_bag` wrapper is created to achieve this, e.g.,
+# applying indices = indices.contiguous().
+# The backward functions apply a check that these input tensors are contiguous.
+
+
+- func: _embedding_bag_forward_only(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: _embedding_bag_forward_only_cpu
+ CUDA: _embedding_bag_forward_only_cuda
+ autogen: _embedding_bag_forward_only.out
+
+- func: _rowwise_prune(Tensor weight, Tensor mask, ScalarType compressed_indices_dtype) -> (Tensor, Tensor)
+
+# row_stack is the alias of vstack
+- func: row_stack(Tensor[] tensors) -> Tensor
+
+- func: row_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor, Tensor)
+
+# To keep backward and forward compatibility, and to avoid ambiguity with the
+# original signature above, scale_grad_by_freq, mode, sparse,
+# per_sample_weights, and include_last_offset parameters do not have default
+# values. Once the original signature is removed, default values can be added.
+- func: embedding_bag.padding_idx(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, bool include_last_offset, int? padding_idx) -> (Tensor, Tensor, Tensor, Tensor)
+
+- func: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: _embedding_bag_cpu
+ CUDA: _embedding_bag_cuda
+ autogen: _embedding_bag.out
+ tags: core
+
+- func: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+ dispatch:
+ CPU, CUDA: _embedding_bag_backward_symint
+
+- func: _embedding_bag_sparse_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: _embedding_bag_sparse_backward_symint
+
+- func: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor
+ dispatch:
+ CPU: _embedding_bag_dense_backward_cpu
+ CUDA: _embedding_bag_dense_backward_cuda
+ autogen: _embedding_bag_dense_backward.out
+
+- func: _embedding_bag_per_sample_weights_backward(Tensor grad, Tensor weight, Tensor indices, Tensor offsets, Tensor offset2bag, int mode, int padding_idx=-1) -> Tensor
+ dispatch:
+ CPU: _embedding_bag_per_sample_weights_backward_cpu
+ CUDA: _embedding_bag_per_sample_weights_backward_cuda
+ autogen: _embedding_bag_per_sample_weights_backward.out
+
+- func: empty.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: empty_names
+ autogen: empty.names_out
+
+- func: empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ dispatch:
+ CPU: empty_cpu
+ CUDA: empty_cuda
+ MPS: empty_mps
+ Meta: empty_meta_symint
+ MkldnnCPU: empty_mkldnn
+ SparseCPU, SparseCUDA: empty_sparse
+ SparseMeta: empty_sparse_symint
+ SparseCsrCPU, SparseCsrCUDA: empty_sparse_compressed
+ SparseCsrMeta: empty_sparse_compressed_symint
+ QuantizedCPU, QuantizedCUDA, QuantizedMeta: empty_unknown_quantized
+ tags: core
+
+- func: empty_permuted(SymInt[] size, int[] physical_layout, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: empty_permuted_symint
+ autogen: empty_permuted.out
+
+# We do not make new_empty a composite that calls into new_empty_strided, as the strided version
+# is significantly more difficult to implement by different backends
+- func: new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: new_empty_symint
+ autogen: new_empty.out
+
+- func: new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ variants: method
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: new_empty_strided_symint
+ autogen: new_empty_strided.out
+
+- func: new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ variants: method
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: new_full
+ autogen: new_full.out
+
+- func: new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ variants: method
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: new_zeros
+ autogen: new_zeros.out
+
+- func: new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ variants: method
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: new_ones
+ autogen: new_ones.out
+
+# other overrides are to provide a more helpful error message that dtype is required
+- func: _empty_affine_quantized(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, float scale=1, int zero_point=0, MemoryFormat? memory_format=contiguous_format) -> Tensor
+ dispatch:
+ CPU: empty_affine_quantized_other_backends_stub
+ QuantizedCPU, QuantizedCUDA: empty_affine_quantized
+ autogen: _empty_affine_quantized.out
+
+# it's a factory function receiving a tensor argument, thus overriding explicitly
+# other overrides are to provide a more helpful error message that dtype is required
+- func: _empty_per_channel_affine_quantized(SymInt[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor
+ category_override: factory
+ dispatch:
+ CPU: empty_per_channel_affine_quantized_other_backends_stub
+ QuantizedCPU, QuantizedCUDA: empty_per_channel_affine_quantized
+ autogen: _empty_per_channel_affine_quantized.out
+
+- func: resize_(Tensor(a!) self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: [core, inplace_view]
+ dispatch:
+ Meta: resize__symint
+ CPU: resize_
+ CUDA: resize_cuda_
+ MPS: resize_mps_
+ QuantizedCPU: quantized_resize_cpu_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: resize_sparse_csr_
+ autogen: resize, resize.out
+
+# This is a utility function to enable users to resize out tensor while registering kernels for out variants.
+# Eventually, we can consider exposing `resize_output` as a public API to ship it with python op registration
+# to make it easy to register out variants for ops.
+- func: _resize_output_(Tensor(a!) self, SymInt[] size, Device device) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: function
+ dispatch:
+ Meta: _resize_output_
+ autogen: _resize_output, _resize_output.out
+
+- func: empty_quantized(int[] size, Tensor qtensor, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ category_override: factory
+ variants: function
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: empty_quantized
+ autogen: empty_quantized.out
+
+- func: empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ device_guard: False
+
+- func: empty_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: empty_like
+ QuantizedCPU, QuantizedCUDA: empty_like_quantized
+ SparseCPU, SparseCUDA, SparseMeta: empty_like_sparse_coo
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: empty_like_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: empty_like_nested
+ autogen: empty_like.out
+
+- func: empty_strided(SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CPU: empty_strided_cpu
+ CUDA: empty_strided_cuda
+ MPS: empty_strided_mps
+ Meta: empty_strided_meta_symint
+ QuantizedCPU, QuantizedCUDA: empty_strided_unknown_quantized
+ autogen: empty_strided.out
+ tags: core
+
+- func: erf(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: erf.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: erf_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erf_sparse_csr
+ tags: [core, pointwise]
+
+- func: erf_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: erf.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: erf_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erf_sparse_csr_
+ tags: pointwise
+
+- func: erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: erf_out
+ MPS: erf_out_mps
+ SparseCPU, SparseCUDA: erf_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erf_sparse_csr_out
+ tags: pointwise
+
+- func: erfc(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: erfc.out
+ variants: function, method
+ tags: pointwise
+
+- func: erfc_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: erfc.out
+ variants: function, method
+ tags: pointwise
+
+- func: erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: erfc_out
+ tags: pointwise
+
+- func: exp(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: exp.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: exp_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: exp.out
+ variants: function, method
+ tags: pointwise
+
+- func: exp.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: exp_out
+ MPS: exp_out_mps
+ tags: pointwise
+
+- func: exp2(Tensor self) -> Tensor
+ structured_delegate: exp2.out
+ variants: function, method
+ tags: pointwise
+
+- func: exp2_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: exp2.out
+ variants: function, method
+ tags: pointwise
+
+- func: exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: exp2_out
+ MPS: exp2_out_mps
+ tags: pointwise
+
+- func: expm1(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: expm1.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: expm1_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: expm1_sparse_csr
+ tags: [core, pointwise]
+
+- func: expm1_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: expm1.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: expm1_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: expm1_sparse_csr_
+ tags: pointwise
+
+- func: expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: expm1_out
+ MPS: expm1_out_mps
+ SparseCPU, SparseCUDA: expm1_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: expm1_sparse_csr_out
+ tags: pointwise
+
+- func: expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a)
+ variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too.
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: expand
+ tags: core
+
+- func: expand_as(Tensor(a) self, Tensor other) -> Tensor(a)
+ variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too.
+ device_check: NoCheck
+ device_guard: False
+
+# decomposes to eye.m
+- func: eye(SymInt n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: eye
+
+- func: eye.m(SymInt n, SymInt m, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: eye
+
+- func: eye.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, Meta: eye_out_cpu
+ CUDA: eye_out_cuda
+ MPS: eye_out_mps
+
+- func: eye.m_out(SymInt n, SymInt m, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, Meta: eye_out_cpu
+ CUDA: eye_out_cuda
+ MPS: eye_out_mps
+
+- func: flatten.using_ints(Tensor(a) self, int start_dim=0, int end_dim=-1) -> Tensor(a)
+ variants: function, method
+
+- func: flatten.named_out_dim(Tensor(a) self, int start_dim, int end_dim, Dimname out_dim) -> Tensor(a)
+ variants: function, method
+
+- func: flatten.using_names(Tensor(a) self, Dimname start_dim, Dimname end_dim, Dimname out_dim) -> Tensor(a)
+ variants: function, method
+
+- func: flatten.DimnameList(Tensor(a) self, Dimname[] dims, Dimname out_dim) -> Tensor(a)
+ variants: function, method
+
+- func: unflatten.int(Tensor(a) self, int dim, SymInt[] sizes) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: unflatten_symint
+
+- func: unflatten.Dimname(Tensor(a) self, Dimname dim, SymInt[] sizes, Dimname[] names) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: unflatten_dimname_symint
+
+- func: fill.Scalar(Tensor self, Scalar value) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: fill
+ tags: core
+
+- func: fill.Tensor(Tensor self, Tensor value) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: fill
+
+- func: fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: fill_
+ MPS: fill_scalar_mps
+ QuantizedCPU, QuantizedCUDA: fill_quantized_
+ Meta: fill_meta_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: fill_sparse_csr_
+ NestedTensorCPU, NestedTensorCUDA: fill_nested_
+ autogen: fill.Scalar_out
+
+- func: fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: fill_
+ MPS: fill_tensor_mps_
+ QuantizedCPU, QuantizedCUDA: fill_quantized_
+ Meta: fill_meta_
+ NestedTensorCPU, NestedTensorCUDA: fill_nested_
+ autogen: fill.Tensor_out
+
+- func: floor(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: floor.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: floor_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: floor_sparse_csr
+ tags: [core, pointwise]
+
+- func: floor_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: floor.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: floor_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: floor_sparse_csr_
+ tags: pointwise
+
+- func: floor.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: floor_out
+ MPS: floor_out_mps
+ SparseCPU, SparseCUDA: floor_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: floor_sparse_csr_out
+ tags: pointwise
+
+- func: floor_divide(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: floor_divide
+ MPS: floor_divide_mps
+ SparseCPU, SparseCUDA: floor_divide_sparse
+
+- func: floor_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU, CUDA: floor_divide_
+ MPS: floor_divide_mps_
+ SparseCPU, SparseCUDA: floor_divide_sparse_
+
+- func: floor_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: floor_divide_out
+ MPS: floor_divide_out_mps
+ SparseCPU, SparseCUDA: floor_divide_out_sparse_zerodim
+
+- func: floor_divide.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: floor_divide
+
+- func: floor_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: floor_divide_
+ autogen: floor_divide.Scalar_out
+
+- func: frac(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: frac.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: frac_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: frac_sparse_csr
+ tags: pointwise
+
+- func: frac_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: frac.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: frac_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: frac_sparse_csr_
+ tags: pointwise
+
+- func: frac.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: frac_out
+ MPS: frac_out_mps
+ SparseCPU, SparseCUDA: frac_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: frac_sparse_csr_out
+ tags: pointwise
+
+- func: full.names(int[] size, Scalar fill_value, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: full
+ autogen: full.names_out
+
+- func: full(SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: full
+ tags: core
+
+- func: full.out(SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: full_out
+
+- func: full_like(Tensor self, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: full_like
+ autogen: full_like.out
+ tags: core
+
+- func: from_file(str filename, bool? shared=None, int? size=0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CPU: from_file
+ autogen: from_file.out
+
+- func: gcd.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: gcd_out
+ tags: pointwise
+
+- func: gcd(Tensor self, Tensor other) -> Tensor
+ structured_delegate: gcd.out
+ variants: function, method
+ tags: pointwise
+
+- func: gcd_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: gcd.out
+ variants: function, method
+
+- func: lcm.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: lcm_out
+ tags: pointwise
+
+- func: lcm(Tensor self, Tensor other) -> Tensor
+ structured_delegate: lcm.out
+ variants: function, method
+ tags: pointwise
+
+- func: lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: lcm.out
+ variants: function, method
+
+# NOTE [ grid_sampler Native Functions ]
+# `grid_sampler` is _supposed to_ do all the shape checking and then dispatch to
+# one of `cudnn_grid_sampler`, `grid_sampler_2d`, or `grid_sampler_3d`, each of
+# which has the corresponding backward defined as native functions as well.
+# However, we do shape checking everywhere for now since each of the mentioned
+# functions can be called directly, which will lead to crashes otherwise.
+# See https://github.com/pytorch/pytorch/issues/73187 for more information.
+#
+# There is also _grid_sampler_2d_backward_cpu_fallback which is an
+# implementation detail of grid_sampler_2d and is only exposed here for testing
+# purposes.
+#
+# Additionally, arguments `padding_mode` and `interpolation_mode` are cast to
+# enums defined in `native/GridSampler.h`. `cudnn_grid_sampler` doesn't take in
+# `interpolation_mode` because it only supports Bilinear interpolation mode.
+# Nor does it take in `align_corners` because it only supports the mode
+# `align_corners = True`.
+- func: grid_sampler(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+
+- func: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+ dispatch:
+ CPU, QuantizedCPU: grid_sampler_2d_cpu
+ CUDA: grid_sampler_2d_cuda
+ MPS: grid_sampler_2d_mps
+ autogen: grid_sampler_2d.out
+ tags: core
+
+# `grid_sampler_2d_backward` takes in `output_mask` to optimize performance for
+# the case where `input` doesn't require gradient. Gradient for `grid` is always
+# computed (only `output_mask[0]` is checked by the implementations).
+- func: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor)
+ dispatch:
+ CPU: grid_sampler_2d_backward_cpu
+ CUDA: grid_sampler_2d_backward_cuda
+ autogen: grid_sampler_2d_backward.out
+
+# See NOTE [ grid_sample CPU fallback ]
+- func: _grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _grid_sampler_2d_cpu_fallback
+ autogen: _grid_sampler_2d_cpu_fallback.out
+
+- func: _grid_sampler_2d_cpu_fallback_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor)
+
+- func: grid_sampler_3d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
+ dispatch:
+ CPU: grid_sampler_3d_cpu
+ CUDA: grid_sampler_3d_cuda
+ autogen: grid_sampler_3d.out
+
+# `grid_sampler_3d_backward` takes in `output_mask` to optimize performance for
+# the case where `input` doesn't require gradient. Gradient for `grid` is always
+# computed (only `output_mask[0]` is checked by the implementations).
+- func: grid_sampler_3d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor)
+ dispatch:
+ CPU: grid_sampler_3d_backward_cpu
+ CUDA: grid_sampler_3d_backward_cuda
+ autogen: grid_sampler_3d_backward.out
+
+- func: hann_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: hann_window
+ autogen: hann_window.out
+
+- func: hann_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: hann_window
+ autogen: hann_window.periodic_out
+
+- func: hamming_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: hamming_window
+ autogen: hamming_window.out
+
+- func: hamming_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: hamming_window
+ autogen: hamming_window.periodic_out
+
+- func: hamming_window.periodic_alpha(int window_length, bool periodic, float alpha, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: hamming_window
+ autogen: hamming_window.periodic_alpha_out
+
+- func: hamming_window.periodic_alpha_beta(int window_length, bool periodic, float alpha, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: hamming_window
+ autogen: hamming_window.periodic_alpha_beta_out
+
+- func: kaiser_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: kaiser_window
+ autogen: kaiser_window.out
+
+- func: kaiser_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: kaiser_window
+ autogen: kaiser_window.periodic_out
+
+- func: kaiser_window.beta(int window_length, bool periodic, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: kaiser_window
+ autogen: kaiser_window.beta_out
+
+- func: hinge_embedding_loss(Tensor self, Tensor target, float margin=1.0, int reduction=Mean) -> Tensor
+
+- func: group_norm(Tensor input, int num_groups, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enabled=True) -> Tensor
+
+- func: native_group_norm(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU, CUDA: native_group_norm
+ CompositeExplicitAutograd: math_group_norm
+ autogen: native_group_norm.out
+ tags: core
+
+- func: native_group_norm_backward(Tensor grad_out, Tensor input, Tensor mean, Tensor rstd, Tensor? weight, SymInt N, SymInt C, SymInt HxW, int group, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU, CUDA: native_group_norm_backward
+ autogen: native_group_norm_backward.out
+ tags: core
+
+# Real to complex forward FFT
+- func: _fft_r2c(Tensor self, int[] dim, int normalization, bool onesided) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _fft_r2c_mkl
+ CUDA: _fft_r2c_cufft
+ MPS: _fft_r2c_mps
+
+- func: _fft_r2c.out(Tensor self, int[] dim, int normalization, bool onesided, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CPU: _fft_r2c_mkl_out
+ CUDA: _fft_r2c_cufft_out
+ MPS: _fft_r2c_mps_out
+
+# Complex to real inverse FFT
+- func: _fft_c2r(Tensor self, int[] dim, int normalization, SymInt last_dim_size) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _fft_c2r_mkl
+ CUDA: _fft_c2r_cufft
+ MPS: _fft_c2r_mps
+
+- func: _fft_c2r.out(Tensor self, int[] dim, int normalization, SymInt last_dim_size, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CPU: _fft_c2r_mkl_out
+ CUDA: _fft_c2r_cufft_out
+ MPS: _fft_c2r_mps_out
+
+# Standard complex to complex FFT (forward or backward)
+- func: _fft_c2c(Tensor self, SymInt[] dim, int normalization, bool forward) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _fft_c2c_mkl
+ CUDA: _fft_c2c_cufft
+ MPS: _fft_c2c_mps
+
+- func: _fft_c2c.out(Tensor self, SymInt[] dim, int normalization, bool forward, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CPU: _fft_c2c_mkl_out
+ CUDA: _fft_c2c_cufft_out
+ MPS: _fft_c2c_mps_out
+
+- func: _validate_compressed_sparse_indices(bool is_crow, Tensor compressed_idx, Tensor plain_idx, int cdim, int dim, int nnz) -> ()
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CPU: _validate_compressed_sparse_indices_cpu
+ CUDA: _validate_compressed_sparse_indices_cuda
+
+- func: _cufft_get_plan_cache_size(DeviceIndex device_index) -> int
+
+- func: _cufft_get_plan_cache_max_size(DeviceIndex device_index) -> int
+
+- func: _cufft_set_plan_cache_max_size(DeviceIndex device_index, int max_size) -> ()
+
+- func: _cufft_clear_plan_cache(DeviceIndex device_index) -> ()
+
+- func: index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: index.Tensor_out
+ variants: function, method
+ dispatch:
+ QuantizedCPU: quantized_index
+ tags: [core, dynamic_output_shape]
+ # NB: This function is special-cased in tools/autograd/gen_variable_type.py
+ # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp:
+ # - Tensor Tensor::index(ArrayRef indices)
+ # - Tensor Tensor::index(std::initializer_list indices)
+
+- func: index.Tensor_out(Tensor self, Tensor?[] indices, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ structured: True
+ structured_inherits: TensorIteratorBase
+ precomputed:
+ - indices -> DimVector sizes, DimVector strides
+ dispatch:
+ CPU, CUDA, MPS: index_out
+
+# Used by inductor to signal indexing without bounds checks
+# Note that we don't support boolean indexing, to avoid dynamic output shapes
+- func: _unsafe_index.Tensor(Tensor self, Tensor?[] indices) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _unsafe_index
+
+# Used by inductor to generate masked loads
+# Note that we don't support boolean indexing, to avoid dynamic output shapes
+- func: _unsafe_masked_index(Tensor self, Tensor mask, Tensor?[] indices, Scalar fill) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _unsafe_masked_index
+
+- func: _unsafe_masked_index_put_accumulate(Tensor self, Tensor mask, Tensor?[] indices, Tensor values) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _unsafe_masked_index_put_accumulate
+
+- func: index_copy.out(Tensor self, int dim, Tensor index, Tensor source, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ precomputed:
+ - dim -> int dim
+ dispatch:
+ CPU, CUDA: index_copy_out
+
+- func: index_copy_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!)
+ variants: method
+ structured_delegate: index_copy.out
+
+- func: index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor
+ variants: function, method
+ structured_delegate: index_copy.out
+
+- func: index_copy_.dimname(Tensor(a!) self, Dimname dim, Tensor index, Tensor source) -> Tensor(a!)
+ variants: method
+
+- func: index_copy.dimname(Tensor self, Dimname dim, Tensor index, Tensor source) -> Tensor
+ variants: function, method
+
+- func: index_put_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor(a!)
+ device_check: NoCheck # delegate to _index_put_impl_, which leverages TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: index_put_
+ autogen: index_put.out
+ # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp:
+ # - Tensor & Tensor::index_put_(ArrayRef indices, Tensor const & rhs)
+ # - Tensor & Tensor::index_put_(ArrayRef indices, Scalar v)
+ # - Tensor & Tensor::index_put_(std::initializer_list indices, Tensor const & rhs)
+ # - Tensor & Tensor::index_put_(std::initializer_list indices, Scalar v)
+
+- func: index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor
+ device_check: NoCheck # delegate to _index_put_impl_ after clone, which leverages TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: index_put
+ tags: core
+
+- func: _unsafe_index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor
+ device_check: NoCheck # delegate to _index_put_impl_ after clone, which leverages TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _unsafe_index_put
+
+- func: _index_put_impl_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False, bool unsafe=False) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CPU, CUDA, MPS: _index_put_impl_
+ QuantizedCPU: _index_put_impl_quantized_cpu_
+ QuantizedCUDA: _index_put_impl_quantized_cuda_
+ autogen: _index_put_impl, _index_put_impl.out
+
+- func: instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool use_input_stats, float momentum, float eps, bool cudnn_enabled) -> Tensor
+ variants: function
+
+- func: isclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> Tensor
+ variants: function, method
+
+- func: isin.Tensor_Tensor_out(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: isin_Tensor_Tensor_out
+ MPS: isin_Tensor_Tensor_out_mps
+
+- func: isin.Tensor_Tensor(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor
+ variants: function
+ structured_delegate: isin.Tensor_Tensor_out
+
+- func: isin.Tensor_Scalar_out(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: isin_Tensor_Scalar_out
+
+- func: isin.Tensor_Scalar(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False) -> Tensor
+ variants: function
+ structured_delegate: isin.Tensor_Scalar_out
+
+- func: isin.Scalar_Tensor_out(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: isin_Scalar_Tensor_out
+
+- func: isin.Scalar_Tensor(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor
+ variants: function
+ structured_delegate: isin.Scalar_Tensor_out
+
+- func: isnan(Tensor self) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU, CUDA, MPS: isnan
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_isnan
+ SparseCPU, SparseCUDA: isnan_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isnan_sparse_csr
+ autogen: isnan.out
+ tags: [core, pointwise]
+
+- func: is_distributed(Tensor self) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: is_floating_point(Tensor self) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: is_complex(Tensor self) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: is_conj(Tensor self) -> bool
+ variants: function, method
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: _is_zerotensor(Tensor self) -> bool
+ variants: function, method
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: is_neg(Tensor self) -> bool
+ variants: function, method
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: isreal(Tensor self) -> Tensor
+ variants: function, method
+
+- func: is_nonzero(Tensor self) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: is_same_size(Tensor self, Tensor other) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: nested_is_same_size
+ CompositeExplicitAutograd: is_same_size
+
+- func: is_signed(Tensor self) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: is_inference(Tensor self) -> bool
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: kl_div(Tensor self, Tensor target, int reduction=Mean, *, bool log_target=False) -> Tensor
+
+- func: kron(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+
+- func: kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: kthvalue(Tensor self, int k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: kthvalue
+
+- func: kthvalue.values(Tensor self, int k, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ dispatch:
+ CPU: kthvalue_out_cpu
+ CUDA: kthvalue_out_cuda
+
+- func: kthvalue.dimname(Tensor self, int k, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+
+- func: kthvalue.dimname_out(Tensor self, int k, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: layer_norm_symint
+
+- func: native_layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: layer_norm_cpu
+ CUDA: layer_norm_cuda
+ MPS: layer_norm_mps
+ CompositeExplicitAutograd: math_native_layer_norm
+ NestedTensorCPU, NestedTensorCUDA: nested_layer_norm
+ autogen: native_layer_norm.out
+ tags: core
+
+- func: native_layer_norm_backward(Tensor grad_out, Tensor input, SymInt[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: layer_norm_backward_cpu
+ CUDA: layer_norm_backward_cuda
+ MPS: layer_norm_backward_mps
+ NestedTensorCPU, NestedTensorCUDA: layer_norm_backward_nested
+ autogen: native_layer_norm_backward.out
+ tags: core
+
+- func: rms_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight=None, float? eps=None) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: rms_norm_symint
+
+- func: nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: nan_to_num
+ SparseCPU, SparseCUDA: nan_to_num_sparse
+ tags: pointwise
+
+- func: nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: nan_to_num_
+ SparseCPU, SparseCUDA: nan_to_num_sparse_
+ tags: pointwise
+
+- func: nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: nan_to_num_out
+ MPS: nan_to_num_out_mps
+ SparseCPU, SparseCUDA: nan_to_num_sparse_out
+ tags: pointwise
+
+- func: linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: linear
+ NestedTensorCPU, NestedTensorCUDA: nested_linear
+ MPS: _mps_linear
+
+- func: linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: nested_linear_backward
+ MPS: mps_linear_backward
+ autogen: linear_backward.out
+
+- func: linear.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: linear_out
+
+- func: mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor
+ python_module: nn
+ dispatch:
+ MkldnnCPU: mkldnn_linear
+ autogen: mkldnn_linear.out
+
+- func: mkldnn_linear_backward_input(int[] input_size, Tensor grad_output, Tensor weight) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_linear_backward_input
+ autogen: mkldnn_linear_backward_input.out
+
+- func: mkldnn_linear_backward_weights(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined) -> (Tensor, Tensor)
+ dispatch:
+ MkldnnCPU: mkldnn_linear_backward_weights
+ autogen: mkldnn_linear_backward_weights.out
+
+- func: mkldnn_linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ MkldnnCPU: mkldnn_linear_backward
+ autogen: mkldnn_linear_backward.out
+
+- func: _cslt_compress(Tensor input) -> Tensor
+ dispatch:
+ CUDA: _cslt_compress
+
+- func: _cslt_sparse_mm(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False, int alg_id=0, int split_k=1, bool split_k_one_kernel=True) -> Tensor
+ dispatch:
+ CUDA: _cslt_sparse_mm
+ tags: needs_fixed_stride_order
+
+- func: _cslt_sparse_mm_search(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False) -> int
+ dispatch:
+ CUDA: _cslt_sparse_mm_search
+
+- func: _sparse_semi_structured_tile(Tensor input, str algorithm="", bool use_cutlass=True) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: _sparse_semi_structured_tile
+
+- func: _sparse_semi_structured_apply(Tensor input, Tensor thread_masks) -> (Tensor, Tensor)
+ dispatch:
+ CUDA: _sparse_semi_structured_apply
+
+- func: _sparse_semi_structured_apply_dense(Tensor input, Tensor thread_masks) -> Tensor
+ dispatch:
+ CUDA: _sparse_semi_structured_apply_dense
+
+# DEPRECATED: Use torch.__sparse_semi_structured_mm/torch._sparse_semi_structured_addmm instead
+- func: _sparse_semi_structured_linear(Tensor input, Tensor weight, Tensor meta, *, Tensor? bias=None, str? activation=None, ScalarType? out_dtype=None) -> Tensor
+ dispatch:
+ CUDA: _sparse_semi_structured_linear
+
+- func: _sparse_semi_structured_mm(Tensor mat1, Tensor mat1_meta, Tensor mat2, *, ScalarType? out_dtype=None) -> Tensor
+ dispatch:
+ CUDA: _sparse_semi_structured_mm
+
+- func: _sparse_semi_structured_addmm(Tensor input, Tensor mat1, Tensor mat1_meta, Tensor mat2, *, Scalar alpha=1, Scalar beta=1, ScalarType? out_dtype=None) -> Tensor
+ dispatch:
+ CUDA: _sparse_semi_structured_addmm
+
+- func: _mixed_dtypes_linear(Tensor input, Tensor weight, Tensor scale, *, Tensor? bias=None, str? activation=None) -> Tensor
+ dispatch:
+ CUDA: _mixed_dtypes_linear
+
+- func: fbgemm_linear_int8_weight_fp32_activation(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor
+
+- func: fbgemm_linear_int8_weight(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor
+
+- func: fbgemm_linear_quantize_weight(Tensor input) -> (Tensor, Tensor, float, int)
+
+- func: fbgemm_pack_gemm_matrix_fp16(Tensor input) -> Tensor
+
+- func: _wrapped_linear_prepack(Tensor weight, Tensor weight_scale, Tensor weight_zero_point, Tensor bias) -> Tensor
+
+- func: _wrapped_quantized_linear_prepacked(Tensor input, Tensor input_scale, Tensor input_zero_point, Tensor packed_weight, Tensor output_scale, Tensor output_zero_point, int out_channel) -> Tensor
+
+- func: fbgemm_linear_fp16_weight_fp32_activation(Tensor input, Tensor packed_weight, Tensor bias) -> Tensor
+
+- func: fbgemm_linear_fp16_weight(Tensor input, Tensor packed_weight, Tensor bias) -> Tensor
+
+- func: fbgemm_pack_quantized_matrix(Tensor input) -> Tensor
+
+- func: fbgemm_pack_quantized_matrix.KN(Tensor input, int K, int N) -> Tensor
+
+- func: ldexp.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+
+- func: ldexp_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: function, method
+ tags: pointwise
+
+- func: ldexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ tags: pointwise
+
+- func: linspace(Scalar start, Scalar end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: linspace
+
+- func: linspace.Tensor_Tensor(Tensor start, Tensor end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: linspace
+
+- func: linspace.Tensor_Scalar(Tensor start, Scalar end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: linspace
+
+- func: linspace.Scalar_Tensor(Scalar start, Tensor end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: linspace
+
+- func: linspace.out(Scalar start, Scalar end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, Meta: linspace_out
+ CUDA: linspace_cuda_out
+ MPS: linspace_out_mps
+
+- func: linspace.Tensor_Tensor_out(Tensor start, Tensor end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: linspace_out
+
+- func: linspace.Tensor_Scalar_out(Tensor start, Scalar end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: linspace_out
+
+- func: linspace.Scalar_Tensor_out(Scalar start, Tensor end, int steps, *, Tensor(a!) out) -> Tensor(a!)
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: linspace_out
+
+- func: log(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: log_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log.out
+ variants: function, method
+ tags: pointwise
+
+- func: log.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: log_out
+ MPS: log_out_mps
+ tags: pointwise
+
+- func: log10(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log10.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: log10_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log10.out
+ variants: function, method
+ tags: pointwise
+
+- func: log10.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: log10_out
+ MPS: log10_out_mps
+ tags: pointwise
+
+- func: log1p(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log1p.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: log1p_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: log1p_sparse_csr
+ tags: [core, pointwise]
+
+- func: log1p_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log1p.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: log1p_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: log1p_sparse_csr_
+ tags: pointwise
+
+- func: log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: log1p_out
+ MPS: log1p_out_mps
+ SparseCPU, SparseCUDA: log1p_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: log1p_sparse_csr_out
+ tags: pointwise
+
+- func: log2(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log2.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: log2_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: log2.out
+ variants: function, method
+ tags: pointwise
+
+- func: log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: log2_out
+ MPS: log2_out_mps
+ tags: pointwise
+
+- func: logaddexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: logaddexp_out
+ MPS: logaddexp_out_mps
+ tags: pointwise
+
+- func: logaddexp(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+ structured_delegate: logaddexp.out
+ tags: pointwise
+
+- func: logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: logaddexp2_out
+ MPS: logaddexp2_out_mps
+ tags: pointwise
+
+- func: logaddexp2(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+ structured_delegate: logaddexp2.out
+ tags: pointwise
+
+- func: xlogy.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: xlogy.OutTensor
+ variants: function, method
+ tags: pointwise
+
+- func: xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: xlogy
+ tags: pointwise
+
+- func: xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: xlogy
+ tags: pointwise
+
+# xlogy: inplace variant
+- func: xlogy_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: xlogy.OutTensor
+ tags: pointwise
+
+- func: xlogy_.Scalar_Other(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: xlogy_
+
+# xlogy: out variant
+- func: xlogy.OutTensor(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ variants: function
+ dispatch:
+ CPU, CUDA: xlogy_out
+ MPS: xlogy_out_mps
+ tags: pointwise
+
+- func: xlogy.OutScalar_Self(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: xlogy_out
+ tags: pointwise
+
+- func: xlogy.OutScalar_Other(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: xlogy_out
+ tags: pointwise
+
+- func: logspace(Scalar start, Scalar end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: logspace
+
+- func: logspace.Tensor_Tensor(Tensor start, Tensor end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: logspace
+
+- func: logspace.Tensor_Scalar(Tensor start, Scalar end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: logspace
+
+- func: logspace.Scalar_Tensor(Scalar start, Tensor end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: logspace
+
+- func: logspace.out(Scalar start, Scalar end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, Meta: logspace_out
+ CUDA: logspace_cuda_out
+
+- func: logspace.Tensor_Tensor_out(Tensor start, Tensor end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: logspace_out
+
+- func: logspace.Tensor_Scalar_out(Tensor start, Scalar end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: logspace_out
+
+- func: logspace.Scalar_Tensor_out(Scalar start, Tensor end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!)
+ category_override: factory
+ dispatch:
+ CompositeExplicitAutograd: logspace_out
+
+# log_softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models.
+- func: log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+ variants: function, method
+
+- func: log_softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: log_softmax_out
+
+- func: log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+ variants: function, method
+
+- func: _log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+ structured_delegate: _log_softmax.out
+ tags: core
+
+- func: _log_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: log_softmax_cpu_out
+ CUDA: log_softmax_cuda_out
+ MPS: log_softmax_mps_out
+
+- func: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor
+ structured_delegate: _log_softmax_backward_data.out
+
+- func: _log_softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: log_softmax_backward_cpu_out
+ CUDA: log_softmax_backward_cuda_out
+ MPS: log_softmax_backward_mps_out
+
+- func: _logcumsumexp(Tensor self, int dim) -> Tensor
+ dispatch:
+ CPU: _logcumsumexp_cpu
+ CUDA: _logcumsumexp_cuda
+
+- func: _logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: _logcumsumexp_out_cpu
+ CUDA: _logcumsumexp_out_cuda
+
+- func: logcumsumexp(Tensor self, int dim) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: logcumsumexp
+
+- func: logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: logcumsumexp_out
+
+- func: logcumsumexp.dimname(Tensor self, Dimname dim) -> Tensor
+ variants: function, method
+
+- func: logcumsumexp.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: logsumexp
+
+- func: logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ # calls squeeze
+ CompositeExplicitAutogradNonFunctional: logsumexp_out
+
+- func: logsumexp.names(Tensor self, Dimname[1] dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: logsumexp.names_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor
+
+- func: matmul(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: matmul
+ NestedTensorCPU, NestedTensorCUDA: matmul_nested
+
+- func: matmul_backward(Tensor grad, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: matmul_backward_nested
+ autogen: matmul_backward.out
+
+- func: matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeImplicitAutograd: matmul_out
+ NestedTensorCPU, NestedTensorCUDA: matmul_out_nested
+
+# Alias to linalg.matrix_power
+- func: matrix_power(Tensor self, int n) -> Tensor
+ variants: function, method
+
+# Alias to linalg.matrix_power
+- func: matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!)
+
+# Alias to linalg.matrix_exp
+- func: matrix_exp(Tensor self) -> Tensor
+ variants: function, method
+
+# This function should be deprecated in favor of differential_analytic_matrix_function in FunctionsManual.cpp
+- func: matrix_exp_backward(Tensor self, Tensor grad) -> Tensor
+
+# DEPRECATED: Use torch.aminmax instead
+- func: _aminmax(Tensor self) -> (Tensor, Tensor)
+ dispatch:
+ CPU, CUDA: _aminmax_all
+ autogen: _aminmax.out
+
+# DEPRECATED: Use torch.aminmax instead
+- func: _aminmax.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor, Tensor)
+ dispatch:
+ CPU, CUDA: _aminmax
+ autogen: _aminmax.dim_out
+
+- func: aminmax(Tensor self, *, int? dim=None, bool keepdim=False) -> (Tensor min, Tensor max)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: aminmax.out
+ variants: function, method
+
+- func: aminmax.out(Tensor self, *, int? dim=None, bool keepdim=False, Tensor(a!) min, Tensor(b!) max) -> (Tensor(a!) min, Tensor(b!) max)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: aminmax_out
+ MPS: aminmax_out_mps
+
+- func: _compute_linear_combination(Tensor input, Tensor coefficients) -> Tensor
+ dispatch:
+ CPU, CUDA: _compute_linear_combination
+
+- func: _compute_linear_combination.out(Tensor input, Tensor coefficients, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: _compute_linear_combination_out
+
+- func: max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: max.dim_max
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: qmax
+ tags: core
+
+- func: max.dim_max(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ precomputed:
+ - dim -> int dim
+ dispatch:
+ CPU, CUDA: max_out
+ MPS: max_out_mps
+
+- func: max.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+
+- func: value_selecting_reduction_backward(Tensor grad, int dim, Tensor indices, SymInt[] sizes, bool keepdim) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: value_selecting_reduction_backward_symint
+
+- func: amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor
+ variants: function, method
+ structured_delegate: amax.out
+ tags: core
+
+- func: amax.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU, CUDA: amax_out
+ MPS: amax_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool1d_with_indices(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+
+- func: max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor
+
+- func: max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: max_pool2d
+ MPS: mps_max_pool2d
+
+- func: max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ MPS: mps_max_pool2d_backward
+ autogen: max_pool2d_backward.out
+
+- func: mkldnn_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_max_pool2d
+ autogen: mkldnn_max_pool2d.out
+
+- func: mkldnn_max_pool2d_backward(Tensor grad_output, Tensor output, Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_max_pool2d_backward
+ autogen: mkldnn_max_pool2d_backward.out
+
+- func: mkldnn_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_max_pool3d
+ autogen: mkldnn_max_pool3d.out
+
+- func: mkldnn_max_pool3d_backward(Tensor grad_output, Tensor output, Tensor input, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_max_pool3d_backward
+ autogen: mkldnn_max_pool3d_backward.out
+
+- func: quantized_max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ QuantizedCPU: quantized_max_pool1d
+ autogen: quantized_max_pool1d.out
+
+- func: quantized_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ QuantizedCPU: quantized_max_pool2d
+ QuantizedCUDA: quantized_max_pool2d_cudnn
+ autogen: quantized_max_pool2d.out
+
+- func: quantized_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+ dispatch:
+ QuantizedCPU: quantized_max_pool3d
+ autogen: quantized_max_pool3d.out
+
+- func: max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor
+
+# The CPU and GPU dispatch variants are named weirdly here because otherwise there
+# are namespacing issues in C++
+- func: mean(Tensor self, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: mean
+ tags: core
+
+# For normal naming convention this should be `mean.out`. However since we already have `mean.out` we have to rename this.
+- func: mean.dtype_out(Tensor self, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: mean_dtype_out
+
+- func: mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ structured_delegate: mean.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ QuantizedCPU: mean_quantized_cpu
+ tags: core
+
+- func: mean.out(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: mean_out
+ MPS: mean_out_mps
+ QuantizedCPU: mean_out_quantized_cpu
+
+- func: mean.names_dim(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: mean.names_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: nanmean(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # Composite
+ variants: function, method
+
+- func: nanmean.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # Composite
+
+- func: median(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: median_cpu
+ CUDA: median_cuda
+ MPS: median_mps
+ autogen: median.out
+
+- func: median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: median
+
+- func: median.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ dispatch:
+ CPU: median_out_cpu
+ CUDA: median_out_cuda
+ MPS: median_out_mps
+
+- func: median.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+
+- func: median.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: nanmedian(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: nanmedian_cpu
+ CUDA: nanmedian_cuda
+ autogen: nanmedian.out
+
+- func: nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: nanmedian
+
+- func: nanmedian.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ dispatch:
+ CPU: nanmedian_out_cpu
+ CUDA: nanmedian_out_cuda
+
+- func: nanmedian.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+
+- func: nanmedian.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: min.dim_min
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: qmin
+ tags: core
+
+- func: min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ precomputed:
+ - dim -> int dim
+ dispatch:
+ CPU, CUDA: min_out
+ MPS: min_out_mps
+
+- func: min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: min.names_dim_min(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+
+- func: amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor
+ variants: function, method
+ structured_delegate: amin.out
+ tags: core
+
+- func: amin.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU, CUDA: amin_out
+ MPS: amin_out_mps
+
+# TODO: Add this function to MPS dispatch key so that we avoid declaring it in
+# native_functions.yaml
+# https://github.com/pytorch/pytorch/issues/77394
+- func: _mps_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ MPS: _mps_convolution
+ autogen: _mps_convolution.out
+
+- func: mps_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ MPS: mps_convolution_backward
+ autogen: mps_convolution_backward.out
+
+- func: mkldnn_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: mkldnn_convolution
+ autogen: mkldnn_convolution.out
+
+- func: mkldnn_rnn_layer(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: mkldnn_rnn_layer
+ MkldnnCPU: mkldnn_rnn_layer
+ autogen: mkldnn_rnn_layer.out
+
+- func: mkldnn_rnn_layer_backward(Tensor input, Tensor weight1, Tensor weight2, Tensor weight3, Tensor weight4, Tensor hx_, Tensor cx_tmp, Tensor output, Tensor hy_, Tensor cy_, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, bool reverse, int mode, int hidden_size, int num_layers, bool has_biases, bool train, bool bidirectional, int[] batch_sizes, bool batch_first, Tensor workspace) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: mkldnn_rnn_layer_backward
+ autogen: mkldnn_rnn_layer_backward.out
+
+- func: miopen_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: miopen_batch_norm
+ autogen: miopen_batch_norm.out
+
+- func: miopen_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: miopen_batch_norm_backward
+ autogen: miopen_batch_norm_backward.out
+
+- func: miopen_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+ dispatch:
+ CUDA: miopen_convolution
+ autogen: miopen_convolution.out
+
+- func: miopen_convolution_transpose(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+ dispatch:
+ CUDA: miopen_convolution_transpose
+ autogen: miopen_convolution_transpose.out
+
+- func: miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor
+ dispatch:
+ CUDA: miopen_depthwise_convolution
+ autogen: miopen_depthwise_convolution.out
+
+- func: miopen_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ CUDA: miopen_convolution_relu
+
+- func: miopen_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
+ dispatch:
+ CUDA: miopen_convolution_add_relu
+
+- func: miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: miopen_rnn
+ autogen: miopen_rnn.out
+ tags: nondeterministic_seeded
+
+
+- func: miopen_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[])
+ dispatch:
+ CUDA: miopen_rnn_backward
+ autogen: miopen_rnn_backward.out
+
+- func: mm(Tensor self, Tensor mat2) -> Tensor
+ structured_delegate: mm.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: _sparse_mm
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: _sparse_csr_mm
+ tags: core
+
+- func: mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: mm_out_cpu
+ CUDA: mm_out_cuda
+ MPS: mm_out_mps
+ XPU: mm_out_xpu
+ SparseCPU, SparseCUDA: _sparse_mm_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: _sparse_csr_mm_out
+
+- func: _int_mm(Tensor self, Tensor mat2) -> Tensor
+ dispatch:
+ CPU: _int_mm_cpu
+ CUDA: _int_mm_cuda
+
+- func: _int_mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: _int_mm_out_cpu
+ CUDA: _int_mm_out_cuda
+
+- func: _convert_weight_to_int4pack(Tensor self, int innerKTiles) -> Tensor
+ dispatch:
+ CUDA: _convert_weight_to_int4pack_cuda
+ MPS: _convert_weight_to_int4pack_mps
+
+- func: _weight_int4pack_mm(Tensor self, Tensor mat2, int qGroupSize, Tensor qScaleAndZeros) -> Tensor
+ dispatch:
+ MPS: _weight_int4pack_mm_mps
+ CUDA: _weight_int4pack_mm_cuda
+
+# Split int4 pack weight between cpu and other devices due to
+# https://github.com/pytorch/ao/issues/1117#issuecomment-2451252756.
+- func: _convert_weight_to_int4pack_for_cpu(Tensor self, int innerKTiles) -> Tensor
+ dispatch:
+ CPU: _convert_weight_to_int4pack_cpu
+
+- func: _weight_int4pack_mm_for_cpu(Tensor self, Tensor mat2, int qGroupSize, Tensor qScaleAndZeros) -> Tensor
+ dispatch:
+ CPU: _weight_int4pack_mm_cpu
+
+- func: _weight_int8pack_mm(Tensor self, Tensor mat2, Tensor scales) -> Tensor
+ dispatch:
+ CPU: _weight_int8pack_mm_cpu
+ MPS: _weight_int8pack_mm_mps
+
+- func: _sparse_mm(Tensor sparse, Tensor dense) -> Tensor
+ python_module: sparse
+
+- func: _sparse_mm.reduce(Tensor sparse, Tensor dense, str reduce) -> Tensor
+ python_module: sparse
+
+- func: _sparse_sparse_matmul(Tensor self, Tensor other) -> Tensor
+ dispatch:
+ SparseCPU: sparse_sparse_matmul_cpu
+ SparseCUDA: sparse_sparse_matmul_cuda
+ autogen: _sparse_sparse_matmul.out
+
+- func: mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+ dispatch:
+ CPU, CUDA: mode
+
+- func: mode.values(Tensor self, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ dispatch:
+ CompositeExplicitAutograd: mode_out
+
+- func: mode.dimname(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
+ variants: function, method
+
+- func: mode.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: mul.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: mul.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: mul_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_sparse_csr
+ MkldnnCPU: mkldnn_mul
+ ZeroTensor: mul_zerotensor
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_mul_Tensor
+ tags: [core, pointwise]
+
+- func: mul_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: mul.out
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: mul_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_sparse_csr_
+ MkldnnCPU: mkldnn_mul_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_mul__Tensor
+ tags: pointwise
+
+- func: mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: mul_out
+ MPS: mul_out_mps
+ SparseCPU: mul_out_sparse_cpu
+ SparseCUDA: mul_out_sparse_cuda
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_out_sparse_csr
+ MkldnnCPU: mkldnn_mul_out
+ tags: pointwise
+ # For C++ only, until we have conversion from C++ numbers to Tensor
+
+- func: mul.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: mul
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul_scalar_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_mul_Scalar
+ tags: [core, pointwise]
+
+- func: mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: mul_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: mul__scalar_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_mul__Scalar
+ autogen: mul.Scalar_out
+ tags: pointwise
+# multiply, alias for mul
+
+- func: multiply.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+
+- func: multiply_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: multiply.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: multiply.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: function, method
+
+- func: multiply_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: mv(Tensor self, Tensor vec) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: mv
+ SparseCPU, SparseCUDA: mv_sparse
+
+- func: mv.out(Tensor self, Tensor vec, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: mv_out
+
+- func: mvlgamma.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: mvlgamma_out
+ tags: pointwise
+
+- func: mvlgamma(Tensor self, int p) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: mvlgamma
+ tags: pointwise
+
+- func: mvlgamma_(Tensor(a!) self, int p) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: mvlgamma_
+ tags: pointwise
+
+- func: narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU: narrow_copy_dense_cpu
+ SparseCPU, SparseCUDA: narrow_copy_sparse
+ CompositeExplicitAutogradNonFunctional: narrow_copy_dense_symint
+ tags: view_copy
+
+- func: narrow_copy.out(Tensor self, int dim, SymInt start, SymInt length, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: narrow_copy_dense_cpu_out
+
+- func: narrow(Tensor(a) self, int dim, SymInt start, SymInt length) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: narrow_symint
+ NestedTensorCPU, NestedTensorCUDA: narrow_nested_symint
+
+- func: narrow.Tensor(Tensor(a) self, int dim, Tensor start, SymInt length) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: narrow_tensor_symint
+
+- func: native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: batch_norm_cpu
+ CUDA: batch_norm_cuda
+ MPS: batch_norm_mps
+ MkldnnCPU: mkldnn_batch_norm
+
+- func: native_batch_norm.out(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+ dispatch:
+ CUDA: batch_norm_cuda_out
+ MPS: batch_norm_mps_out
+ CPU: batch_norm_cpu_out
+
+# TODO: In 2 weeks, we should make native_batch_norm composite implicit so that this correct schema percolates correctly through our dispatching
+- func: _native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: _batch_norm_legit_cpu
+ CUDA: _batch_norm_legit_cuda
+ MPS: _batch_norm_legit_mps
+ MkldnnCPU: _mkldnn_batch_norm_legit
+ autogen: _native_batch_norm_legit_functional
+ tags: core
+
+# HACK: identical to _native_batch_norm_legit, but training is known to be False,
+# So we known that running stats will not be mutated.
+# The real fix here is batch norm consolidation.
+- func: _native_batch_norm_legit_no_training(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CompositeExplicitAutograd: _batch_norm_legit_no_training
+ autogen: _native_batch_norm_legit_no_training.out
+ tags: core
+
+- func: _native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!))
+ dispatch:
+ CPU: _batch_norm_legit_cpu_out
+ CUDA: _batch_norm_legit_cuda_out
+ MPS: _batch_norm_legit_mps_out
+
+- func: _native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: _batch_norm_legit_no_stats_cpu
+ CUDA: _batch_norm_legit_no_stats_cuda
+ MPS: _batch_norm_legit_no_stats_mps
+ MkldnnCPU: _mkldnn_batch_norm_legit_no_stats
+ tags: core
+
+- func: _native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+ dispatch:
+ CPU: _batch_norm_legit_no_stats_cpu_out
+ CUDA: _batch_norm_legit_no_stats_cuda_out
+ MPS: _batch_norm_legit_no_stats_mps_out
+
+- func: batch_norm_stats(Tensor input, float eps) -> (Tensor, Tensor)
+ dispatch:
+ CUDA: batch_norm_stats_cuda
+ autogen: batch_norm_stats.out
+
+- func: batch_norm_elemt(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps) -> Tensor
+ dispatch:
+ CUDA: batch_norm_elemt_cuda
+
+- func: batch_norm_elemt.out(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CUDA: batch_norm_elemt_cuda_out
+
+# for backward compatibility
+- func: batch_norm_gather_stats(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, int count) -> (Tensor, Tensor)
+ dispatch:
+ CUDA: batch_norm_gather_stats_cuda
+ autogen: batch_norm_gather_stats.out
+
+- func: batch_norm_gather_stats_with_counts(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, Tensor counts) -> (Tensor, Tensor)
+ dispatch:
+ CUDA: batch_norm_gather_stats_with_counts_cuda
+ autogen: batch_norm_gather_stats_with_counts.out
+
+- func: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: batch_norm_backward_cpu
+ CUDA: batch_norm_backward_cuda
+ MPS: batch_norm_backward_mps
+ MkldnnCPU: mkldnn_batch_norm_backward
+ autogen: native_batch_norm_backward.out
+
+- func: batch_norm_backward_reduce(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: batch_norm_backward_reduce_cuda
+ autogen: batch_norm_backward_reduce.out
+
+- func: batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor sum_dy, Tensor sum_dy_xmu, Tensor count) -> Tensor
+ dispatch:
+ CUDA: batch_norm_backward_elemt_cuda
+ autogen: batch_norm_backward_elemt.out
+
+- func: batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor)
+ dispatch:
+ CPU: batch_norm_update_stats_cpu
+ CUDA: batch_norm_update_stats_cuda
+ autogen: batch_norm_update_stats.out
+
+- func: is_vulkan_available() -> bool
+
+- func: _nnpack_available() -> bool
+
+- func: _nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _nnpack_spatial_convolution
+ autogen: _nnpack_spatial_convolution.out
+
+- func: ones.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: ones
+ autogen: ones.names_out
+
+- func: ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: ones
+
+- func: ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: ones_out
+
+- func: ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: ones_like
+ NestedTensorCPU, NestedTensorCUDA: ones_like
+ autogen: ones_like.out
+
+- func: pairwise_distance(Tensor x1, Tensor x2, float p=2, float eps=1e-06, bool keepdim=False) -> Tensor
+
+- func: cdist(Tensor x1, Tensor x2, float p=2, int? compute_mode=None) -> Tensor
+
+- func: _euclidean_dist(Tensor x1, Tensor x2) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _euclidean_dist
+ autogen: _euclidean_dist.out
+
+- func: _cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor
+ dispatch:
+ CPU, CUDA: _cdist_forward
+ MPS: _cdist_forward_mps
+ autogen: _cdist_forward.out
+ tags: core
+
+- func: _cdist_backward(Tensor grad, Tensor x1, Tensor x2, float p, Tensor cdist) -> Tensor
+ dispatch:
+ CPU, CUDA: _cdist_backward
+ autogen: _cdist_backward.out
+
+- func: pdist(Tensor self, float p=2) -> Tensor
+
+- func: _pdist_forward(Tensor self, float p=2) -> Tensor
+ dispatch:
+ CPU, CUDA: _pdist_forward
+ autogen: _pdist_forward.out
+ tags: core
+
+- func: _pdist_backward(Tensor grad, Tensor self, float p, Tensor pdist) -> Tensor
+ dispatch:
+ CPU, CUDA: _pdist_backward
+ autogen: _pdist_backward.out
+
+- func: cosine_similarity(Tensor x1, Tensor x2, int dim=1, float eps=1e-08) -> Tensor
+ variants: function
+
+- func: permute(Tensor(a) self, int[] dims) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: permute
+ MPS: permute_mps
+ SparseCPU, SparseCUDA: permute_sparse_coo
+ tags: core
+
+- func: movedim.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a)
+ variants: function, method
+
+- func: movedim.int(Tensor(a) self, int source, int destination) -> Tensor(a)
+ variants: function, method
+
+# moveaxis, alias for movedim
+- func: moveaxis.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a)
+ variants: function, method
+
+- func: moveaxis.int(Tensor(a) self, int source, int destination) -> Tensor(a)
+ variants: function, method
+
+# Only exposed from C++ -- in Python,
+# we expose it as an attribute `T`, not a function.
+#
+# I'd like to name this "T" in C++ too, but
+# calling a native function "T" causes undefined
+# behavior on Windows, for reasons I don't understand
+# (maybe related to capital letter collation somehow...)
+- func: numpy_T(Tensor(a) self) -> Tensor(a)
+ variants: method
+
+# Exposed on Python as an attribute 'H'
+- func: matrix_H(Tensor(a) self) -> Tensor(a)
+ variants: method
+
+# Exposed on Python as an attribute 'mT'
+- func: mT(Tensor(a) self) -> Tensor(a)
+ variants: method
+
+# Exposed on Python as an attribute 'mH'
+- func: mH(Tensor(a) self) -> Tensor(a)
+ variants: method
+
+- func: adjoint(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+
+- func: pixel_shuffle(Tensor self, int upscale_factor) -> Tensor
+ dispatch:
+ CPU: pixel_shuffle_cpu
+ MPS: pixel_shuffle_mps
+ CompositeExplicitAutogradNonFunctional: math_pixel_shuffle
+ autogen: pixel_shuffle.out
+
+- func: pixel_unshuffle(Tensor self, int downscale_factor) -> Tensor
+ dispatch:
+ CPU: pixel_unshuffle_cpu
+ MPS: pixel_unshuffle_mps
+ CompositeExplicitAutogradNonFunctional: math_pixel_unshuffle
+ autogen: pixel_unshuffle.out
+
+- func: channel_shuffle(Tensor self, SymInt groups) -> Tensor
+ dispatch:
+ CPU, CUDA: channel_shuffle
+ QuantizedCPU: channel_shuffle_quantized_cpu
+ autogen: channel_shuffle.out
+
+- func: native_channel_shuffle(Tensor self, SymInt groups) -> Tensor
+ dispatch:
+ CPU: channel_shuffle_cpu
+ CompositeImplicitAutograd: math_channel_shuffle
+
+- func: is_pinned(Tensor self, Device? device=None) -> bool
+ variants: method
+ dispatch:
+ # the NestedTensor keys are necessary because NestedTensor has been removed
+ # from the CompositeExplicitAutograd keyset see Note [NestedTensor Not Included in Backend Keys]
+ CompositeExplicitAutograd, NestedTensorCPU: is_pinned
+ SparseCsrCPU: is_pinned_sparse_compressed
+ SparseCPU: is_pinned_sparse_coo
+
+# TODO: add a copy kwarg that guarantees that the tensor is put into fresh
+# pinned memory
+- func: pin_memory(Tensor(a) self, Device? device=None) -> Tensor(a)
+ variants: method
+
+# Unlike pin_memory, this is guaranteed to give a new non-aliasing tensor
+- func: _pin_memory(Tensor self, Device? device=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _pin_memory
+ NestedTensorCPU: _pin_memory_nested
+ SparseCPU: _pin_memory_sparse_coo
+ SparseCsrCPU: _pin_memory_sparse_compressed
+ autogen: _pin_memory.out
+
+- func: pinverse(Tensor self, float rcond=1e-15) -> Tensor
+ variants: function, method
+
+- func: poisson_nll_loss(Tensor input, Tensor target, bool log_input, bool full, float eps, int reduction) -> Tensor
+ variants: function
+
+- func: rad2deg(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: rad2deg
+ SparseCPU, SparseCUDA: rad2deg_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: rad2deg_sparse_csr
+ tags: pointwise
+
+- func: rad2deg_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: rad2deg_
+ SparseCPU, SparseCUDA: rad2deg_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: rad2deg_sparse_csr_
+ tags: pointwise
+
+- func: rad2deg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: rad2deg_out
+ SparseCPU, SparseCUDA: rad2deg_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: rad2deg_sparse_csr_out
+ tags: pointwise
+
+- func: deg2rad(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: deg2rad
+ SparseCPU, SparseCUDA: deg2rad_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: deg2rad_sparse_csr
+ tags: pointwise
+
+- func: deg2rad_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: deg2rad_
+ SparseCPU, SparseCUDA: deg2rad_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: deg2rad_sparse_csr_
+ tags: pointwise
+
+- func: deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: deg2rad_out
+ SparseCPU, SparseCUDA: deg2rad_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: deg2rad_sparse_csr_out
+ tags: pointwise
+
+- func: scalar_tensor(Scalar s, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: scalar_tensor
+ autogen: scalar_tensor.out
+ tags: core
+
+- func: rand.names(SymInt[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: rand
+ autogen: rand.names_out
+ tags: nondeterministic_seeded
+
+- func: rand.generator_with_names(SymInt[] size, *, Generator? generator, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: rand
+ autogen: rand.generator_with_names_out
+
+- func: rand(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: [core, nondeterministic_seeded]
+ dispatch:
+ CompositeExplicitAutograd: rand
+
+- func: rand.generator(SymInt[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: rand
+
+- func: rand.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: rand_out
+
+- func: rand.generator_out(SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: rand_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: rand_like
+ autogen: rand_like.out
+
+- func: randint(SymInt high, SymInt[] size, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint
+
+- func: randint.generator(SymInt high, SymInt[] size, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint
+
+- func: randint.low(SymInt low, SymInt high, SymInt[] size, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint
+
+- func: randint.low_generator(SymInt low, SymInt high, SymInt[] size, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint
+
+- func: randint.out(SymInt high, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint_out
+
+- func: randint.generator_out(SymInt high, SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint_out
+
+- func: randint.low_out(SymInt low, SymInt high, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint_out
+
+- func: randint.low_generator_out(SymInt low, SymInt high, SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randint_out
+
+- func: randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: randint_like
+ autogen: randint_like.out
+
+- func: randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd: randint_like
+ autogen: randint_like.low_dtype_out
+
+- func: randn(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: [core, nondeterministic_seeded]
+ dispatch:
+ CompositeExplicitAutograd: randn
+
+- func: randn.generator(SymInt[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randn
+
+- func: randn.names(SymInt[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: randn
+ autogen: randn.names_out
+
+- func: randn.generator_with_names(SymInt[] size, *, Generator? generator, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: randn
+ autogen: randn.generator_with_names_out
+
+- func: randn.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: randn.generator_out(SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+
+- func: randn_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: randn_like
+ autogen: randn_like.out
+
+- func: randperm(SymInt n, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: [core, nondeterministic_seeded]
+ dispatch:
+ CompositeExplicitAutograd: randperm
+
+- func: randperm.generator(SymInt n, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randperm
+
+- func: randperm.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: randperm_out
+
+- func: randperm.generator_out(SymInt n, *, Generator? generator, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU: randperm_out_cpu
+ CUDA: randperm_out_cuda
+ MPS: randperm_out_mps
+
+- func: range.step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: range
+
+- func: range(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: range
+
+- func: range.out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: range_out_no_step
+
+- func: range.out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, Meta: range_out
+ CUDA: range_cuda_out
+ MPS: range_mps_out
+ cpp_no_default_args: ['step']
+
+- func: ravel(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+
+- func: reciprocal(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: reciprocal.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: reciprocal_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: reciprocal.out
+ variants: function, method
+ tags: pointwise
+
+- func: reciprocal.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: reciprocal_out
+ MPS: reciprocal_out_mps
+ tags: pointwise
+
+- func: neg(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: neg.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: neg_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: neg_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_neg
+ tags: [core, pointwise]
+
+- func: neg_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: neg.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: neg_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: neg_sparse_csr_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_neg_
+ tags: pointwise
+
+- func: neg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: neg_out
+ MPS: neg_out_mps
+ SparseCPU, SparseCUDA: neg_out_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: neg_sparse_csr_out
+ tags: pointwise
+# Alias for neg
+
+- func: negative(Tensor self) -> Tensor
+ variants: function, method
+
+- func: negative_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: negative.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: repeat(Tensor self, SymInt[] repeats) -> Tensor
+ variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too.
+ dispatch:
+ CompositeExplicitAutograd: repeat
+ MPS: repeat_mps
+ autogen: repeat.out
+ tags: core
+
+- func: repeat_interleave.Tensor(Tensor repeats, *, SymInt? output_size=None) -> Tensor
+ variants: function
+ dispatch:
+ CPU: repeat_interleave_cpu
+ CUDA: repeat_interleave_cuda
+ MPS: repeat_interleave_mps
+ tags: dynamic_output_shape
+ autogen: repeat_interleave.Tensor_out
+
+- func: repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: repeat_interleave_symint
+
+- func: repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: repeat_interleave_symint
+
+- func: reshape(Tensor(a) self, SymInt[] shape) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: reshape_symint
+ CompositeImplicitAutogradNestedTensor: reshape_nested_symint
+
+- func: _reshape_copy(Tensor self, SymInt[] size) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _reshape_copy_symint
+
+# NOTE [ _reshape_alias ] is meant to be used in the implementation of reshape.
+# They are not user-facing, hence the leading underscore. Please don't use it
+# anywhere else.
+- func: _reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU, CUDA, Meta, QuantizedCPU, QuantizedCUDA, ZeroTensor, MPS: _reshape_alias
+ # We don't need to support mkldnn since this is handled explicitly by the reshape operator.
+
+- func: _mkldnn_reshape(Tensor self, int[] shape) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ MkldnnCPU: mkldnn_reshape
+ autogen: _mkldnn_reshape.out
+
+- func: reshape_as(Tensor(a) self, Tensor other) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: reshape_as
+ CompositeImplicitAutogradNestedTensor: reshape_as_nested
+
+- func: round(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: round.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: round_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: round_sparse_csr
+ tags: [core, pointwise]
+
+- func: round_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: round.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: round_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: round_sparse_csr_
+ tags: pointwise
+
+- func: round.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU: round_out
+ CUDA: round_out
+ MPS: round_out_mps
+ SparseCPU, SparseCUDA: round_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: round_sparse_csr_out
+ tags: pointwise
+
+- func: round.decimals(Tensor self, *, int decimals) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: round.decimals_out
+ variants: function, method
+ tags: pointwise
+
+- func: round_.decimals(Tensor(a!) self, *, int decimals) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: round.decimals_out
+ variants: function, method
+ tags: pointwise
+
+- func: round.decimals_out(Tensor self, *, int decimals, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU: round_decimals_out
+ CUDA: round_decimals_out
+ tags: pointwise
+
+- func: rrelu(Tensor self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ tags: [pointwise, nondeterministic_seeded]
+
+- func: rrelu_(Tensor(a!) self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ device_check: NoCheck # TensorIterator
+
+- func: relu(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: relu
+ MPS: relu_mps
+ MkldnnCPU: mkldnn_relu
+ QuantizedCPU: relu_quantized_cpu
+ QuantizedCUDA: relu_quantized_cuda
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_relu
+ SparseCPU, SparseCUDA: relu_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: relu_sparse_csr
+ tags: [core, pointwise]
+
+- func: relu_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: relu_
+ MPS: relu_mps_
+ MkldnnCPU: mkldnn_relu_
+ QuantizedCPU: relu_quantized_cpu_
+ QuantizedCUDA: relu_quantized_cuda_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_relu_
+ SparseCPU, SparseCUDA: relu_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: relu_sparse_csr_
+ autogen: relu.out
+ tags: pointwise
+
+- func: relu6(Tensor self) -> Tensor
+ python_module: nn
+ tags: pointwise
+
+- func: relu6_(Tensor(a!) self) -> Tensor(a!)
+ python_module: nn
+
+- func: prelu(Tensor self, Tensor weight) -> Tensor
+ variants: function, method
+ autogen: prelu.out
+
+- func: _prelu_kernel(Tensor self, Tensor weight) -> Tensor
+ dispatch:
+ CPU, CUDA: _prelu_kernel
+ QuantizedCPU: _prelu_kernel_quantized_cpu
+ MkldnnCPU: mkldnn_prelu
+ MPS: prelu_mps
+
+- func: _prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor)
+ dispatch:
+ CPU, CUDA: _prelu_kernel_backward
+ MkldnnCPU: mkldnn_prelu_backward
+ MPS: prelu_backward_mps
+
+- func: gelu.out(Tensor self, *, str approximate='none', Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU: gelu_out_cpu
+ CUDA: gelu_out_cuda
+ MPS: gelu_out_mps
+
+- func: gelu_(Tensor(a!) self, *, str approximate='none') -> Tensor(a!)
+ structured_delegate: gelu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ QuantizedCPU: gelu_quantized_cpu_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_gelu_
+
+- func: gelu(Tensor self, *, str approximate='none') -> Tensor
+ structured_delegate: gelu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ MkldnnCPU: mkldnn_gelu
+ QuantizedCPU: gelu_quantized_cpu
+ QuantizedCUDA: gelu_quantized_cuda
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_gelu
+ tags: [core, pointwise]
+
+- func: gelu_backward.grad_input(Tensor grad_output, Tensor self, *, str approximate='none', Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU: gelu_backward_out_cpu
+ CUDA: gelu_backward_out_cuda
+ MPS: gelu_backward_out_mps
+
+- func: gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor
+ structured_delegate: gelu_backward.grad_input
+ python_module: nn
+ dispatch:
+ MkldnnCPU: mkldnn_gelu_backward
+ NestedTensorCPU, NestedTensorCUDA: gelu_backwards_nested
+ tags: pointwise
+
+- func: infinitely_differentiable_gelu_backward(Tensor grad, Tensor self) -> Tensor
+ variants: function
+ python_module: nn
+ device_check: NoCheck
+ device_guard: False
+
+- func: hardshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: hardshrink_out
+
+- func: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor
+ structured_delegate: hardshrink.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: pointwise
+
+- func: hardshrink_backward.grad_input(Tensor grad_out, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: hardshrink_backward_out
+
+- func: hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor
+ structured_delegate: hardshrink_backward.grad_input
+ variants: function, method
+
+- func: rsqrt(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: rsqrt.out
+ variants: function, method
+ tags: [core, pointwise]
+
+- func: rsqrt_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: rsqrt.out
+ variants: function, method
+ tags: pointwise
+
+- func: rsqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: rsqrt_out
+ MPS: rsqrt_out_mps
+ tags: pointwise
+
+- func: select.Dimname(Tensor(a) self, Dimname dim, int index) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: select_symint
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: select_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: select_nested
+ tags: core
+
+- func: select_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt index) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: select_backward_symint
+ autogen: select_backward.out
+
+- func: _nested_select_backward(Tensor grad_output, Tensor self, int dim, SymInt index) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: _nested_select_backward_symint
+
+- func: selu(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ tags: pointwise
+
+- func: selu_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: celu(Tensor self, Scalar alpha=1.0) -> Tensor
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: celu
+ tags: pointwise
+
+- func: celu_(Tensor(a!) self, Scalar alpha=1.0) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: celu_
+ autogen: celu.out
+
+- func: silu(Tensor self) -> Tensor
+ structured_delegate: silu.out
+ python_module: nn
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_silu
+ tags: pointwise
+
+- func: silu_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: silu.out
+ python_module: nn
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_silu_
+ tags: pointwise
+
+- func: silu.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: silu_out
+ MPS: silu_out_mps
+ tags: pointwise
+
+- func: silu_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: silu_backward_out
+ MPS: silu_backward_out_mps
+ tags: pointwise
+
+- func: silu_backward(Tensor grad_output, Tensor self) -> Tensor
+ structured_delegate: silu_backward.grad_input
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: math_silu_backward
+ NestedTensorCPU, NestedTensorCUDA: silu_backward_nested
+ tags: pointwise
+
+- func: mish(Tensor self) -> Tensor
+ structured_delegate: mish.out
+ python_module: nn
+ tags: pointwise
+
+- func: mish_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: mish.out
+ python_module: nn
+
+- func: mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: mish_out
+ MPS: mish_out_mps
+
+- func: mish_backward(Tensor grad_output, Tensor self) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: mish_backward
+ MPS: mish_backward_mps
+ CompositeImplicitAutograd: math_mish_backward
+
+- func: sigmoid(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sigmoid.out
+ variants: function, method
+ dispatch:
+ QuantizedCPU: sigmoid_quantized_cpu
+ MkldnnCPU: mkldnn_sigmoid
+ tags: [core, pointwise]
+
+- func: sigmoid_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sigmoid.out
+ variants: function, method
+ dispatch:
+ MkldnnCPU: mkldnn_sigmoid_
+ tags: pointwise
+
+- func: sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sigmoid_out
+ MPS: sigmoid_out_mps
+ tags: pointwise
+
+- func: logit(Tensor self, float? eps=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU, CUDA: logit
+ MPS: logit_mps
+ tags: pointwise
+
+- func: logit_(Tensor(a!) self, float? eps=None) -> Tensor(a!)
+ variants: function, method
+ dispatch:
+ CPU, CUDA: logit_
+ tags: pointwise
+
+- func: logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: logit_out
+ MPS: logit_out_mps
+ tags: pointwise
+
+- func: sin(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sin.out
+ variants: function, method
+ dispatch:
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sin_sparse_csr
+ SparseCPU, SparseCUDA: sin_sparse
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_sin
+ tags: [core, pointwise]
+
+- func: sin_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sin.out
+ variants: function, method
+ dispatch:
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sin_sparse_csr_
+ SparseCPU, SparseCUDA: sin_sparse_
+ tags: pointwise
+
+- func: sin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sin_out
+ MPS: sin_out_mps
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sin_sparse_csr_out
+ SparseCPU, SparseCUDA: sin_sparse_out
+ tags: pointwise
+
+- func: sinc(Tensor self) -> Tensor
+ structured_delegate: sinc.out
+ variants: function, method
+ tags: pointwise
+
+- func: sinc_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: sinc.out
+ variants: function, method
+ tags: pointwise
+
+- func: sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sinc_out
+ tags: pointwise
+
+- func: sinh(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sinh.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: sinh_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sinh_sparse_csr
+ tags: [core, pointwise]
+
+- func: sinh_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sinh.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: sinh_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sinh_sparse_csr_
+ tags: pointwise
+
+- func: sinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sinh_out
+ MPS: sinh_out_mps
+ SparseCPU, SparseCUDA: sinh_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sinh_sparse_csr_out
+
+# Returns a copy of this `Variable` that is detached from its autograd graph.
+# This method is OK to call if the `Variable` is a view.
+#
+# NOTE: Previously, if we change the tensor metadata (e.g. sizes / strides /
+# storage / storage_offset) of a tensor created from `detach()`, those metadata
+# in the original tensor will also be updated. However, the new behavior is that
+# those metadata changes to the detached tensor will not update the original tensor
+# anymore, and in the `detach()` function we need to set `allow_tensor_metadata_change_`
+# to false to make such changes explicitly illegal, in order to prevent users from
+# changing metadata of the detached tensor and expecting the original tensor to also
+# be updated.
+ tags: pointwise
+- func: detach(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: detach
+ NestedTensorCPU, NestedTensorCUDA: detach
+
+# Like `detach()`, but modifies this `Variable` in-place. This method may
+# only be called on non-view `Variable`s. You can use `is_view()` to check
+# this. If this `Variable` is a view, throws an `std::runtime_error()`.
+- func: detach_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: detach_
+
+- func: size.int(Tensor self, int dim) -> int
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: size.Dimname(Tensor self, Dimname dim) -> int
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: sym_size.int(Tensor self, int dim) -> SymInt
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ tags: core
+ manual_cpp_binding: True
+
+- func: sym_numel(Tensor self) -> SymInt
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ tags: core
+ manual_cpp_binding: True
+
+- func: sym_storage_offset(Tensor self) -> SymInt
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ tags: core
+ manual_cpp_binding: True
+
+- func: slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: slice
+ tags: core
+
+# NOTE: The implementation of split_with_sizes bypasses the dispatcher to call this; undo
+# that if adding specific implementations here!
+
+- func: slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: slice_backward
+ autogen: slice_backward.out
+
+# NB: This op exists to back the implementation of reverse view_funcs for various views (chunk,
+# slice.Tensor, split_with_sizes, et al.). Currently, these are only used during fake-ification
+# of PT2 graph input subclass instances that are views. This means:
+# * This op shouldn't really show up in eager mode (so e.g. XLA shouldn't have to implement it)
+# * This op shouldn't show up in a PT2 graph (so a PT2 backend shouldn't have to implement it)
+# * A subclass will have to implement this to work in PT2 if a subclass view is used as a graph
+# input AND the view utilizes this op in its inverse. The idea is that slice_inverse() is
+# easier to implement for a subclass than as_strided()
+- func: slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: slice_inverse_symint
+
+- func: slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: slice_scatter
+ autogen: slice_scatter.out
+ tags: [core, view_copy]
+
+- func: select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: select_scatter_symint
+ autogen: select_scatter.out
+ tags: core
+
+- func: diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: diagonal_scatter
+ autogen: diagonal_scatter.out
+
+- func: as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: as_strided_scatter_symint
+ autogen: as_strided_scatter.out
+
+- func: smm(Tensor self, Tensor mat2) -> Tensor
+ variants: function, method
+
+# softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models.
+- func: softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+ variants: function, method
+
+- func: softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: softmax_out
+
+- func: softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+ variants: function, method
+
+- func: _softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+ structured_delegate: _softmax.out
+ dispatch:
+ MkldnnCPU: mkldnn_softmax
+ NestedTensorCPU, NestedTensorCUDA: softmax_nested
+ tags: core
+
+- func: _softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: softmax_cpu_out
+ CUDA: softmax_cuda_out
+ MPS: softmax_mps_out
+
+- func: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor
+ structured_delegate: _softmax_backward_data.out
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: nested_softmax_backward
+
+- func: _softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: softmax_backward_cpu_out
+ CUDA: softmax_backward_cuda_out
+ MPS: softmax_backward_mps_out
+
+- func: unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[]
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: unsafe_split
+ autogen: unsafe_split.Tensor_out
+
+- func: split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: split
+
+- func: split.sizes(Tensor(a -> *) self, SymInt[] split_size, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: split_symint
+
+- func: unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: unsafe_split_with_sizes
+ autogen: unsafe_split_with_sizes.out
+
+- func: split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: split_with_sizes
+ NestedTensorCPU, NestedTensorCUDA: split_with_sizes_nested
+ tags: core
+
+- func: hsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[]
+ variants: function, method
+
+- func: hsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[]
+ variants: function, method
+
+- func: vsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[]
+ variants: function, method
+
+- func: vsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[]
+ variants: function, method
+
+- func: dsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[]
+ variants: function, method
+
+- func: dsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[]
+ variants: function, method
+
+- func: squeeze(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: squeeze
+ QuantizedCPU, QuantizedCUDA: squeeze_quantized
+ NestedTensorCPU, NestedTensorCUDA: squeeze_nested
+
+- func: squeeze.dim(Tensor(a) self, int dim) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: squeeze
+ QuantizedCPU, QuantizedCUDA: squeeze_quantized
+ NestedTensorCPU, NestedTensorCUDA: squeeze_dim_nested
+ tags: core
+
+- func: squeeze.dimname(Tensor(a) self, Dimname dim) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+
+- func: squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: squeeze
+ QuantizedCPU, QuantizedCUDA: squeeze_quantized
+ NestedTensorCPU, NestedTensorCUDA: squeeze_dim_nested
+ tags: core
+
+- func: squeeze_(Tensor(a!) self) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: squeeze_
+
+- func: squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: squeeze_
+
+- func: squeeze_.dims(Tensor(a!) self, int[] dim) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: squeeze_
+
+- func: squeeze_.dimname(Tensor(a!) self, Dimname dim) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+
+- func: sspaddmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ variants: function, method
+
+- func: sspaddmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: _sspaddmm_out_only_sparse
+ CUDA: _sspaddmm_out_only_sparse_cuda
+ SparseCPU: _sspaddmm_out_cpu
+ SparseCUDA: _sspaddmm_out_cuda
+
+- func: _chunk_cat(Tensor[] tensors, int dim, int num_chunks) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _chunk_cat
+ CUDA: _chunk_cat_cuda
+
+- func: _chunk_cat.out(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: _chunk_cat_out
+ CUDA: _chunk_cat_out_cuda
+
+- func: stack(Tensor[] tensors, int dim=0) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: stack
+
+- func: stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: stack_out
+
+- func: _stack(Tensor[] tensors, int dim=0) -> Tensor
+ dispatch: # match the backends supported by _cat
+ CPU: _stack_cpu
+ CompositeExplicitAutograd: _stack
+
+- func: _stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch: # match the backends supported by _cat_out
+ CPU: _stack_out_cpu
+ CompositeExplicitAutograd: _stack_out
+
+- func: hstack(Tensor[] tensors) -> Tensor
+
+- func: hstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: vstack(Tensor[] tensors) -> Tensor
+
+- func: vstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: dstack(Tensor[] tensors) -> Tensor
+
+- func: dstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+# Overload without center & pad mode, needed for forward-compatibility
+- func: stft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool normalized=False, bool? onesided=None, bool? return_complex=None) -> Tensor
+ variants: function, method
+ cpp_no_default_args: ['hop_length', 'win_length', 'window', 'normalized']
+
+- func: stft.center(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, str pad_mode="reflect", bool normalized=False, bool? onesided=None, bool? return_complex=None) -> Tensor
+ variants: function, method
+
+- func: istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensor
+ variants: function, method
+
+- func: stride.int(Tensor self, int dim) -> int
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ manual_cpp_binding: True
+
+- func: stride.Dimname(Tensor self, Dimname dim) -> int
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: sym_stride.int(Tensor self, int dim) -> SymInt
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ tags: core
+ manual_cpp_binding: True
+
+- func: sum(Tensor self, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: sum
+ SparseCPU, SparseCUDA, SparseMeta: sum_coo
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sum_csr
+ autogen: sum.out
+
+- func: sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ # TODO: Align the signature of sum.dim_IntList and _sparse_csr_sum.dim_dtype
+ structured_delegate: sum.IntList_out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ NestedTensorCPU: NestedTensor_sum_dim_CPU
+ SparseCPU, SparseCUDA: sum_sparse_coo
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sum_sparse_compressed
+ tags: core
+
+- func: sum.dim_DimnameList(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: sum.IntList_out(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: sum_out
+ MPS: sum_out_mps
+
+- func: sum.DimnameList_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+# TODO: this function will be replaced once nested expand semantics have been settled on
+- func: _nested_sum_backward(Tensor grad, Tensor self, int[1]? dim, bool keepdim=False) -> Tensor
+ dispatch:
+ NestedTensorCPU: _nested_sum_backward_cpu
+
+- func: nansum(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU, CUDA: nansum
+ MPS: nansum_mps
+
+- func: nansum.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: nansum_out
+ MPS: nansum_out_mps
+
+- func: sum_to_size(Tensor self, SymInt[] size) -> Tensor
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: sum_to_size_symint
+
+- func: sqrt(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sqrt.out
+ variants: function, method
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_sqrt
+ SparseCPU, SparseCUDA: sqrt_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sqrt_sparse_csr
+ tags: [core, pointwise]
+
+- func: sqrt_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sqrt.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: sqrt_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sqrt_sparse_csr_
+ tags: pointwise
+
+- func: sqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sqrt_out
+ MPS: sqrt_out_mps
+ SparseCPU, SparseCUDA: sqrt_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sqrt_sparse_csr_out
+ tags: pointwise
+
+- func: square(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: pointwise
+
+- func: square_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: pointwise
+
+- func: square.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ tags: pointwise
+
+- func: std(Tensor self, bool unbiased=True) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ["unbiased"]
+
+- func: std.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ["unbiased"]
+
+- func: std.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: std
+ MPS: std_mps
+ QuantizedCPU: std_quantized_cpu
+
+- func: std_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ cpp_no_default_args: ["unbiased"]
+
+- func: std_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ cpp_no_default_args: ["unbiased"]
+
+- func: std_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CPU, CUDA: std_mean
+ MPS: std_mean_mps
+ autogen: std_mean.correction_out
+
+- func: std_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ cpp_no_default_args: ["unbiased"]
+
+- func: std_mean.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: std.out(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ cpp_no_default_args: ["unbiased"]
+
+- func: std.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: std_out
+ QuantizedCPU: std_out_quantized_cpu
+
+- func: std.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ["unbiased"]
+
+- func: std.names_out(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ cpp_no_default_args: ["unbiased"]
+
+- func: std.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: std.correction_names_out(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: prod(Tensor self, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: prod
+ MPS: prod_mps
+ autogen: prod.out
+ tags: core
+
+- func: prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ structured_delegate: prod.int_out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: core
+
+- func: prod.int_out(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: prod_out
+ MPS: prod_out_mps
+
+- func: prod.dim_Dimname(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: prod.Dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: t(Tensor(a) self) -> Tensor(a)
+ device_check: NoCheck
+ device_guard: False
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: t
+
+- func: t_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck
+ device_guard: False
+ variants: method
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: t_
+
+- func: tan(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: tan.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: tan_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tan_sparse_csr
+ tags: [core, pointwise]
+
+- func: tan_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: tan.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: tan_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tan_sparse_csr_
+ tags: pointwise
+
+- func: tan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: tan_out
+ MPS: tan_out_mps
+ SparseCPU, SparseCUDA: tan_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tan_sparse_csr_out
+ tags: pointwise
+
+- func: tanh(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: tanh.out
+ variants: function, method
+ dispatch:
+ QuantizedCPU: tanh_quantized_cpu
+ MkldnnCPU: mkldnn_tanh
+ SparseCPU, SparseCUDA: tanh_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tanh_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_tanh
+ tags: [core, pointwise]
+
+- func: tanh_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: tanh.out
+ variants: function, method
+ dispatch:
+ MkldnnCPU: mkldnn_tanh_
+ SparseCPU, SparseCUDA: tanh_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tanh_sparse_csr_
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_tanh_
+ tags: pointwise
+
+- func: tanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: tanh_out
+ MPS: tanh_out_mps
+ SparseCPU, SparseCUDA: tanh_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: tanh_sparse_csr_out
+ tags: pointwise
+
+- func: tensordot(Tensor self, Tensor other, int[] dims_self, int[] dims_other) -> Tensor
+ variants: function
+
+- func: tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+
+# TODO: namespace threshold in 'nn'
+- func: threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ structured_delegate: threshold.out
+ dispatch:
+ QuantizedCPU: threshold_quantized_cpu
+ tags: pointwise
+
+- func: threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ structured_delegate: threshold.out
+
+- func: threshold.out(Tensor self, Scalar threshold, Scalar value, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: threshold_out
+ MPS: threshold_out_mps
+
+- func: threshold_backward.grad_input(Tensor grad_output, Tensor self, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: threshold_backward_out
+ MPS: threshold_backward_out_mps
+ SparseCPU, SparseCUDA: threshold_backward_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: threshold_backward_sparse_compressed_out
+
+- func: threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor
+ variants: function
+ structured_delegate: threshold_backward.grad_input
+ dispatch:
+ MkldnnCPU: mkldnn_relu_backward
+ SparseCPU, SparseCUDA: threshold_backward_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: threshold_backward_sparse_compressed
+ NestedTensorCPU, NestedTensorCUDA: threshold_backwards_nested
+ tags: pointwise
+
+- func: tile(Tensor self, SymInt[] dims) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeImplicitAutograd: tile_symint
+
+- func: transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: transpose
+ NestedTensorCPU, NestedTensorCUDA: transpose_nested
+
+- func: transpose.Dimname(Tensor(a) self, Dimname dim0, Dimname dim1) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: _mkldnn_transpose(Tensor self, int dim0, int dim1) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ MkldnnCPU: mkldnn_transpose
+
+- func: transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: transpose_
+
+- func: _mkldnn_transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ MkldnnCPU: mkldnn_transpose_
+ autogen: _mkldnn_transpose.out
+
+- func: one_hot(Tensor self, int num_classes=-1) -> Tensor
+ python_module: nn
+ variants: function
+ tags: dynamic_output_shape
+
+- func: flip(Tensor self, int[] dims) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU, QuantizedCPU, CUDA, QuantizedCUDA: flip
+ MPS: flip_mps
+ autogen: flip.out
+ tags: core
+
+- func: fliplr(Tensor self) -> Tensor
+ variants: function, method
+
+- func: flipud(Tensor self) -> Tensor
+ variants: function, method
+
+- func: roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU, MPS: roll
+ CUDA: roll_cuda
+ autogen: roll.out
+
+# default int[] value [0,1] should not add space after comma, since codegen parser uses ', ' to split args
+
+- func: rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: rot90
+ autogen: rot90.out
+
+- func: trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
+
+- func: trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor
+
+- func: trapz.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor
+
+- func: trapz.dx(Tensor y, *, float dx=1, int dim=-1) -> Tensor
+
+# Fused implementation detail for transformers. Adds in-projection bias to QKV and divides Q by sqrt(D/num_heads).
+- func: _transform_bias_rescale_qkv(Tensor qkv, Tensor qkv_bias, int num_heads) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU, NestedTensorCPU: transform_bias_rescale_qkv_cpu
+ CUDA, NestedTensorCUDA: transform_bias_rescale_qkv_cuda
+ autogen: _transform_bias_rescale_qkv.out
+
+- func: _nested_tensor_from_mask(Tensor t, Tensor mask, bool mask_check=True) -> Tensor
+ dispatch:
+ CPU, CUDA: NestedTensor_nested_tensor_from_mask
+ autogen: _nested_tensor_from_mask.out
+
+- func: _nested_tensor_from_mask_left_aligned(Tensor t, Tensor mask) -> bool
+ dispatch:
+ CPU, CUDA: NestedTensor_nested_tensor_from_mask_left_aligned
+
+- func: _nested_from_padded(Tensor padded, Tensor cpu_nested_shape_example, bool fuse_transform_0213=False) -> Tensor
+ device_check: NoCheck # cpu_nested_shape_example will always be on CPU
+ dispatch:
+ CPU: nested_from_padded_generic
+ CUDA: nested_from_padded_cuda
+ autogen: _nested_from_padded.out
+
+# These private functions are temporary. They will be updated/deleted when nested tensors switch to using SymInts for their metadata representation
+- func: _nested_tensor_size(Tensor self) -> Tensor
+ variants: method
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: _nested_tensor_size
+ autogen: _nested_tensor_size.out
+
+- func: _nested_tensor_strides(Tensor self) -> Tensor
+ variants: method
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: _nested_tensor_strides
+ autogen: _nested_tensor_strides.out
+
+- func: _nested_tensor_storage_offsets(Tensor self) -> Tensor
+ variants: method
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA, NestedTensorMeta: _nested_tensor_storage_offsets
+ autogen: _nested_tensor_storage_offsets.out
+
+# _nested_from_padded is not usable from Python, so
+# _nested_from_padded_and_nested_example is available for testing.
+- func: _nested_from_padded_and_nested_example(Tensor padded, Tensor nt_example) -> Tensor
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_from_padded_and_nested_example
+ autogen: _nested_from_padded_and_nested_example.out
+
+# The input arguments' types to this functions are temporary. When nested tensors switch to using SymInts for their metadata representation
+# this will need to be updated
+- func: _nested_view_from_buffer(Tensor(a) self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor(a)
+ variants: function
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: _nested_view_from_buffer
+
+- func: _nested_view_from_buffer_copy(Tensor self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor
+ variants: function
+ device_check: NoCheck
+ tags: view_copy
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _nested_view_from_buffer_copy
+ autogen: _nested_view_from_buffer_copy.out
+
+- func: _nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor(a)
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_view_from_jagged_copy(Tensor self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor
+ variants: function
+ device_check: NoCheck
+ tags: view_copy
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _nested_view_from_jagged_copy
+ autogen: _nested_view_from_jagged_copy.out
+
+- func: _nested_get_values(Tensor(a) self) -> Tensor(a)
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_get_values_copy(Tensor self) -> Tensor
+ variants: function
+ device_check: NoCheck
+ tags: view_copy
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _nested_get_values_copy
+ autogen: _nested_get_values_copy.out
+
+- func: _nested_get_offsets(Tensor self) -> Tensor
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+# returns undefined Tensor if no lengths present
+- func: _nested_get_lengths(Tensor self) -> Tensor
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_get_ragged_idx(Tensor self) -> int
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_get_min_seqlen(Tensor self) -> Tensor
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_get_max_seqlen(Tensor self) -> Tensor
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_get_jagged_dummy(Tensor any) -> Tensor
+ category_override: dummy
+ dispatch: {}
+
+- func: _nested_compute_contiguous_strides_offsets(Tensor nested_size) -> (Tensor, Tensor)
+ variants: function
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: _nested_compute_contiguous_strides_offsets
+
+- func: _trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor
+ dispatch:
+ # calls unsqueeze
+ CompositeExplicitAutogradNonFunctional: _trilinear
+ autogen: _trilinear.out
+
+- func: triplet_margin_loss(Tensor anchor, Tensor positive, Tensor negative, float margin=1.0, float p=2, float eps=1e-06, bool swap=False, int reduction=Mean) -> Tensor
+
+- func: trunc(Tensor self) -> Tensor
+ structured_delegate: trunc.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: trunc_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: trunc_sparse_csr
+ tags: [core, pointwise]
+
+- func: trunc_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: trunc.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: trunc_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: trunc_sparse_csr_
+ tags: pointwise
+
+- func: trunc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: trunc_out
+ MPS: trunc_out_mps
+ SparseCPU, SparseCUDA: trunc_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: trunc_sparse_csr_out
+ tags: pointwise
+# Alias for trunc
+
+- func: fix(Tensor self) -> Tensor
+ variants: function, method
+
+- func: fix_(Tensor(a!) self) -> Tensor(a!)
+ variants: function, method
+
+- func: fix.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: type_as(Tensor self, Tensor other) -> Tensor
+ variants: method
+
+- func: _has_compatible_shallow_copy_type(Tensor self, Tensor from) -> bool
+ variants: function
+
+- func: _unique(Tensor self, bool sorted=True, bool return_inverse=False) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: _unique_cpu
+ CUDA: _unique_cuda
+ autogen: _unique.out
+
+- func: unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: unique_dim_cpu
+ CUDA: unique_dim_cuda
+ tags: dynamic_output_shape
+ autogen: unique_dim.out
+
+- func: unique_consecutive(Tensor self, bool return_inverse=False, bool return_counts=False, int? dim=None) -> (Tensor, Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: unique_consecutive_cpu
+ CUDA: unique_consecutive_cuda
+ MPS: unique_consecutive_mps
+ tags: dynamic_output_shape
+ autogen: unique_consecutive.out
+
+- func: unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: unique_dim_consecutive_cpu
+ CUDA: unique_dim_consecutive_cuda
+ MPS: unique_dim_consecutive_mps
+ tags: dynamic_output_shape
+ autogen: unique_dim_consecutive.out
+
+# _unique and _unique_dim are fragile and modifying them easily cause internal break
+# the below operator is a temporary hack for adding return_counts support
+# Please don't rely on these two operators, they will be removed soon
+
+- func: _unique2(Tensor self, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: _unique2_cpu
+ CUDA: _unique2_cuda
+ MPS: _unique2_mps
+ tags: dynamic_output_shape
+ autogen: _unique2.out
+
+- func: _unsafe_view(Tensor self, SymInt[] size) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _unsafe_view
+ autogen: _unsafe_view.out
+
+- func: unsqueeze(Tensor(a) self, int dim) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: unsqueeze
+ SparseCPU, SparseCUDA: unsqueeze_sparse
+ QuantizedCPU, QuantizedCUDA: unsqueeze_quantized
+ NestedTensorCPU, NestedTensorCUDA: unsqueeze_nested
+ tags: core
+
+- func: unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+ dispatch:
+ CompositeExplicitAutograd: unsqueeze_
+
+- func: vander(Tensor x, int? N=None, bool increasing=False) -> Tensor
+
+- func: var(Tensor self, bool unbiased=True) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ["unbiased"]
+
+- func: var.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ tags: core
+ cpp_no_default_args: ["unbiased"]
+
+- func: var.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA: var
+ MPS: var_mps
+ tags: core
+
+- func: var.out(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ cpp_no_default_args: ["unbiased"]
+
+- func: var.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: var_out
+
+- func: var.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ cpp_no_default_args: ["unbiased"]
+
+- func: var.names_out(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ cpp_no_default_args: ["unbiased"]
+
+- func: var.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: var.correction_names_out(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: var_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ cpp_no_default_args: ["unbiased"]
+
+- func: var_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ cpp_no_default_args: ["unbiased"]
+
+- func: var_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CPU, CUDA: var_mean
+ MPS: var_mean_mps
+ autogen: var_mean.correction_out
+
+- func: var_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ cpp_no_default_args: ["unbiased"]
+
+- func: var_mean.correction_names(Tensor self, Dimname[1] dim, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: view_as(Tensor(a) self, Tensor other) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+
+- func: where.self(Tensor condition, Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CPU, CUDA, MPS: where
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_where
+ tags: [core, pointwise]
+
+- func: where.self_out(Tensor condition, Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA, MPS: where_self_out
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_where_out
+
+- func: where.ScalarSelf(Tensor condition, Scalar self, Tensor other) -> Tensor
+ variants: function
+
+- func: where.ScalarOther(Tensor condition, Tensor self, Scalar other) -> Tensor
+ variants: function, method
+
+- func: where.Scalar(Tensor condition, Scalar self, Scalar other) -> Tensor
+ variants: function
+
+- func: where(Tensor condition) -> Tensor[]
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: norm_except_dim(Tensor v, int pow=2, int dim=0) -> Tensor
+ variants: function
+
+# VariableType::_weight_norm does not want to be given a gap in the autograd graph,
+# so we don't define "dispatch" variants for it.
+- func: _weight_norm(Tensor v, Tensor g, int dim=0) -> Tensor
+ variants: function
+
+- func: _weight_norm_interface(Tensor v, Tensor g, int dim=0) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: weight_norm_cpu
+ CUDA: weight_norm_cuda
+ MPS: weight_norm_mps
+ autogen: _weight_norm_interface.out
+
+- func: _weight_norm_interface_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU: weight_norm_backward_cpu
+ CUDA: weight_norm_backward_cuda
+ MPS: weight_norm_backward_mps
+ autogen: _weight_norm_interface_backward.out
+
+- func: _weight_norm_differentiable_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor)
+ variants: function
+
+- func: zeros.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: zeros
+ autogen: zeros.names_out
+
+- func: _efficientzerotensor(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CPU: _efficientzerotensor
+ CUDA: _efficientzerotensor_cuda
+ MPS: _efficientzerotensor_mps
+ Meta: _efficientzerotensor_meta_symint
+ autogen: _efficientzerotensor.out
+
+- func: zeros(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: zeros_symint
+
+- func: zeros.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: zeros_out
+ SparseCPU, SparseCUDA, SparseMeta: zeros_sparse_out
+
+- func: zeros_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor
+ dispatch:
+ # NB: Although this composite mutates on the inside, it is
+ # non-differentiable so NonFunctional doesn't apply
+ CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: zeros_like
+ autogen: zeros_like.out
+
+- func: _standard_gamma_grad(Tensor self, Tensor output) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _standard_gamma_grad_cpu
+ CUDA: _standard_gamma_grad_cuda
+ autogen: _standard_gamma_grad.out
+
+- func: _standard_gamma(Tensor self, Generator? generator=None) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _s_gamma_cpu
+ CUDA: _s_gamma_cuda
+ tags: nondeterministic_seeded
+ autogen: _standard_gamma.out
+
+- func: _dirichlet_grad(Tensor x, Tensor alpha, Tensor total) -> Tensor
+ dispatch:
+ CPU: _dirichlet_grad_cpu
+ CUDA: _dirichlet_grad_cuda
+ autogen: _dirichlet_grad.out
+
+- func: _sample_dirichlet(Tensor self, Generator? generator=None) -> Tensor
+ tags: nondeterministic_seeded
+ variants: function
+ dispatch:
+ CPU: _s_dirichlet_cpu
+ CUDA: _s_dirichlet_cuda
+ autogen: _sample_dirichlet.out
+
+- func: poisson(Tensor self, Generator? generator=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU: _s_poisson_cpu
+ CUDA: _s_poisson_cuda
+ tags: nondeterministic_seeded
+ autogen: poisson.out
+
+- func: binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU: _s_binomial_cpu
+ CUDA: _s_binomial_cuda
+ tags: nondeterministic_seeded
+ autogen: binomial.out
+
+# When more variants get ported to native, this dispatch will get more
+# complicated
+
+- func: native_norm(Tensor self, Scalar p=2) -> Tensor
+ dispatch:
+ SparseCPU, SparseCUDA: norm_sparse
+ autogen: native_norm.out
+
+- func: native_norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, ScalarType? dtype) -> Tensor
+ dispatch:
+ SparseCPU, SparseCUDA: norm_sparse
+ autogen: native_norm.ScalarOpt_dim_dtype_out
+
+- func: _batch_norm_with_update(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: _batch_norm_with_update_cpu
+ CUDA: _batch_norm_with_update_cuda
+ MPS: _batch_norm_with_update_mps
+ MkldnnCPU: _batch_norm_with_update_mkldnn
+ autogen: _batch_norm_with_update_functional
+
+- func: _batch_norm_with_update.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd, Tensor(g!) reserve) -> (Tensor(d!), Tensor(e!), Tensor(f!), Tensor(g!))
+ dispatch:
+ CPU: _batch_norm_with_update_cpu_out
+ CUDA: _batch_norm_with_update_cuda_out
+ MPS: _batch_norm_with_update_mps_out
+
+- func: _batch_norm_no_update(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CompositeExplicitAutograd: _batch_norm_no_update
+ autogen: _batch_norm_no_update.out
+
+- func: batch_norm_backward(Tensor grad_out, Tensor input, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, bool update, float eps, bool[3] output_mask, Tensor reserve) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CPU: _new_batch_norm_backward_cpu
+ CUDA: _new_batch_norm_backward_cuda
+ MPS: _new_batch_norm_backward_mps
+ MkldnnCPU: _new_batch_norm_backward_mkldnn
+
+# TODO: reduce signatures down to one when optional args is available
+- func: _sparse_sum(Tensor self) -> Tensor
+
+- func: _sparse_sum.dtype(Tensor self, *, ScalarType dtype) -> Tensor
+
+- func: _sparse_sum.dim(Tensor self, int[1] dim) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _sparse_sum
+ autogen: _sparse_sum.dim_out
+
+- func: _sparse_sum.dim_dtype(Tensor self, int[1] dim, *, ScalarType dtype) -> Tensor
+
+- func: _sparse_sum_backward(Tensor grad, Tensor self, int[] dim) -> Tensor
+ dispatch:
+ SparseCPU: _sparse_sum_backward_cpu
+ SparseCUDA: _sparse_sum_backward_cuda
+ autogen: _sparse_sum_backward.out
+
+- func: _sparse_csr_sum.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ dispatch:
+ SparseCsrCPU: _sparse_csr_sum_cpu
+ SparseCsrCUDA: _sparse_csr_sum_cuda
+ autogen: _sparse_csr_sum.dim_dtype_out
+
+- func: _sparse_csr_prod.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ dispatch:
+ SparseCsrCPU: _sparse_csr_prod_cpu
+ SparseCsrCUDA: _sparse_csr_prod_cuda
+ autogen: _sparse_csr_prod.dim_dtype_out
+
+- func: _sparse_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+ python_module: sparse
+ variants: function
+
+- func: _sparse_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+ python_module: sparse
+ variants: function
+
+- func: _sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+ python_module: sparse
+ dispatch:
+ SparseCPU: softmax_sparse_cpu
+ SparseCUDA: softmax_sparse_cuda
+ autogen: _sparse_softmax.out
+
+- func: _sparse_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor
+ dispatch:
+ SparseCPU: softmax_backward_sparse_cpu
+ SparseCUDA: softmax_backward_sparse_cuda
+ autogen: _sparse_softmax_backward_data.out
+
+- func: _sparse_log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+ python_module: sparse
+ variants: function
+
+- func: _sparse_log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor
+ python_module: sparse
+ variants: function
+
+- func: _sparse_log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor
+ python_module: sparse
+ dispatch:
+ SparseCPU: log_softmax_sparse_cpu
+ SparseCUDA: log_softmax_sparse_cuda
+ autogen: _sparse_log_softmax.out
+
+- func: _sparse_log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor
+ dispatch:
+ SparseCPU: log_softmax_backward_sparse_cpu
+ SparseCUDA: log_softmax_backward_sparse_cuda
+ autogen: _sparse_log_softmax_backward_data.out
+
+- func: _spdiags(Tensor diagonals, Tensor offsets, int[] shape, Layout? layout=None) -> Tensor
+ python_module: sparse
+ dispatch:
+ CPU: spdiags
+ autogen: _spdiags.out
+
+- func: norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: norm
+ autogen: norm.ScalarOpt_dtype_out
+
+- func: norm.Scalar(Tensor self, Scalar p=2) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: norm
+ autogen: norm.Scalar_out
+
+- func: norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor
+ structured_delegate: norm.dtype_out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_dtype_norm
+
+- func: norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor
+ structured_delegate: norm.out
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_norm
+
+- func: norm.dtype_out(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: norm_dtype_out
+ MPS: norm_dtype_out_mps
+
+- func: norm.out(Tensor self, Scalar? p, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: norm_out
+ MPS: norm_out_mps
+
+# These four redispatch in their implementation, so OK to be CompositeImplicitAutograd
+- func: norm.names_ScalarOpt_dim_dtype(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: norm.names_ScalarOpt_dim(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: norm.names_dtype_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: norm.names_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent)
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: frexp
+ tags: pointwise
+
+- func: frexp.Tensor_out(Tensor self, *, Tensor(a!) mantissa, Tensor(b!) exponent) -> (Tensor(a!) mantissa, Tensor(b!) exponent)
+ dispatch:
+ CPU, CUDA: frexp_out
+ tags: pointwise
+
+# Deprecated (v.1.12)
+- func: frobenius_norm.dim(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+ variants: function
+
+# Deprecated (v.1.12)
+- func: frobenius_norm.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm(Tensor self, bool keepdim=False) -> Tensor
+ variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm.out(Tensor self, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm.dim(Tensor self, int[2] dim, bool keepdim=False) -> Tensor
+ variants: function
+
+# Deprecated (v.1.12)
+- func: nuclear_norm.dim_out(Tensor self, int[2] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+
+- func: clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: clone
+ SparseCPU, SparseCUDA: clone_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: clone_sparse_compressed
+ MkldnnCPU: mkldnn_clone
+ QuantizedCPU, QuantizedCUDA: quantized_clone
+ NestedTensorCPU, NestedTensorCUDA: clone_nested
+ autogen: clone.out
+ tags: [core, pointwise]
+
+- func: positive(Tensor(a) self) -> Tensor(a)
+ variants: function, method
+ tags: pointwise
+
+- func: resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: resize_as_
+ autogen: resize_as, resize_as.out
+ tags: inplace_view
+
+- func: resize_as_sparse_(Tensor(a!) self, Tensor the_template) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: resize_as_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: resize_as_sparse_compressed_
+ autogen: resize_as_sparse, resize_as_sparse.out
+
+- func: zero_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA: zero_
+ MPS: zero_mps_
+ Meta: zero_meta_
+ SparseCPU, SparseCUDA, SparseMeta: zero_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: zero_sparse_csr_
+ MkldnnCPU: mkldnn_zero_
+ NestedTensorCPU, NestedTensorCUDA: zero_nested_
+ autogen: zero, zero.out
+
+- func: sub.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sub_out
+ MPS: sub_out_mps
+ SparseCPU, SparseCUDA: sub_out_sparse
+ tags: pointwise
+
+- func: sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: sub.out
+ dispatch:
+ SparseCPU, SparseCUDA: sub_sparse
+ ZeroTensor: sub_zerotensor
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_sub_Tensor
+ tags: [core, pointwise]
+
+- func: sub_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: sub.out
+ dispatch:
+ SparseCPU, SparseCUDA: sub_sparse_
+ tags: pointwise
+# For C++ only, until we have conversion from C++ numbers to Tensor
+
+- func: sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: sub
+ tags: [core, pointwise]
+
+- func: sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: sub_
+ autogen: sub.Scalar_out
+ tags: pointwise
+# subtract, alias for sub
+
+- func: subtract.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+
+- func: subtract.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+ variants: function, method
+
+- func: subtract_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
+ variants: method
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: subtract.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+ variants: function, method
+
+- func: subtract_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
+ variants: method
+
+- func: rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CPU, CUDA: rsub
+ autogen: rsub.Tensor_out
+
+- func: heaviside.out(Tensor self, Tensor values, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: heaviside_out
+ tags: pointwise
+
+- func: heaviside(Tensor self, Tensor values) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: heaviside.out
+ tags: pointwise
+
+- func: heaviside_(Tensor(a!) self, Tensor values) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: heaviside.out
+
+# For C++ only, until we have conversion from C++ numbers to Tensor
+- func: rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: rsub
+ autogen: rsub.Scalar_out
+
+# Functionally the same as addmm, but we give it a different derivative formula
+# that doesn't propagate gradients to non-present entries on sparse.
+ tags: pointwise
+- func: _sparse_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ python_module: sparse
+ dispatch:
+ CompositeExplicitAutograd: _sparse_addmm
+ autogen: _sparse_addmm.out
+
+- func: sparse_sampled_addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ python_module: sparse
+ dispatch:
+ SparseCsrCUDA: sparse_sampled_addmm_out_sparse_csr_cuda
+ SparseCsrCPU: sparse_sampled_addmm_out_sparse_csr_cpu
+
+- func: sparse_sampled_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ python_module: sparse
+ dispatch:
+ SparseCsrCUDA: sparse_sampled_addmm_sparse_csr_cuda
+ SparseCsrCPU: sparse_sampled_addmm_sparse_csr_cpu
+
+- func: _sparse_mm_reduce_impl(Tensor self, Tensor other, str reduce) -> (Tensor, Tensor)
+ python_module: sparse
+ dispatch:
+ SparseCsrCPU: _sparse_mm_reduce_impl_sparse_csr_cpu
+
+- func: _sparse_mm_reduce_impl_backward(Tensor self, Tensor grad_out, Tensor weight, str reduce, Tensor arg_out, bool[2] output_mask) -> (Tensor, Tensor)
+ python_module: sparse
+ dispatch:
+ SparseCsrCPU: _sparse_mm_reduce_impl_backward_sparse_csr_cpu
+
+- func: addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: addmm_out_cpu
+ CUDA: addmm_out_cuda
+ MPS: addmm_out_mps
+ XPU: addmm_out_xpu
+ SparseCPU: addmm_out_sparse_dense_cpu
+ SparseCUDA: addmm_out_sparse_dense_cuda
+ SparseCsrCPU: addmm_out_sparse_compressed_cpu
+ SparseCsrCUDA: addmm_out_sparse_compressed_cuda
+
+- func: addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ structured_delegate: addmm.out
+ variants: function, method
+ dispatch:
+ SparseCPU: addmm_sparse_dense_cpu
+ SparseCUDA: addmm_sparse_dense_cuda
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: addmm_sparse_compressed_dense
+ tags: core
+
+- func: addmm_(Tensor(a!) self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+ structured_delegate: addmm.out
+ variants: method
+ dispatch:
+ # Warning! For whatever reason, the inplace sparse addmm is NON
+ # broadcasting
+ SparseCPU: s_addmm_sparse_dense_cpu_
+ SparseCUDA: s_addmm_sparse_dense_cuda_
+
+- func: _addmm_activation.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: addmm_activation_out_cpu
+ CUDA: addmm_activation_out_cuda
+ XPU: addmm_activation_out_xpu
+
+- func: _addmm_activation(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False) -> Tensor
+ structured_delegate: _addmm_activation.out
+ variants: function, method
+
+- func: _scaled_mm(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False) -> Tensor
+ variants: function
+ dispatch:
+ CUDA: _scaled_mm_cuda
+
+- func: _scaled_mm.out(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False, *, Tensor(a!) out) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CUDA: _scaled_mm_out_cuda
+
+# NOTE [ Sparse: autograd and API ]
+#
+#
+# Sparse Tensor Constructors
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# The API entry points to sparse tensor construction should be
+# `sparse_coo tensor` and `_sparse_coo_tensor_unsafe`. Depending on whether the
+# indices and values tensors are given, they eventually dispatch to either
+# `sparse_coo_tensor_with_dims` or `sparse_coo_tensor_with_dims_and_tensors`.
+#
+# The autograd support for ctor is implement on `sparse_coo_tensor_with_dims_and_tensors`.
+#
+# The API methods `sparse_coo tensor` and `_sparse_coo_tensor_unsafe`
+# **must not** have specific type dispatches because otherwise codegen will
+# consider them as abstract methods (see Note [Abstract ATen methods]), dispatch
+# using **Tensor** type, and thus lose autograd tracking on the actual method
+# they dispatch to, e.g., `sparse_coo_tensor_with_dims_and_tensors`.
+#
+#
+# Sparse Methods API Design
+# ~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# Goals: 1. Flexible API for users to write custom sparse ops
+# 2. ctor and member accessor with autograd support
+#
+# To achieve 1, we need to provide a set of *dangerous* APIs (dangerous in the
+# sense that misusing them will break sparse tensor invariant and may out in
+# unexpected behavior, e.g., crash). These methods are all prefixed with
+# underscore "_" to indicate that they should be used with care. We provide:
+#
+# + `_indices()`: returns the *raw* indices within the sparse tensor (not just
+# sharing storage). Any inplace operation will change the
+# actual indices, including t_, set_, as_strided_, resize_,
+# etc.
+# + `_values()`: returns the *raw* values within the sparse tensor. Similar
+# semantics as `_indices()`
+# + `_nnz()`: returns the number of non-zero entries. This will always be
+# determined by the shapes of indices and values.
+# + `_coalesced_(bool)`: inplace sets whether the tensor is coalesced, and
+# returns itself.
+#
+# These methods are very useful in writing new operations, e.g., a custom
+# autograd Function.
+#
+# We also provide other public *safe* APIs:
+# + `indices()`: returns a **view** of the indices tensor if the sparse tensor
+# is **coalesced**.
+# + `values()`: returns a **view** of the values tensor if the containing
+# sparse tensor is **coalesced**.
+# + `sparse_dim()`: number of sparse dimensions
+# + `dense_dim()`: number of dense dimensions
+# + `is_coalesced()`: whether the sparse tensor is coalesced
+#
+# `_indices()` and `_values()` should returns the raw indices and values dense
+# tensors within a sparse tensor. They can be quite unsafe with inplace
+# operations like `t_()`, and exposes uncoalesced indices and values. The public
+# recommended API is `indices()` and `values()`, both of which first check that
+# the tensor is coalesced and return views on those tensors.
+#
+#
+# Autograd Support
+# ~~~~~~~~~~~~~~~~
+#
+# Autograd is supported on `values()` and sparse tensor ctor with indices and
+# values tensors. E.g., `torch.sparse_coo_tensor(i, v).values().sum()` is
+# differentiable w.r.t. `v`.
+#
+# NB: The `values()` and `_values()` operators are special in that they are
+# layout-aware, i.e., the output depends not just on the data it represents, but
+# also on the input layout details (in this case, the `indices` tensor). See
+# NOTE [ as_strided Backward and layout-aware/agnostic autograd ] in Functions.cpp
+# for discussion on layout-aware vs layout-agnostic autograd. Since PyTorch ops
+# operate in the layout-agnostic mode, similar to `as_strided`, backward of
+# these two operators need to consider them in a layout-agnostic way:
+# + `values()`:
+# Input is coalesced.
+# We just pretend having `input.indices()` as an additional argument
+# `input_indices`, then forward is similar to
+# `input.to(kStrided).index_select(input_indices)` regardless of the layout.
+# Note that `values()` normally is layout-aware even if we constrain
+# ourselves on sparse inputs since it may include all zeros values entries
+# as "present" entries.
+# + `_values()`:
+# Input may be uncoalesced.
+# It is not straightforward to construct a layout-agnostic version because
+# duplicate indices entries may exist and additional parameterization is
+# needed to distribute the value into different values entries. Furthermore,
+# this op is intended to provide ways to write custom sparse ops, rather
+# than being used in autograd graph, so it is marked as *non-differentiable*
+# in derivatives.yaml.
+#
+# Before reading the following, see NOTE [ Autograd Variable Views ] in
+# variable.h for details on views that are tracked by autograd, and views that
+# are not.
+#
+# Moreover, these methods return tensors that share storage with inputs, so we
+# mark these methods as view ops to support autograd history tracking.
+# The sparse tensor ctor output should technically be view of both input indices
+# and values tensors, but currently we only support setting as view of a single
+# Variable, so it is only view of the values tensor.
+# TODO: clone indices in sparse tensor ctor.
+#
+# For other methods that return outputs that share storage with inputs, i.e.,
+# `indices()` and `_indices()`. We mark their outputs as non-differentiable, so
+# the view relation is not tracked by autograd, but the version counter is still
+# shared. In other words, their outputs are non-differentiable views of the
+# sparse tensor.
+# FIXME: would be nicer if TensorOptions was optional based; not adding default arguments for options given
+# the default would never make sense.
+
+- func: _sparse_compressed_tensor_with_dims(int nnz, int dense_dim, int[] size, int[] blocksize, ScalarType index_dtype, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: sparse_compressed_tensor_with_dims
+
+- func: sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: sparse_compressed_tensor
+
+- func: sparse_csr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_csc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+
+- func: sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: sparse_compressed_tensor
+- func: sparse_csr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_csc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+- func: sparse_bsc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+
+- func: _sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: _sparse_compressed_tensor_unsafe_symint
+
+- func: _sparse_csr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+- func: _sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+- func: _sparse_bsr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+- func: _sparse_bsc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+
+- func: sparse_coo_tensor.size(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: sparse_coo_tensor
+ autogen: sparse_coo_tensor.size_out
+
+- func: sparse_coo_tensor.indices(Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor
+
+- func: sparse_coo_tensor.indices_size(Tensor indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor
+
+- func: _sparse_coo_tensor_unsafe(Tensor indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: _sparse_coo_tensor_unsafe_symint
+
+- func: _validate_sparse_coo_tensor_args(Tensor indices, Tensor values, int[] size, bool? is_coalesced=None) -> ()
+
+- func: _validate_sparse_compressed_tensor_args(Tensor compressed_indices, Tensor plain_indices, Tensor values, int[] size, Layout layout) -> ()
+- func: _validate_sparse_csr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size) -> ()
+- func: _validate_sparse_csc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size) -> ()
+- func: _validate_sparse_bsr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size) -> ()
+- func: _validate_sparse_bsc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size) -> ()
+
+- func: _sparse_coo_tensor_with_dims(int sparse_dim, int dense_dim, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta, Meta: new_with_dims_sparse
+ autogen: _sparse_coo_tensor_with_dims.out
+
+- func: _sparse_coo_tensor_with_dims_and_tensors(int sparse_dim, int dense_dim, SymInt[] size, Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False, bool? is_coalesced=None) -> Tensor
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta, Meta: new_with_dims_and_tensor_sparse_symint
+ autogen: _sparse_coo_tensor_with_dims_and_tensors.out
+
+- func: sparse_resize_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: sparse_resize_
+ autogen: sparse_resize, sparse_resize.out
+
+- func: sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: sparse_resize_and_clear_
+ autogen: sparse_resize_and_clear, sparse_resize_and_clear.out
+
+- func: sparse_mask(Tensor self, Tensor mask) -> Tensor
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_mask
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_mask_sparse_compressed
+ autogen: sparse_mask.out
+
+- func: _sparse_mask_projection(Tensor self, Tensor mask, bool accumulate_matches=False) -> Tensor
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_mask_projection
+ autogen: _sparse_mask_projection.out
+
+- func: _to_cpu(Tensor[] tensors) -> Tensor[]
+ variants: function
+
+- func: to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor
+ variants: method
+
+# Special case of to_dense with custom derivative
+- func: _to_dense(Tensor self, ScalarType? dtype=None, bool? masked_grad=None) -> Tensor
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_to_dense
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_dense
+ MkldnnCPU: mkldnn_to_dense
+ autogen: _to_dense.out
+
+- func: to_dense_backward(Tensor grad, Tensor input, bool? masked_grad=None) -> Tensor
+
+- func: sparse_dim(Tensor self) -> int
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: sparse_dim_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_dim_sparse_csr
+ CompositeExplicitAutograd: sparse_dim_default
+ device_check: NoCheck
+ device_guard: False
+
+# legacy method
+- func: _dimI(Tensor self) -> int
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: sparse_dim_sparse
+ device_check: NoCheck
+ device_guard: False
+
+- func: dense_dim(Tensor self) -> int
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: dense_dim_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: dense_dim_sparse_csr
+ CompositeExplicitAutograd: dense_dim_default
+ device_check: NoCheck
+ device_guard: False
+
+# legacy method
+- func: _dimV(Tensor self) -> int
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: dense_dim_sparse
+ device_check: NoCheck
+ device_guard: False
+
+- func: _nnz(Tensor self) -> int
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: _nnz_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: _nnz_sparse_csr
+ device_check: NoCheck
+ device_guard: False
+
+# NOTE: [ coalesce autograd ]
+# coalesce returns self directly for already coalesced sparse tensors.
+# This means coalesce cannot have a derivative registered, otherwise it creates
+# circular references in the autograd graph (see gh-52874).
+# Instead, the derivative is registered on the slow-path "_coalesce"
+- func: coalesce(Tensor(a) self) -> Tensor(a)
+ variants: method
+
+- func: _coalesce(Tensor self) -> Tensor
+ dispatch:
+ SparseCPU: _coalesce_sparse_cpu
+ SparseCUDA: _coalesce_sparse_cuda
+ autogen: _coalesce.out
+
+- func: is_coalesced(Tensor self) -> bool
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: is_coalesced_sparse
+ CompositeExplicitAutograd: is_coalesced_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: _indices(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: _indices_sparse
+ device_check: NoCheck
+ device_guard: False
+
+- func: _values(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: _values_sparse
+ device_check: NoCheck
+ device_guard: False
+
+# This method doesn't do any check but only directly sets the flag. So it can be
+# a bit unsafe. Similar to _indices and _values, this is useful for implementing
+# custom sparse operations in Python/C++ extension.
+- func: _coalesced_(Tensor(a!) self, bool coalesced) -> Tensor(a!)
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: _coalesced_sparse_
+ device_check: NoCheck
+ device_guard: False
+ autogen: _coalesced, _coalesced.out
+
+- func: indices(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: indices_sparse
+ CompositeExplicitAutograd: indices_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: values(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: values_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: values_sparse_csr
+ NestedTensorCPU, NestedTensorCUDA: values_nested
+ CompositeExplicitAutograd: values_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: crow_indices(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: crow_indices_sparse_csr
+ CompositeExplicitAutograd: crow_indices_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: col_indices(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: col_indices_sparse_csr
+ CompositeExplicitAutograd: col_indices_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: ccol_indices(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: ccol_indices_sparse_csr
+ CompositeExplicitAutograd: ccol_indices_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: row_indices(Tensor(a) self) -> Tensor(a)
+ variants: method
+ dispatch:
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: row_indices_sparse_csr
+ CompositeExplicitAutograd: row_indices_default
+ device_check: NoCheck
+ device_guard: False
+
+- func: hspmm.out(Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ SparseCPU: hspmm_out_sparse_cpu
+ SparseCUDA: hspmm_out_sparse_cuda
+
+- func: hspmm(Tensor mat1, Tensor mat2) -> Tensor
+ dispatch:
+ SparseCPU: hspmm_sparse_cpu
+ SparseCUDA: hspmm_sparse_cuda
+
+- func: copy_sparse_to_sparse_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
+ device_check: NoCheck # Allows copy into different device
+ variants: function
+ dispatch:
+ SparseCPU, SparseCUDA, SparseMeta: copy_sparse_
+ autogen: copy_sparse_to_sparse, copy_sparse_to_sparse.out
+
+# By adding the AutogradNestedTensor this makes this function CompositeImplicit-like for nested tensors
+- func: unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[]
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: unbind
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_unbind
+
+- func: unbind.Dimname(Tensor(a -> *) self, Dimname dim) -> Tensor(a)[]
+ variants: function, method
+
+- func: to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor
+ variants: method
+
+# Special case of to_sparse.sparse_dim with custom derivative
+- func: _to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor
+ variants: method
+ dispatch:
+ CPU, CUDA: dense_to_sparse
+ SparseCPU, SparseCUDA: sparse_coo_to_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse
+ autogen: _to_sparse.sparse_dim_out
+
+- func: to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor
+ variants: method
+
+# Special case of to_sparse with custom derivative
+- func: _to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor
+ variants: method
+ dispatch:
+ CPU, CUDA: dense_to_sparse
+ SparseCPU, SparseCUDA: sparse_coo_to_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse
+ autogen: _to_sparse.out
+
+- func: to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor
+ variants: method
+
+# Special case of to_sparse_csr with custom derivative
+- func: _to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor
+ variants: method
+ dispatch:
+ CPU, CUDA: dense_to_sparse_csr
+ SparseCPU, SparseCUDA: coo_to_sparse_csr
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_csr
+ autogen: _to_sparse_csr.out
+
+- func: to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor
+ variants: method
+
+# Special case of to_sparse_csc with custom derivative
+- func: _to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor
+ variants: method
+ dispatch:
+ CPU, CUDA: dense_to_sparse_csc
+ SparseCPU, SparseCUDA: coo_to_sparse_csc
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_csc
+ autogen: _to_sparse_csc.out
+
+- func: to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+ variants: method
+
+# Special case of to_sparse_bsr with custom derivative
+- func: _to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+ variants: method
+ dispatch:
+ CPU, CUDA: dense_to_sparse_bsr
+ SparseCPU, SparseCUDA: coo_to_sparse_bsr
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_bsr
+ autogen: _to_sparse_bsr.out
+
+- func: to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+ variants: method
+
+# Special case of to_sparse_bsc with custom derivative
+- func: _to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor
+ variants: method
+ dispatch:
+ CPU, CUDA: dense_to_sparse_bsc
+ SparseCPU, SparseCUDA: coo_to_sparse_bsc
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sparse_compressed_to_sparse_bsc
+ autogen: _to_sparse_bsc.out
+
+- func: _to_sparse_semi_structured(Tensor dense) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CUDA: _to_sparse_semi_structured
+
+- func: to_mkldnn(Tensor self, ScalarType? dtype=None) -> Tensor
+ variants: method
+ dispatch:
+ CPU: dense_to_mkldnn
+ autogen: to_mkldnn.out
+
+- func: mkldnn_reorder_conv2d_weight(Tensor self, SymInt[2] padding=0, SymInt[2] stride=1, SymInt[2] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor
+ variants: function
+ python_module: nn
+ dispatch:
+ MkldnnCPU: mkldnn_reorder_conv2d_weight
+ autogen: mkldnn_reorder_conv2d_weight.out
+
+- func: mkldnn_reorder_conv3d_weight(Tensor self, SymInt[3] padding=0, SymInt[3] stride=1, SymInt[3] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor
+ variants: function
+ python_module: nn
+ dispatch:
+ MkldnnCPU: mkldnn_reorder_conv3d_weight
+ autogen: mkldnn_reorder_conv3d_weight.out
+
+- func: to_mkldnn_backward(Tensor grad, Tensor input) -> Tensor
+
+- func: quantize_per_tensor_dynamic(Tensor self, ScalarType dtype, bool reduce_range) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: quantize_per_tensor_dynamic
+ autogen: quantize_per_tensor_dynamic.out
+
+- func: quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType dtype) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: quantize_per_tensor
+ autogen: quantize_per_tensor.out
+
+- func: quantize_per_tensor.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: quantize_per_tensor_tensor_qparams
+ autogen: quantize_per_tensor.tensor_qparams_out
+
+- func: quantize_per_tensor.tensors(Tensor[] tensors, Tensor scales, Tensor zero_points, ScalarType dtype) -> Tensor[]
+ variants: function
+ dispatch:
+ CPU: quantize_per_tensor_list_cpu
+ autogen: quantize_per_tensor.tensors_out
+
+- func: quantize_per_channel(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: quantize_per_channel
+ autogen: quantize_per_channel.out
+
+- func: dequantize.self(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ CPU, CUDA: dequantize_cpu_or_cuda
+ QuantizedCPU, QuantizedCUDA: dequantize_quantized
+ autogen: dequantize.self_out
+
+- func: dequantize.tensors(Tensor[] tensors) -> Tensor[]
+ variants: function
+ dispatch:
+ QuantizedCPU: dequantize_tensors_quantized_cpu
+ autogen: dequantize.tensors_out
+
+- func: q_scale(Tensor self) -> float
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: q_scale_quant
+
+- func: q_zero_point(Tensor self) -> int
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: q_zero_point_quant
+
+- func: q_per_channel_scales(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: q_per_channel_scales
+ autogen: q_per_channel_scales.out
+
+- func: q_per_channel_zero_points(Tensor self) -> Tensor
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: q_per_channel_zero_points
+ autogen: q_per_channel_zero_points.out
+
+- func: q_per_channel_axis(Tensor self) -> int
+ variants: function, method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: q_per_channel_axis
+
+- func: int_repr(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ QuantizedCPU: int_repr_quantized_cpu
+ QuantizedCUDA: int_repr_quantized_cuda
+ autogen: int_repr.out
+
+- func: _make_per_tensor_quantized_tensor(Tensor self, float scale, int zero_point) -> Tensor
+ dispatch:
+ CPU: make_per_tensor_quantized_tensor_cpu
+ CUDA: make_per_tensor_quantized_tensor_cuda
+ autogen: _make_per_tensor_quantized_tensor.out
+
+- func: _make_per_channel_quantized_tensor(Tensor self, Tensor scale, Tensor zero_point, int axis) -> Tensor
+ dispatch:
+ CPU: make_per_channel_quantized_tensor_cpu
+ CUDA: make_per_channel_quantized_tensor_cuda
+ autogen: _make_per_channel_quantized_tensor.out
+
+- func: qscheme(Tensor self) -> QScheme
+ variants: method
+ dispatch:
+ QuantizedCPU, QuantizedCUDA: qscheme_quant
+
+- func: fake_quantize_per_tensor_affine(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: fake_quantize_per_tensor_affine.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: fake_quantize_per_tensor_affine_cachemask(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+ variants: function
+ dispatch:
+ CPU, CUDA: fake_quantize_per_tensor_affine_cachemask
+ autogen: fake_quantize_per_tensor_affine_cachemask.out
+
+- func: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+ variants: function
+ dispatch:
+ CPU, CUDA: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams
+ autogen: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams.out
+
+- func: fake_quantize_per_tensor_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor
+ variants: function
+
+- func: _fake_quantize_learnable_per_tensor_affine(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: _fake_quantize_learnable_per_tensor_affine
+ autogen: _fake_quantize_learnable_per_tensor_affine.out
+
+- func: _fake_quantize_learnable_per_tensor_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU, CUDA: _fake_quantize_learnable_per_tensor_affine_backward
+
+- func: fake_quantize_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: fake_quantize_per_channel_affine_cachemask(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> (Tensor output, Tensor mask)
+ variants: function
+ dispatch:
+ CPU, CUDA: fake_quantize_per_channel_affine_cachemask
+ autogen: fake_quantize_per_channel_affine_cachemask.out
+
+- func: fake_quantize_per_channel_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor
+ variants: function
+
+- func: _fake_quantize_learnable_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: _fake_quantize_learnable_per_channel_affine
+ autogen: _fake_quantize_learnable_per_channel_affine.out
+
+- func: _fake_quantize_learnable_per_channel_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU, CUDA: _fake_quantize_learnable_per_channel_affine_backward
+
+- func: fused_moving_avg_obs_fake_quant(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> Tensor
+ variants: function
+
+- func: _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask)
+ dispatch:
+ CPU: fused_moving_avg_obs_fake_quant_cpu
+ CUDA: fused_moving_avg_obs_fake_quant_cuda
+ autogen: _fused_moving_avg_obs_fq_helper_functional, _fused_moving_avg_obs_fq_helper.out
+
+- func: _choose_qparams_per_tensor(Tensor self, bool reduce_range=False) -> (float, int)
+ variants: function
+
+- func: _saturate_weight_to_fp16(Tensor weight) -> Tensor
+ variants: function
+
+- func: choose_qparams_optimized(Tensor input, int numel, int n_bins, float ratio, int bit_width) -> (Tensor, Tensor)
+ variants: function
+
+- func: _autocast_to_reduced_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) -> Tensor(a)
+ variants: method
+ device_guard: False
+
+- func: _autocast_to_full_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled) -> Tensor(a)
+ variants: method
+ device_guard: False
+
+- func: _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: _to_copy
+ NestedTensorCPU, NestedTensorCUDA: _to_copy_nested
+ autogen: _to_copy.out
+ tags: core
+
+# to(Device) must not exist because all constructors of Device also works for
+# TensorOptions. Otherwise, an ambiguity error is thrown.
+# See NOTE [ TensorOptions Constructors ].
+- func: to.dtype_layout(Tensor(a) self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+
+- func: to.device(Tensor(a) self, Device device, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+
+- func: to.dtype(Tensor(a) self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+
+- func: to.other(Tensor(a) self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+
+- func: meshgrid(Tensor[] tensors) -> Tensor[]
+
+# TODO: Two weeks after this lands, combine these two overloads,
+# making "indexing" optional. These are temporarily distinct for
+# forward-compatibility reasons.
+- func: meshgrid.indexing(Tensor[] tensors, *, str indexing) -> Tensor[]
+
+- func: cartesian_prod(Tensor[] tensors) -> Tensor
+ variants: function
+ tags: maybe_aliasing_or_mutating
+
+- func: combinations(Tensor self, int r=2, bool with_replacement=False) -> Tensor
+ variants: function
+
+- func: item(Tensor self) -> Scalar
+ tags: data_dependent_output
+ variants: method
+
+- func: result_type.Tensor(Tensor tensor, Tensor other) -> ScalarType
+ variants: function
+
+- func: result_type.Scalar(Tensor tensor, Scalar other) -> ScalarType
+ variants: function
+
+- func: result_type.Scalar_Tensor(Scalar scalar, Tensor tensor) -> ScalarType
+ variants: function
+
+- func: result_type.Scalar_Scalar(Scalar scalar1, Scalar scalar2) -> ScalarType
+
+- func: can_cast(ScalarType from_, ScalarType to) -> bool
+ variants: function
+
+- func: promote_types(ScalarType type1, ScalarType type2) -> ScalarType
+ variants: function
+
+# NB: Does NOT check precondition that numel == 1
+- func: _local_scalar_dense(Tensor self) -> Scalar
+ tags: [core, data_dependent_output]
+ dispatch:
+ CPU: _local_scalar_dense_cpu
+ CUDA: _local_scalar_dense_cuda
+ MPS: _local_scalar_dense_mps
+ variants: function
+
+# MPS LSTM implementation
+
+- func: _lstm_mps(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ MPS: _lstm_mps
+ autogen: _lstm_mps.out
+ tags: nondeterministic_seeded
+
+- func: lstm_mps_backward(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor[], Tensor[])
+ dispatch:
+ MPS: lstm_mps_backward
+ autogen: lstm_mps_backward.out
+
+
+# Fused RNN kernels
+- func: _thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: _thnn_fused_lstm_cell_cuda
+ autogen: _thnn_fused_lstm_cell.out
+
+# NB: The composite version of this function below is a simple wrapper that duplicates some of the outputs
+# It is necessary to avoid triggering TensorImpl use count checks in debug mode
+# NB: this is function is NOT differentiable
+- func: _thnn_fused_lstm_cell_backward_impl(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: _thnn_fused_lstm_cell_backward_impl_cuda
+ autogen: _thnn_fused_lstm_cell_backward_impl.out
+
+- func: _thnn_fused_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+
+- func: _thnn_differentiable_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor input_gates, Tensor hidden_gates, Tensor? input_bias, Tensor? hidden_bias, Tensor cx, Tensor cy) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+
+- func: _thnn_fused_gru_cell(Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor)
+ dispatch:
+ CUDA: _thnn_fused_gru_cell_cuda
+ autogen: _thnn_fused_gru_cell.out
+
+- func: _thnn_fused_gru_cell_backward(Tensor grad_hy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: _thnn_fused_gru_cell_backward_cuda
+ autogen: _thnn_fused_gru_cell_backward.out
+
+- func: _thnn_differentiable_gru_cell_backward(Tensor grad_hy, Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias, Tensor? hidden_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
+
+# RNN cells and layers
+- func: lstm.input(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: rnn_tanh.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: rnn_tanh.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: rnn_relu.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+ tags: nondeterministic_seeded
+
+- func: lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> (Tensor, Tensor)
+
+- func: gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
+
+- func: rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
+
+- func: rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
+
+# Quantized RNN layer registration has been moved to C10 dispatch in `RNN.cpp`
+
+# Quantized RNN layers
+# - func: quantized_lstm(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)
+
+
+# - func: quantized_lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor)
+
+
+# Quantized GRU layers
+
+# - func: quantized_gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)
+#
+
+# - func: quantized_gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
+#
+
+# Quantized RNN cells
+- func: quantized_lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> (Tensor, Tensor)
+
+- func: quantized_gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor
+
+- func: quantized_rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor
+
+- func: quantized_rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor
+
+# PackedSequence utilities
+- func: _pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor)
+ dispatch:
+ CompositeExplicitAutograd: _pack_padded_sequence
+ autogen: _pack_padded_sequence.out
+
+- func: _pack_padded_sequence_backward(Tensor grad, SymInt[] input_size, Tensor batch_sizes, bool batch_first) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd: _pack_padded_sequence_backward_symint
+
+- func: _pad_packed_sequence(Tensor data, Tensor batch_sizes, bool batch_first, Scalar padding_value, int total_length) -> (Tensor, Tensor)
+
+# wrappers for legacy TH methods
+
+- func: set_.source_Storage(Tensor(a!) self, Storage source) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU, CUDA, Meta, MPS: set_
+ autogen: set.source_Storage, set.source_Storage_out
+ tags: inplace_view
+
+- func: set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU: set_storage_cpu_
+ Meta: set_storage_meta__symint
+ CUDA: set_storage_cuda_
+ MPS: set_storage_mps_
+ QuantizedCPU, QuantizedCUDA: set_storage_quantized_
+ autogen: set.source_Storage_storage_offset, set.source_Storage_storage_offset_out
+ tags: inplace_view
+
+- func: set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: set__symint
+ tags: inplace_view
+
+- func: set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU, CUDA, Meta, MPS: set_tensor_
+ autogen: set.source_Tensor, set.source_Tensor_out
+ tags: inplace_view
+
+- func: set_(Tensor(a!) self) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CPU: set_cpu_
+ CUDA: set_cuda_
+ Meta: set_meta_
+ MPS: set_mps_
+ autogen: set, set.out
+ tags: inplace_view
+
+# Not making it CompositeImplicitAutograd because lift
+# should be a primitive w.r.t. functorch
+
+# TODO: this should have a view annotation
+# TODO: shouldn't be a method
+- func: lift(Tensor self) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: lift
+ autogen: lift.out
+
+# lift_fresh is called with an argument that is guaranteed to be
+# fresh (i.e., newly allocated). This is ONLY called from a
+# torch.tensor call; if you FX trace a lift_fresh, you are obligated
+# to convert this into a lift_fresh_copy (because FX will violate the
+# freshness invariant when tracing).
+- func: lift_fresh(Tensor(a) self) -> Tensor(a)
+ dispatch:
+ CompositeExplicitAutograd: lift_fresh
+
+# Like lift, but it clones the input.
+- func: lift_fresh_copy(Tensor self) -> Tensor
+ tags: view_copy
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: lift_fresh_copy
+ autogen: lift_fresh_copy.out
+
+- func: is_set_to(Tensor self, Tensor tensor) -> bool
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU, CUDA, MPS: is_set_to
+
+- func: masked_fill_.Scalar(Tensor(a!) self, Tensor mask, Scalar value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU: masked_fill__cpu
+ CUDA: masked_fill__cuda
+ QuantizedCPU: masked_fill__quantized_cpu
+ QuantizedCUDA: masked_fill__quantized_cuda
+ MPS: masked_fill__mps
+ autogen: masked_fill.Scalar_out
+
+- func: masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: masked_fill
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_masked_fill
+ tags: pointwise
+
+- func: masked_fill_.Tensor(Tensor(a!) self, Tensor mask, Tensor value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU: masked_fill__cpu
+ CUDA: masked_fill__cuda
+ QuantizedCPU: masked_fill__quantized_cpu
+ QuantizedCUDA: masked_fill__quantized_cuda
+ MPS: masked_fill__mps
+ autogen: masked_fill.Tensor_out
+
+- func: masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: masked_fill
+
+- func: masked_scatter_(Tensor(a!) self, Tensor mask, Tensor source) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CPU: masked_scatter__cpu
+ CUDA: masked_scatter__cuda
+ MPS: masked_scatter__mps
+ autogen: masked_scatter.out
+
+- func: masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: masked_scatter
+ tags: core
+
+- func: masked_scatter_backward(Tensor grad_output, Tensor mask, SymInt[] sizes) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: masked_scatter_backward_symint
+
+- func: _masked_softmax(Tensor self, Tensor mask, int? dim=None, int? mask_type=None) -> Tensor
+ dispatch:
+ CUDA: masked_softmax_cuda
+ CPU: masked_softmax_cpu
+ autogen: _masked_softmax.out
+
+- func: _masked_softmax_backward(Tensor grad_output, Tensor output, Tensor mask, int? dim=None) -> Tensor
+ dispatch:
+ CUDA: masked_softmax_backward_cuda
+ CPU: masked_softmax_backward_cpu
+ autogen: _masked_softmax_backward.out
+
+- func: view(Tensor(a) self, SymInt[] size) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ ZeroTensor, Meta, CPU, CUDA, QuantizedCPU, QuantizedCUDA, MPS: view
+ MkldnnCPU: mkldnn_view
+ NestedTensorCPU, NestedTensorCUDA: view_nested
+ tags: core
+
+# Warning: If you want to change the name or overload name of this
+# operator, you might also want to change the `isBlockListedSchema`
+# function in `torch/csrc/jit/frontend/schema_catching.cpp`.
+# The name and overload name of this operator is hardcoded in that
+# function in order to workaround a bug:
+# https://github.com/pytorch/pytorch/issues/47964
+- func: view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: view_dtype
+
+- func: put_(Tensor(a!) self, Tensor index, Tensor source, bool accumulate=False) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CPU, CUDA: put_
+ autogen: put.out
+
+- func: put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: put
+
+- func: index_add.out(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ precomputed:
+ - dim -> int dim
+ dispatch:
+ CPU: index_add_cpu_out
+ CUDA: index_add_cuda_out
+ MPS: index_add_mps_out
+
+- func: index_add_(Tensor(a!) self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor(a!)
+ structured_delegate: index_add.out
+ variants: method
+
+- func: index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor
+ structured_delegate: index_add.out
+ variants: function, method
+
+- func: index_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor
+ variants: function, method
+
+- func: index_reduce.out(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ precomputed:
+ - dim -> int dim
+ dispatch:
+ CPU: index_reduce_cpu_out
+ CUDA: index_reduce_cuda_out
+
+- func: index_reduce_(Tensor(a!) self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor(a!)
+ structured_delegate: index_reduce.out
+ variants: method
+
+- func: index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor
+ structured_delegate: index_reduce.out
+ variants: function, method
+
+- func: index_fill_.int_Scalar(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU: index_fill_
+ CUDA: index_fill_
+ MPS: index_fill_mps_
+ autogen: index_fill.int_Scalar_out
+
+- func: index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: index_fill
+
+- func: index_fill_.int_Tensor(Tensor(a!) self, int dim, Tensor index, Tensor value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU, CUDA: index_fill_
+ MPS: index_fill_mps_
+ autogen: index_fill.int_Tensor_out
+
+- func: index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ dispatch:
+ CompositeExplicitAutograd: index_fill
+
+- func: index_fill_.Dimname_Scalar(Tensor(a!) self, Dimname dim, Tensor index, Scalar value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: index_fill_.Dimname_Tensor(Tensor(a!) self, Dimname dim, Tensor index, Tensor value) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: index_fill.Dimname_Scalar(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: index_fill.Dimname_Tensor(Tensor self, Dimname dim, Tensor index, Tensor value) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+
+- func: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor
+ structured_delegate: scatter.src_out
+ variants: function, method
+ tags: core
+
+- func: scatter_.src(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!)
+ structured_delegate: scatter.src_out
+ variants: method
+
+- func: scatter.src_out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU, CUDA: scatter_src_out
+ MPS: scatter_src_out_mps
+
+- func: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor
+ structured_delegate: scatter.value_out
+ variants: function, method
+ tags: core
+
+- func: scatter_.value(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!)
+ structured_delegate: scatter.value_out
+ variants: method
+
+- func: scatter.value_out(Tensor self, int dim, Tensor index, Scalar value, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU, CUDA: scatter_value_out
+ MPS: scatter_value_out_mps
+
+- func: scatter.reduce(Tensor self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor
+ structured_delegate: scatter.reduce_out
+ variants: function, method
+
+- func: scatter_.reduce(Tensor(a!) self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor(a!)
+ structured_delegate: scatter.reduce_out
+ variants: method
+
+- func: scatter.reduce_out(Tensor self, int dim, Tensor index, Tensor src, *, str reduce, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU, CUDA: scatter_reduce_out
+ MPS: scatter_reduce_out_mps
+
+- func: scatter.value_reduce(Tensor self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor
+ structured_delegate: scatter.value_reduce_out
+ variants: function, method
+
+- func: scatter_.value_reduce(Tensor(a!) self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor(a!)
+ structured_delegate: scatter.value_reduce_out
+ variants: method
+
+- func: scatter.value_reduce_out(Tensor self, int dim, Tensor index, Scalar value, *, str reduce, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU, CUDA: scatter_value_reduce_out
+ MPS: scatter_value_reduce_out_mps
+
+- func: scatter.dimname_src(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor
+ variants: function, method
+
+- func: scatter.dimname_value(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor
+ variants: function, method
+
+- func: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor
+ structured_delegate: scatter_add.out
+ variants: function, method
+ tags: core
+
+- func: scatter_add_(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!)
+ structured_delegate: scatter_add.out
+ variants: method
+
+- func: scatter_add.out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU, CUDA: scatter_add
+ MPS: scatter_add_mps_out
+
+- func: scatter_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor
+ variants: function, method
+
+- func: scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor
+ structured_delegate: scatter_reduce.two_out
+ variants: function, method
+ tags: core
+
+- func: scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor(a!)
+ structured_delegate: scatter_reduce.two_out
+ variants: method
+
+- func: scatter_reduce.two_out(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ variants: function
+ dispatch:
+ CPU, CUDA, MPS: scatter_reduce_two
+
+- func: eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ structured_delegate: eq.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: eq.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: bitwise_and.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ variants: function
+ dispatch:
+ CPU, CUDA: bitwise_and_out
+ MPS: bitwise_and_out_mps
+ tags: pointwise
+
+- func: bitwise_and.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_and_out
+ tags: pointwise
+
+- func: bitwise_and.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_and
+ tags: [core, pointwise]
+
+- func: bitwise_and.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_and
+ autogen: bitwise_and.Scalar_Tensor_out
+ tags: pointwise
+
+- func: bitwise_and.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ structured_delegate: bitwise_and.Tensor_out
+ tags: [core, pointwise]
+
+- func: bitwise_and_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: bitwise_and_
+ tags: pointwise
+
+- func: bitwise_and_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: bitwise_and.Tensor_out
+ tags: pointwise
+
+- func: __and__.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+
+- func: __and__.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+
+- func: __iand__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: __iand__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: bitwise_or.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ variants: function
+ dispatch:
+ CPU, CUDA: bitwise_or_out
+ MPS: bitwise_or_out_mps
+ tags: pointwise
+
+- func: bitwise_or.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_or_out
+ tags: pointwise
+
+- func: bitwise_or.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_or
+ tags: [core, pointwise]
+
+- func: bitwise_or.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_or
+ autogen: bitwise_or.Scalar_Tensor_out
+ tags: pointwise
+
+- func: bitwise_or.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ structured_delegate: bitwise_or.Tensor_out
+ tags: [core, pointwise]
+
+- func: bitwise_or_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: bitwise_or_
+ tags: pointwise
+
+- func: bitwise_or_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: bitwise_or.Tensor_out
+ tags: pointwise
+
+- func: __or__.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+
+- func: __or__.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+
+- func: __ior__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: __ior__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: bitwise_xor.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ variants: function
+ dispatch:
+ CPU, CUDA: bitwise_xor_out
+ MPS: bitwise_xor_out_mps
+ tags: pointwise
+
+- func: bitwise_xor.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_xor_out
+ tags: pointwise
+
+- func: bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_xor
+ tags: [core, pointwise]
+
+- func: bitwise_xor.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_xor
+ autogen: bitwise_xor.Scalar_Tensor_out
+ tags: pointwise
+
+- func: bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ structured_delegate: bitwise_xor.Tensor_out
+ tags: [core, pointwise]
+
+- func: bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: bitwise_xor_
+ tags: pointwise
+
+- func: bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: bitwise_xor.Tensor_out
+ tags: pointwise
+
+- func: __xor__.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: __xor__.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: __ixor__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: pointwise
+
+- func: __ixor__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: pointwise
+
+- func: __lshift__.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA, MPS: __lshift__
+ tags: pointwise
+
+- func: __lshift__.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA, MPS: __lshift__
+ tags: pointwise
+
+- func: __ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU, CUDA, MPS: __ilshift__
+ autogen: __lshift__.Scalar_out
+ tags: pointwise
+
+- func: __ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU, CUDA, MPS: __ilshift__
+ autogen: __lshift__.Tensor_out
+ tags: pointwise
+
+- func: bitwise_left_shift.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: bitwise_left_shift.Tensor_out
+ tags: pointwise
+
+- func: bitwise_left_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: bitwise_left_shift.Tensor_out
+ tags: pointwise
+
+- func: bitwise_left_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: bitwise_left_shift_out
+ tags: pointwise
+
+- func: bitwise_left_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_left_shift
+ tags: pointwise
+
+- func: bitwise_left_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: bitwise_left_shift_
+ tags: pointwise
+
+- func: bitwise_left_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_left_shift_out
+ tags: pointwise
+
+- func: bitwise_left_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_left_shift
+ autogen: bitwise_left_shift.Scalar_Tensor_out
+ tags: pointwise
+
+- func: __rshift__.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA, MPS: __rshift__
+ tags: pointwise
+
+- func: __rshift__.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA, MPS: __rshift__
+ tags: pointwise
+
+- func: __irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU, CUDA, MPS: __irshift__
+ autogen: __rshift__.Scalar_out
+
+- func: __irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CPU, CUDA, MPS: __irshift__
+ autogen: __rshift__.Tensor_out
+
+- func: bitwise_right_shift.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function, method
+ structured_delegate: bitwise_right_shift.Tensor_out
+ tags: pointwise
+
+- func: bitwise_right_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: bitwise_right_shift.Tensor_out
+ tags: pointwise
+
+- func: bitwise_right_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: bitwise_right_shift_out
+ tags: pointwise
+
+- func: bitwise_right_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_right_shift
+ tags: pointwise
+
+- func: bitwise_right_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: bitwise_right_shift_
+ tags: pointwise
+
+- func: bitwise_right_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_right_shift_out
+ tags: pointwise
+
+- func: bitwise_right_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: bitwise_right_shift
+ autogen: bitwise_right_shift.Scalar_Tensor_out
+ tags: pointwise
+
+- func: tril_(Tensor(a!) self, int diagonal=0) -> Tensor(a!)
+ structured_delegate: tril.out
+ variants: method
+
+- func: triu_(Tensor(a!) self, int diagonal=0) -> Tensor(a!)
+ structured_delegate: triu.out
+ variants: method
+
+- func: digamma_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: digamma.out
+ variants: method
+ tags: pointwise
+
+- func: lerp_.Scalar(Tensor(a!) self, Tensor end, Scalar weight) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: lerp.Scalar_out
+ tags: pointwise
+
+- func: lerp_.Tensor(Tensor(a!) self, Tensor end, Tensor weight) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: lerp.Tensor_out
+ tags: pointwise
+
+- func: addbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CPU, CUDA, XPU: addbmm_
+ MPS: addbmm_mps_
+
+- func: addbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA, XPU: addbmm_out
+ MPS: addbmm_out_mps
+
+- func: addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, CUDA, XPU: addbmm
+ MPS: addbmm_mps
+
+- func: random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: random_
+ Meta: random_meta_
+ MPS: random_mps_
+ autogen: random.from, random.from_out
+
+- func: random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: random_
+ Meta: random_meta_
+ MPS: random_mps_
+ autogen: random.to, random.to_out
+
+- func: random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: random_
+ MPS: random_mps_
+ Meta: random_meta_
+ autogen: random, random.out
+
+- func: uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: uniform_
+ MPS: uniform_mps_
+ Meta: uniform_meta_
+ autogen: uniform, uniform.out
+
+- func: cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: cauchy_
+ autogen: cauchy, cauchy.out
+
+- func: log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: log_normal_
+ autogen: log_normal, log_normal.out
+
+- func: exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: exponential_
+ MPS: exponential_mps_
+ autogen: exponential, exponential.out
+
+- func: geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: geometric_
+
+ # wrappers for TH functions
+ autogen: geometric, geometric.out
+
+- func: diag.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: diag(Tensor self, int diagonal=0) -> Tensor
+ variants: method, function
+
+- func: cross.out(Tensor self, Tensor other, int? dim=None, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: cross(Tensor self, Tensor other, int? dim=None) -> Tensor
+ variants: method, function
+
+- func: triu.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: triu_cpu
+ CUDA: triu_cuda
+ MPS: triu_mps_out
+
+- func: triu(Tensor self, int diagonal=0) -> Tensor
+ structured_delegate: triu.out
+ variants: method, function
+
+- func: tril.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: tril_cpu
+ CUDA: tril_cuda
+ MPS: tril_mps_out
+
+- func: tril(Tensor self, int diagonal=0) -> Tensor
+ structured_delegate: tril.out
+ variants: method, function
+
+- func: tril_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CPU: tril_indices_cpu
+ CUDA: tril_indices_cuda
+ MPS: tril_indices_mps
+ autogen: tril_indices.out
+
+- func: triu_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CPU: triu_indices_cpu
+ CUDA: triu_indices_cuda
+ MPS: triu_indices_mps
+ autogen: triu_indices.out
+
+- func: trace(Tensor self) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU: trace_cpu
+ CUDA: trace_cuda
+ MPS: trace_mps
+ autogen: trace.out
+
+- func: trace_backward(Tensor grad, SymInt[] sizes) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: trace_backward_symint
+
+- func: ne.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: ne_Scalar_out
+ MPS: ne_scalar_out_mps
+ QuantizedCPU: ne_out_quantized_cpu
+ tags: pointwise
+
+- func: ne.Scalar(Tensor self, Scalar other) -> Tensor
+ structured_delegate: ne.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: ne_quantized_cpu
+ tags: [core, pointwise]
+
+- func: ne.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: ne_Tensor_out
+ MPS: ne_tensor_out_mps
+ QuantizedCPU: ne_out_quantized_cpu
+ tags: pointwise
+
+- func: ne.Tensor(Tensor self, Tensor other) -> Tensor
+ structured_delegate: ne.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: ne_quantized_cpu
+ tags: [core, pointwise]
+
+- func: ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ structured_delegate: ne.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: ne.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+# not_equal, alias for torch.ne
+- func: not_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: not_equal.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: method, function
+
+- func: not_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: not_equal.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+
+- func: not_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: not_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: eq.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: eq_Scalar_out
+ MPS: eq_scalar_out_mps
+ QuantizedCPU: eq_out_quantized_cpu
+ tags: pointwise
+
+- func: eq.Scalar(Tensor self, Scalar other) -> Tensor
+ structured_delegate: eq.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: eq_quantized_cpu
+ NestedTensorCPU, NestedTensorCUDA: eq_scalar_nested
+ tags: [core, pointwise]
+
+- func: eq.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: eq_Tensor_out
+ MPS: eq_tensor_out_mps
+ QuantizedCPU: eq_out_quantized_cpu
+ tags: pointwise
+
+- func: eq.Tensor(Tensor self, Tensor other) -> Tensor
+ structured_delegate: eq.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: eq_quantized_cpu
+ NestedTensorCPU, NestedTensorCUDA: eq_tensor_nested
+ tags: [core, pointwise]
+
+- func: ge.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: ge_Scalar_out
+ MPS: ge_scalar_out_mps
+ QuantizedCPU: ge_out_quantized_cpu
+ tags: pointwise
+
+- func: ge.Scalar(Tensor self, Scalar other) -> Tensor
+ structured_delegate: ge.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: ge_quantized_cpu
+ NestedTensorCPU, NestedTensorCUDA: ge_scalar_nested
+ tags: [core, pointwise]
+
+- func: ge.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: ge_Tensor_out
+ MPS: ge_tensor_out_mps
+ QuantizedCPU: ge_out_quantized_cpu
+ tags: pointwise
+
+- func: ge.Tensor(Tensor self, Tensor other) -> Tensor
+ structured_delegate: ge.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: ge_quantized_cpu
+ tags: [core, pointwise]
+
+- func: ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ structured_delegate: ge.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: ge.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+# greater_equal, alias for torch.ge
+- func: greater_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater_equal.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: method, function
+
+- func: greater_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater_equal.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+
+- func: greater_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: greater_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: le.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: le_Scalar_out
+ MPS: le_scalar_out_mps
+ QuantizedCPU: le_out_quantized_cpu
+ tags: pointwise
+
+- func: le.Scalar(Tensor self, Scalar other) -> Tensor
+ structured_delegate: le.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: le_quantized_cpu
+ tags: [core, pointwise]
+
+- func: le.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: le_Tensor_out
+ MPS: le_tensor_out_mps
+ QuantizedCPU: le_out_quantized_cpu
+ tags: pointwise
+
+- func: le.Tensor(Tensor self, Tensor other) -> Tensor
+ structured_delegate: le.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: le_quantized_cpu
+ tags: [core, pointwise]
+
+- func: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ structured_delegate: le.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: le.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+# less_equal, alias for torch.le
+- func: less_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less_equal.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: method, function
+
+- func: less_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less_equal.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+
+- func: less_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: less_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: gt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: gt_Scalar_out
+ MPS: gt_scalar_out_mps
+ QuantizedCPU: gt_out_quantized_cpu
+ tags: pointwise
+
+- func: gt.Scalar(Tensor self, Scalar other) -> Tensor
+ structured_delegate: gt.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: gt_quantized_cpu
+ NestedTensorCPU, NestedTensorCUDA: gt_scalar_nested
+ tags: [core, pointwise]
+
+- func: gt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: gt_Tensor_out
+ MPS: gt_tensor_out_mps
+ QuantizedCPU: gt_out_quantized_cpu
+ tags: pointwise
+
+- func: gt.Tensor(Tensor self, Tensor other) -> Tensor
+ structured_delegate: gt.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: gt_quantized_cpu
+ tags: [core, pointwise]
+
+- func: gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ structured_delegate: gt.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: gt.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+# greater, alias for torch.gt
+- func: greater.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: method, function
+
+- func: greater.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: greater.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+
+- func: greater_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: greater_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: lt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: lt_Scalar_out
+ MPS: lt_scalar_out_mps
+ QuantizedCPU: lt_out_quantized_cpu
+ tags: pointwise
+
+- func: lt.Scalar(Tensor self, Scalar other) -> Tensor
+ structured_delegate: lt.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: lt_quantized_cpu
+ tags: [core, pointwise]
+
+- func: lt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: lt_Tensor_out
+ MPS: lt_tensor_out_mps
+ QuantizedCPU: lt_out_quantized_cpu
+ tags: pointwise
+
+- func: lt.Tensor(Tensor self, Tensor other) -> Tensor
+ structured_delegate: lt.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ QuantizedCPU: lt_quantized_cpu
+ tags: [core, pointwise]
+
+- func: lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ structured_delegate: lt.Scalar_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+- func: lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: lt.Tensor_out
+ device_check: NoCheck # TensorIterator
+ variants: method
+
+# less, alias for torch.lt
+- func: less.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: method, function
+
+- func: less.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: less.Tensor(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+
+- func: less_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+
+- func: less_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: take.out(Tensor self, Tensor index, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: take_out
+
+- func: take(Tensor self, Tensor index) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, CUDA: take
+
+- func: take_along_dim.out(Tensor self, Tensor indices, int? dim=None, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: take_along_dim(Tensor self, Tensor indices, int? dim=None) -> Tensor
+ variants: method, function
+
+- func: index_select.out(Tensor self, int dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, QuantizedCPU: index_select_out_cpu_
+ CUDA, QuantizedCUDA: index_select_out_cuda
+ MPS: index_select_out_mps
+
+- func: index_select(Tensor self, int dim, Tensor index) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU: index_select_cpu_
+ QuantizedCPU: index_select_quantized_cpu_
+ CUDA: index_select_cuda
+ QuantizedCUDA: index_select_quantized_cuda
+ SparseCPU: index_select_sparse_cpu
+ SparseCUDA: index_select_sparse_cuda
+ MPS: index_select_mps
+ tags: core
+
+- func: index_select.dimname_out(Tensor self, Dimname dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: index_select.dimname(Tensor self, Dimname dim, Tensor index) -> Tensor
+ variants: method, function
+
+- func: index_select_backward(Tensor grad, SymInt[] self_sizes, int dim, Tensor index) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeImplicitAutograd: index_select_backward_symint
+
+- func: masked_select.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: masked_select_out_cpu
+ CUDA: masked_select_out_cuda
+ MPS: masked_select_out_mps
+ tags: dynamic_output_shape
+
+- func: masked_select(Tensor self, Tensor mask) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU: masked_select_cpu
+ CUDA: masked_select_cuda
+ MPS: masked_select_mps
+ tags: dynamic_output_shape
+
+- func: masked_select_backward(Tensor grad, Tensor input, Tensor mask) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+
+- func: nonzero.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: nonzero_out_cpu
+ CUDA: nonzero_out_cuda
+ MPS: nonzero_out_mps
+ tags: dynamic_output_shape
+
+- func: nonzero(Tensor self) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU: nonzero_cpu
+ CUDA: nonzero_cuda
+ MPS: nonzero_mps
+ tags: [dynamic_output_shape, core]
+
+- func: nonzero_static.out(Tensor self, *, int size, int fill_value=-1, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: nonzero_static_out_cpu
+ CUDA: nonzero_static_out_cuda
+
+- func: nonzero_static(Tensor self, *, int size, int fill_value=-1) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU: nonzero_static_cpu
+ CUDA: nonzero_static_cuda
+
+- func: nonzero_numpy(Tensor self) -> Tensor[]
+ variants: method, function
+
+- func: argwhere(Tensor self) -> Tensor
+ variants: method, function
+ tags: dynamic_output_shape
+
+- func: gather.out(Tensor self, int dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU, CUDA: gather_out
+ MPS: gather_out_mps
+
+- func: gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor
+ variants: method, function
+ structured_delegate: gather.out
+ tags: core
+
+- func: gather_backward(Tensor grad, Tensor self, int dim, Tensor index, bool sparse_grad) -> Tensor
+ variants: function
+ device_check: NoCheck
+ device_guard: False
+
+- func: gather.dimname_out(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!)
+
+- func: gather.dimname(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False) -> Tensor
+ variants: method, function
+
+- func: _gather_sparse_backward(Tensor self, int dim, Tensor index, Tensor grad) -> Tensor
+
+- func: addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: addcmul_out
+ MPS: addcmul_out_mps
+ tags: pointwise
+
+- func: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor
+ structured_delegate: addcmul.out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: addcmul_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!)
+ structured_delegate: addcmul.out
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: pointwise
+
+- func: addcdiv.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: addcdiv_out
+ MPS: addcdiv_out_mps
+ tags: pointwise
+
+- func: addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor
+ structured_delegate: addcdiv.out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!)
+ structured_delegate: addcdiv.out
+ device_check: NoCheck # TensorIterator
+ variants: method
+ tags: pointwise
+
+- func: cross_entropy_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, float label_smoothing=0.0) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: cross_entropy_loss_symint
+
+- func: triangular_solve.X(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False, *, Tensor(a!) X, Tensor(b!) M) -> (Tensor(a!) solution, Tensor(b!) cloned_coefficient)
+ structured: True
+ dispatch:
+ CPU, CUDA: triangular_solve_out
+ MPS: triangular_solve_mps_out
+ SparseCsrCPU: triangular_solve_out_sparse_csr_cpu
+ SparseCsrCUDA: triangular_solve_out_sparse_csr_cuda
+
+- func: triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient)
+ structured_delegate: triangular_solve.X
+ variants: method, function
+
+- func: _linalg_check_errors(Tensor info, str api_name, *, bool is_matrix) -> ()
+ dispatch:
+ CompositeExplicitAutograd: _linalg_check_errors
+
+- func: linalg_solve_triangular.out(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ dispatch:
+ CPU, CUDA: linalg_solve_triangular_out
+ MPS: linalg_solve_triangular_mps_out
+
+- func: linalg_solve_triangular(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False) -> Tensor
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_solve_triangular
+ MPS: linalg_solve_triangular_mps
+
+- func: linalg_vander(Tensor x, *, SymInt? N=None) -> Tensor
+ python_module: linalg
+ dispatch:
+ CompositeImplicitAutograd: linalg_vander_symint
+
+- func: svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V)
+
+- func: svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V)
+ variants: method, function
+
+# swapaxes, alias for transpose
+- func: swapaxes(Tensor(a) self, int axis0, int axis1) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: swapaxes_(Tensor(a!) self, int axis0, int axis1) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+
+# swapdims, alias for transpose
+- func: swapdims(Tensor(a) self, int dim0, int dim1) -> Tensor(a)
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+
+- func: swapdims_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ tags: inplace_view
+
+- func: cholesky.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: cholesky_out
+
+- func: cholesky(Tensor self, bool upper=False) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, CUDA: cholesky
+
+- func: cholesky_solve.out(Tensor self, Tensor input2, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: cholesky_solve_out
+
+- func: cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: cholesky_solve
+
+- func: _cholesky_solve_helper(Tensor self, Tensor A, bool upper) -> Tensor
+ variants: function
+ dispatch:
+ CPU: _cholesky_solve_helper_cpu
+ CUDA: _cholesky_solve_helper_cuda
+ autogen: _cholesky_solve_helper.out
+
+- func: cholesky_inverse(Tensor self, bool upper=False) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, CUDA: cholesky_inverse
+
+- func: cholesky_inverse.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: cholesky_inverse_out
+
+- func: qr.Q(Tensor self, bool some=True, *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R)
+
+- func: qr(Tensor self, bool some=True) -> (Tensor Q, Tensor R)
+ variants: method, function
+
+- func: geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau)
+ dispatch:
+ CPU, CUDA: geqrf_out
+
+- func: geqrf(Tensor self) -> (Tensor a, Tensor tau)
+ variants: method, function
+ dispatch:
+ CPU, CUDA: geqrf
+
+# orgqr, alias for linalg_householder_product
+- func: orgqr(Tensor self, Tensor input2) -> Tensor
+ variants: method, function
+
+- func: orgqr.out(Tensor self, Tensor input2, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: ormqr.out(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: ormqr_out
+
+- func: ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, CUDA: ormqr
+
+- func: _lu_with_info(Tensor self, bool pivot=True, bool check_errors=True) -> (Tensor LU, Tensor pivots, Tensor info)
+ variants: function
+
+- func: lu_solve.out(Tensor self, Tensor LU_data, Tensor LU_pivots, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: lu_solve(Tensor self, Tensor LU_data, Tensor LU_pivots) -> Tensor
+ variants: method, function
+
+# lu_unpack
+- func: lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U)
+ structured_delegate: lu_unpack.out
+ variants: function
+
+- func: lu_unpack.out(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True, *, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U)
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: lu_unpack_out
+
+# TODO: remove dispatch section when porting TH CUDA to ATen
+- func: multinomial.out(Tensor self, int num_samples, bool replacement=False, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: multinomial_out
+ MPS: multinomial_out_mps
+
+- func: multinomial(Tensor self, int num_samples, bool replacement=False, *, Generator? generator=None) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, CUDA: multinomial
+ MPS: multinomial_mps
+ tags: nondeterministic_seeded
+
+- func: lgamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: lgamma_out
+ MPS: lgamma_out_mps
+ tags: pointwise
+
+- func: lgamma_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: lgamma.out
+ variants: method
+ tags: pointwise
+
+- func: lgamma(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: lgamma.out
+ variants: method, function
+ tags: pointwise
+
+- func: digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: digamma_out
+ MPS: digamma_out_mps
+ tags: pointwise
+
+- func: digamma(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: digamma.out
+ variants: method, function
+ tags: pointwise
+
+- func: polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: polygamma_out
+ MPS: polygamma_out_mps
+ tags: pointwise
+
+- func: polygamma(int n, Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: polygamma.out
+ variants: method, function
+ tags: pointwise
+
+- func: polygamma_(Tensor(a!) self, int n) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: polygamma_
+ tags: pointwise
+
+- func: erfinv(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: erfinv.out
+ variants: method, function
+ dispatch:
+ SparseCPU, SparseCUDA: erfinv_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erfinv_sparse_csr
+ tags: pointwise
+
+- func: erfinv_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: erfinv.out
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: erfinv_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erfinv_sparse_csr_
+ tags: pointwise
+
+- func: erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: erfinv_out
+ MPS: erfinv_out_mps
+ SparseCPU, SparseCUDA: erfinv_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: erfinv_sparse_csr_out
+ tags: pointwise
+
+- func: i0(Tensor self) -> Tensor
+ structured_delegate: i0.out
+ variants: function, method
+ tags: pointwise
+
+- func: i0_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: i0.out
+ variants: function, method
+ tags: pointwise
+
+- func: i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: i0_out
+ tags: pointwise
+
+- func: sign(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sign.out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: sign_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sign_sparse_csr
+ tags: [core, pointwise]
+
+- func: sign_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: sign.out
+ variants: method
+ dispatch:
+ SparseCPU, SparseCUDA: sign_sparse_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sign_sparse_csr_
+ tags: pointwise
+
+- func: sign.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sign_out
+ MPS: sign_out_mps
+ SparseCPU, SparseCUDA: sign_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: sign_sparse_csr_out
+ tags: pointwise
+
+- func: signbit(Tensor self) -> Tensor
+ variants: function, method
+ structured_delegate: signbit.out
+ dispatch:
+ SparseCPU, SparseCUDA: signbit_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: signbit_sparse_csr
+ tags: pointwise
+
+- func: signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU: signbit_out
+ CUDA: signbit_out
+ MPS: signbit_out_mps
+ SparseCPU, SparseCUDA: signbit_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: signbit_sparse_csr_out
+ tags: pointwise
+
+- func: dist(Tensor self, Tensor other, Scalar p=2) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: dist
+ autogen: dist.out
+
+- func: atan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: atan2_out
+ MPS: atan2_out_mps
+ tags: [core, pointwise]
+
+- func: atan2_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: atan2.out
+ variants: method
+ tags: pointwise
+
+- func: atan2(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: atan2.out
+ variants: method, function
+ tags: [core, pointwise]
+# arctan2, alias of atan2
+
+- func: arctan2(Tensor self, Tensor other) -> Tensor
+ variants: method, function
+
+- func: arctan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+
+- func: arctan2_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ variants: method
+
+- func: lerp.Scalar_out(Tensor self, Tensor end, Scalar weight, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: lerp_Scalar
+ MPS: lerp_Scalar_mps
+ tags: pointwise
+
+- func: lerp.Tensor_out(Tensor self, Tensor end, Tensor weight, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: lerp_Tensor
+ MPS: lerp_Tensor_mps
+ tags: pointwise
+
+- func: lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ structured_delegate: lerp.Scalar_out
+ tags: pointwise
+
+- func: lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ structured_delegate: lerp.Tensor_out
+ tags: pointwise
+
+- func: histc.out(Tensor self, int bins=100, Scalar min=0, Scalar max=0, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, MPS: histogram_histc_out
+ CUDA: _histc_out_cuda
+
+- func: histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor
+ variants: method, function
+ dispatch:
+ CPU, MPS: histogram_histc
+ CUDA: _histc_cuda
+
+- func: histogram.bins_tensor_out(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges)
+ dispatch:
+ CPU, MPS: histogram_out
+
+- func: histogram.bins_tensor(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges)
+ variants: method, function
+ dispatch:
+ CPU, MPS: histogram
+
+- func: histogram.bin_ct_out(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges)
+ dispatch:
+ CPU, MPS: histogram_out
+
+- func: histogram.bin_ct(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges)
+ variants: method, function
+ dispatch:
+ CPU, MPS: histogram
+
+- func: _histogramdd_bin_edges(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor[]
+ dispatch:
+ CPU, MPS: histogramdd_bin_edges
+ autogen: _histogramdd_bin_edges.out
+
+- func: _histogramdd_from_bin_cts(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor
+ dispatch:
+ CPU, MPS: _histogramdd
+ autogen: _histogramdd_from_bin_cts.out
+
+- func: _histogramdd_from_bin_tensors(Tensor self, Tensor[] bins, *, Tensor? weight=None, bool density=False) -> Tensor
+ dispatch:
+ CPU, MPS: _histogramdd
+ autogen: _histogramdd_from_bin_tensors.out
+
+- func: histogramdd(Tensor self, int[] bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges)
+
+- func: histogramdd.int_bins(Tensor self, int bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges)
+
+- func: histogramdd.TensorList_bins(Tensor self, Tensor[] bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges)
+
+- func: fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: fmod_out
+ tags: pointwise
+
+- func: fmod.Scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: fmod
+ tags: [core, pointwise]
+
+- func: fmod_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: fmod_
+ tags: pointwise
+
+- func: fmod.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: fmod_out
+ MPS: fmod_mps_out
+ tags: pointwise
+
+- func: fmod.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: fmod.Tensor_out
+ variants: method, function
+ tags: [core, pointwise]
+
+- func: fmod_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: fmod.Tensor_out
+ tags: pointwise
+
+- func: hypot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: hypot_out
+ MPS: hypot_out_mps
+ tags: pointwise
+
+- func: hypot(Tensor self, Tensor other) -> Tensor
+ structured_delegate: hypot.out
+ variants: method, function
+ tags: pointwise
+
+- func: hypot_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: hypot.out
+ variants: method
+ tags: pointwise
+
+- func: igamma.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: igamma_out
+ tags: pointwise
+
+- func: igamma(Tensor self, Tensor other) -> Tensor
+ structured_delegate: igamma.out
+ variants: method, function
+ tags: pointwise
+
+- func: igamma_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: igamma.out
+ variants: method
+ tags: pointwise
+
+- func: igammac.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: igammac_out
+ tags: pointwise
+
+- func: igammac(Tensor self, Tensor other) -> Tensor
+ structured_delegate: igammac.out
+ variants: method, function
+ tags: pointwise
+
+- func: igammac_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: igammac.out
+ variants: method
+ tags: pointwise
+
+- func: nextafter.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: nextafter_out
+ tags: pointwise
+
+- func: nextafter(Tensor self, Tensor other) -> Tensor
+ structured_delegate: nextafter.out
+ variants: method, function
+ tags: pointwise
+
+- func: nextafter_(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ structured_delegate: nextafter.out
+ variants: method
+ tags: pointwise
+
+- func: remainder.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: remainder_out
+ tags: pointwise
+
+- func: remainder.Scalar(Tensor self, Scalar other) -> Tensor
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: remainder
+ tags: [core, pointwise]
+
+- func: remainder_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
+ variants: method
+ dispatch:
+ CompositeExplicitAutograd: remainder_
+ tags: pointwise
+
+- func: remainder.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: remainder_out
+ MPS: remainder_out_mps
+ tags: pointwise
+
+- func: remainder.Tensor(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: remainder.Tensor_out
+ variants: method, function
+ tags: [core, pointwise]
+
+- func: remainder_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: remainder.Tensor_out
+ variants: method
+ tags: pointwise
+
+- func: remainder.Scalar_Tensor(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: function
+ dispatch:
+ CPU, CUDA, MPS: remainder
+ autogen: remainder.Scalar_Tensor_out
+ tags: pointwise
+
+- func: min(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA: min
+ MPS: min_mps
+ QuantizedCPU: min_quantized_cpu
+
+- func: min.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: min_unary_out
+ QuantizedCPU: min_quantized_unary_out
+
+- func: fmin(Tensor self, Tensor other) -> Tensor
+ structured_delegate: fmin.out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: fmin.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA, MPS: fmin_out
+ tags: pointwise
+
+- func: max(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CPU, CUDA: max
+ MPS: max_mps
+ QuantizedCPU: max_quantized_cpu
+
+- func: fmax(Tensor self, Tensor other) -> Tensor
+ structured_delegate: fmax.out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: fmax.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA, MPS: fmax_out
+ tags: pointwise
+
+- func: maximum(Tensor self, Tensor other) -> Tensor
+ structured_delegate: maximum.out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: [core, pointwise]
+
+- func: maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: maximum_out
+ MPS: maximum_out_mps
+ tags: pointwise
+
+# binary max, alias of maximum
+# NOTE: max is not an alias for maximum, since there is also unary max
+- func: max.other(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: max.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: pointwise
+
+- func: max.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: max_unary_out
+ QuantizedCPU: max_quantized_unary_out
+
+- func: minimum(Tensor self, Tensor other) -> Tensor
+ structured_delegate: minimum.out
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: [core, pointwise]
+
+- func: minimum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CPU, CUDA: minimum_out
+ MPS: minimum_out_mps
+ tags: pointwise
+
+# binary min, alias for minimum
+# NOTE: min is not an alias for minimum, since there is also unary min
+- func: min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: pointwise
+
+- func: min.other(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ tags: pointwise
+
+- func: quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+ variants: method, function
+
+- func: quantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+ variants: method, function
+
+- func: quantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: nanquantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+ variants: method, function
+
+- func: nanquantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: nanquantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor
+ variants: method, function
+
+- func: nanquantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!)
+
+- func: sort.values(Tensor self, int dim=-1, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ device_check: NoCheck # TensorIterator
+ dispatch:
+ CompositeExplicitAutograd: sort_out
+
+- func: sort.values_stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ structured: True
+ dispatch:
+ CPU, CUDA: sort_stable_out
+ MPS: sort_stable_out_mps
+
+- func: sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: sort
+ tags: core
+
+- func: sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices)
+ structured_delegate: sort.values_stable
+ variants: method, function
+ dispatch:
+ QuantizedCPU: sort_quantized_cpu_stable
+
+- func: sort.dimname_values(Tensor self, Dimname dim, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: sort.dimname_values_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+
+- func: sort.dimname(Tensor self, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices)
+ variants: method, function
+
+- func: sort.dimname_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices)
+ variants: method, function
+
+- func: msort.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: msort(Tensor self) -> Tensor
+ variants: method, function
+
+- func: argsort(Tensor self, int dim=-1, bool descending=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+
+- func: argsort.stable(Tensor self, *, bool stable, int dim=-1, bool descending=False) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+
+- func: argsort.stable_out(Tensor self, *, bool stable, int dim=-1, bool descending=False, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: function
+
+- func: argsort.dimname(Tensor self, Dimname dim, bool descending=False) -> Tensor
+ variants: method, function
+
+- func: topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
+ structured: True
+ dispatch:
+ CPU: topk_out_cpu
+ CUDA: topk_out_cuda
+ MPS: topk_out_mps
+
+- func: topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices)
+ variants: method, function
+ structured_delegate: topk.values
+ dispatch:
+ QuantizedCPU: topk_quantized_cpu
+ tags: core
+
+- func: all(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: all.all_out
+ variants: method, function
+
+- func: all.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ structured: True
+ dispatch:
+ CPU, CUDA: all_all_out
+ MPS: all_all_out_mps
+
+- func: any(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: any.all_out
+ variants: method, function
+ dispatch:
+ SparseCPU, SparseCUDA: any_sparse
+ tags: core
+
+- func: any.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ structured: True
+ dispatch:
+ CPU, CUDA: any_all_out
+ MPS: any_all_out_mps
+
+- func: renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: renorm_out
+ MPS: renorm_out_mps
+
+- func: renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor
+ device_check: NoCheck # TensorIterator
+ variants: method, function
+ structured_delegate: renorm.out
+
+- func: renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ variants: method
+ structured_delegate: renorm.out
+
+- func: unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a)
+ variants: method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CPU, CUDA, Meta, MPS: unfold
+ QuantizedCPU, QuantizedCUDA: unfold
+
+- func: unfold_backward(Tensor grad_in, SymInt[] input_sizes, int dim, int size, int step) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA, MPS: unfold_backward
+ autogen: unfold_backward.out
+
+- func: equal(Tensor self, Tensor other) -> bool
+ tags: [data_dependent_output, pointwise]
+ variants: method, function
+ dispatch:
+ CPU: cpu_equal
+ CUDA: cuda_equal
+ MPS: mps_equal
+ QuantizedCPU: equal_quantized_cpu
+
+- func: pow.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: pow_Tensor_Tensor_out
+ MPS: pow_tensor_tensor_out_mps
+ tags: pointwise
+
+- func: pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: pow.Tensor_Tensor_out
+ variants: method, function
+ tags: [core, pointwise]
+
+- func: pow.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ dispatch:
+ CPU, CUDA: pow_Scalar_out
+ MPS: pow_Scalar_out_mps
+ tags: pointwise
+
+- func: pow.Scalar(Scalar self, Tensor exponent) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: pow.Scalar_out
+ tags: [core, pointwise]
+
+- func: pow.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: pow_Tensor_Scalar_out
+ SparseCPU, SparseCUDA: pow_out_sparse_scalar
+ MPS: pow_tensor_scalar_out_mps
+ tags: pointwise
+
+- func: pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: pow.Tensor_Scalar_out
+ variants: function, method
+ dispatch:
+ SparseCPU, SparseCUDA: pow_sparse_scalar
+ tags: [core, pointwise]
+
+- func: pow_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: pow.Tensor_Scalar_out
+ variants: method
+ tags: pointwise
+
+- func: pow_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured_delegate: pow.Tensor_Tensor_out
+ variants: method
+ tags: pointwise
+
+- func: float_power.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+ tags: pointwise
+
+- func: float_power.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor
+ variants: function, method
+ tags: pointwise
+
+- func: float_power.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!)
+ tags: pointwise
+
+- func: float_power.Scalar(Scalar self, Tensor exponent) -> Tensor
+ tags: pointwise
+
+- func: float_power.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!)
+ tags: pointwise
+
+- func: float_power.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor
+ variants: function, method
+ tags: pointwise
+
+- func: float_power_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!)
+ variants: method
+ tags: pointwise
+
+- func: float_power_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!)
+ variants: method
+ tags: pointwise
+
+- func: normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ variants: method
+ dispatch:
+ CPU, CUDA: normal_
+ MPS: normal_mps_
+ Meta: normal_meta_
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: normal_sparse_csr_
+ NestedTensorCPU, NestedTensorCUDA: normal_nested_
+ autogen: normal.out
+
+# Only used by the functionalization pass.
+# Normally, the codegen would be able to generate a normal() NativeFunction,
+# but we can't due to overload ambiguity with normal.Tensor_float.
+- func: normal_functional(Tensor self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor
+ device_check: NoCheck # TensorIterator
+ tags: nondeterministic_seeded
+ dispatch:
+ CompositeExplicitAutograd: normal_functional
+
+- func: normal.Tensor_float_out(Tensor mean, float std=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU, CUDA: normal_out
+ MPS: normal_mps_out
+ Meta: normal_out_meta
+
+- func: normal.Tensor_float(Tensor mean, float std=1, *, Generator? generator=None) -> Tensor
+ dispatch:
+ CPU, CUDA: normal
+ MPS: normal_mps
+ Meta: normal_meta
+ tags: nondeterministic_seeded
+
+- func: normal.float_Tensor_out(float mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: normal_out
+ Meta: normal_out_meta
+ MPS: normal_mps_out
+ tags: nondeterministic_seeded
+
+- func: normal.float_Tensor(float mean, Tensor std, *, Generator? generator=None) -> Tensor
+ dispatch:
+ CPU, CUDA: normal
+ MPS: normal_mps
+ Meta: normal_meta
+ tags: nondeterministic_seeded
+
+- func: normal.Tensor_Tensor_out(Tensor mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: normal_out
+ Meta: normal_out_meta
+ MPS: normal_mps_out
+ tags: nondeterministic_seeded
+
+- func: normal.Tensor_Tensor(Tensor mean, Tensor std, *, Generator? generator=None) -> Tensor
+ dispatch:
+ CPU, CUDA: normal
+ MPS: normal_mps
+ Meta: normal_meta
+ tags: nondeterministic_seeded
+
+- func: normal.float_float(float mean, float std, SymInt[] size, *, Generator? generator=None, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: normal
+ tags: nondeterministic_seeded
+
+- func: normal.float_float_out(float mean, float std, SymInt[] size, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: normal_out
+ tags: nondeterministic_seeded
+
+- func: alias(Tensor(a) self) -> Tensor(a)
+ variants: method, function
+ dispatch:
+ CompositeExplicitAutograd: alias
+ NestedTensorCPU, NestedTensorCUDA: alias_nested
+ tags: core
+
+- func: _amp_foreach_non_finite_check_and_unscale_(Tensor(a!)[] self, Tensor(b!) found_inf, Tensor inv_scale) -> ()
+ variants: function
+ dispatch:
+ CUDA: _amp_foreach_non_finite_check_and_unscale_cuda_
+ CPU: _amp_foreach_non_finite_check_and_unscale_cpu_
+ autogen: _amp_foreach_non_finite_check_and_unscale, _amp_foreach_non_finite_check_and_unscale.out
+
+- func: _amp_update_scale_(Tensor(a!) self, Tensor(b!) growth_tracker, Tensor found_inf, float scale_growth_factor, float scale_backoff_factor, int growth_interval) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CUDA: _amp_update_scale_cuda_
+ CPU: _amp_update_scale_cpu_
+ autogen: _amp_update_scale, _amp_update_scale.out
+
+ #- func: _cat(Tensor[] tensors, int dim=0) -> Tensor
+ #dispatch:
+ #CPU: _cat_cpu
+ #CUDA: cat_cuda
+ #MPS: cat_mps
+ #QuantizedCPU: cat_quantized_cpu
+
+ #- func: _cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)
+ #dispatch:
+ #CPU: _cat_out_cpu
+ #CUDA: cat_out_cuda
+ #QuantizedCPU: cat_out_quantized_cpu
+
+- func: _foreach_add.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_scalar_kernel_slow
+ CUDA: foreach_tensor_add_scalar_kernel_cuda
+
+- func: _foreach_add_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_scalar_kernel_slow_
+ CUDA: foreach_tensor_add_scalar_kernel_cuda_
+ autogen: _foreach_add.Scalar_out
+
+- func: _foreach_add.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_list_kernel_slow
+ CUDA: foreach_tensor_add_list_kernel_cuda
+
+- func: _foreach_add_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_list_kernel_slow_
+ CUDA: foreach_tensor_add_list_kernel_cuda_
+ autogen: _foreach_add.List_out
+
+- func: _foreach_add.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_scalarlist_kernel_slow
+ CUDA: foreach_tensor_add_scalarlist_kernel_cuda
+
+- func: _foreach_add_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_add_scalarlist_kernel_cuda_
+ autogen: _foreach_add.ScalarList_out
+
+- func: _foreach_add.Tensor(Tensor[] self, Tensor other, *, Scalar alpha=1) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_tensor_kernel_slow
+ CUDA: foreach_tensor_add_tensor_kernel_cuda
+
+- func: _foreach_add_.Tensor(Tensor(a!)[] self, Tensor other, *, Scalar alpha=1) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_add_tensor_kernel_slow_
+ CUDA: foreach_tensor_add_tensor_kernel_cuda_
+ autogen: _foreach_add.Tensor_out
+
+- func: _foreach_sub.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sub_scalar_kernel_slow
+ CUDA: foreach_tensor_sub_scalar_kernel_cuda
+
+- func: _foreach_sub_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sub_scalar_kernel_slow_
+ CUDA: foreach_tensor_sub_scalar_kernel_cuda_
+ autogen: _foreach_sub.Scalar_out
+
+- func: _foreach_sub.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sub_list_kernel_slow
+ CUDA: foreach_tensor_sub_list_kernel_cuda
+
+- func: _foreach_sub_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sub_list_kernel_slow_
+ CUDA: foreach_tensor_sub_list_kernel_cuda_
+ autogen: _foreach_sub.List_out
+
+- func: _foreach_sub.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sub_scalarlist_kernel_slow
+ CUDA: foreach_tensor_sub_scalarlist_kernel_cuda
+
+- func: _foreach_sub_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sub_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_sub_scalarlist_kernel_cuda_
+ autogen: _foreach_sub.ScalarList_out
+
+- func: _foreach_mul.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_scalar_kernel_slow
+ CUDA: foreach_tensor_mul_scalar_kernel_cuda
+
+- func: _foreach_mul_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_scalar_kernel_slow_
+ CUDA: foreach_tensor_mul_scalar_kernel_cuda_
+ autogen: _foreach_mul.Scalar_out
+
+- func: _foreach_mul.List(Tensor[] self, Tensor[] other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_list_kernel_slow
+ CUDA: foreach_tensor_mul_list_kernel_cuda
+
+- func: _foreach_mul_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_list_kernel_slow_
+ CUDA: foreach_tensor_mul_list_kernel_cuda_
+ autogen: _foreach_mul.List_out
+
+- func: _foreach_mul.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_scalarlist_kernel_slow
+ CUDA: foreach_tensor_mul_scalarlist_kernel_cuda
+
+- func: _foreach_mul_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_mul_scalarlist_kernel_cuda_
+ autogen: _foreach_mul.ScalarList_out
+
+- func: _foreach_mul.Tensor(Tensor[] self, Tensor other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_tensor_kernel_slow
+ CUDA: foreach_tensor_mul_tensor_kernel_cuda
+
+- func: _foreach_mul_.Tensor(Tensor(a!)[] self, Tensor other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_mul_tensor_kernel_slow_
+ CUDA: foreach_tensor_mul_tensor_kernel_cuda_
+ autogen: _foreach_mul.Tensor_out
+
+- func: _foreach_div.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_scalar_kernel_slow
+ CUDA: foreach_tensor_div_scalar_kernel_cuda
+
+- func: _foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_scalar_kernel_slow_
+ CUDA: foreach_tensor_div_scalar_kernel_cuda_
+ autogen: _foreach_div.Scalar_out
+
+- func: _foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_list_kernel_slow
+ CUDA: foreach_tensor_div_list_kernel_cuda
+
+- func: _foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_list_kernel_slow_
+ CUDA: foreach_tensor_div_list_kernel_cuda_
+ autogen: _foreach_div.List_out
+
+- func: _foreach_div.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_scalarlist_kernel_slow
+ CUDA: foreach_tensor_div_scalarlist_kernel_cuda
+
+- func: _foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_div_scalarlist_kernel_cuda_
+ autogen: _foreach_div.ScalarList_out
+
+- func: _foreach_div.Tensor(Tensor[] self, Tensor other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_tensor_kernel_slow
+ CUDA: foreach_tensor_div_tensor_kernel_cuda
+
+- func: _foreach_div_.Tensor(Tensor(a!)[] self, Tensor other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_div_tensor_kernel_slow_
+ CUDA: foreach_tensor_div_tensor_kernel_cuda_
+ autogen: _foreach_div.Tensor_out
+
+- func: _foreach_clamp_max.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow
+ CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda
+
+- func: _foreach_clamp_max_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow_
+ CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda_
+ autogen: _foreach_clamp_max.Scalar_out
+
+- func: _foreach_clamp_max.List(Tensor[] self, Tensor[] other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow
+ CUDA: foreach_tensor_clamp_max_list_kernel_cuda
+
+- func: _foreach_clamp_max_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow_
+ CUDA: foreach_tensor_clamp_max_list_kernel_cuda_
+ autogen: _foreach_clamp_max.List_out
+
+- func: _foreach_clamp_max.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow
+ CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda
+
+- func: _foreach_clamp_max_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda_
+ autogen: _foreach_clamp_max.ScalarList_out
+
+- func: _foreach_clamp_min.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow
+ CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda
+
+- func: _foreach_clamp_min_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow_
+ CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda_
+ autogen: _foreach_clamp_min.Scalar_out
+
+- func: _foreach_clamp_min.List(Tensor[] self, Tensor[] other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow
+ CUDA: foreach_tensor_clamp_min_list_kernel_cuda
+
+- func: _foreach_clamp_min_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow_
+ CUDA: foreach_tensor_clamp_min_list_kernel_cuda_
+ autogen: _foreach_clamp_min.List_out
+
+- func: _foreach_clamp_min.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow
+ CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda
+
+- func: _foreach_clamp_min_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda_
+ autogen: _foreach_clamp_min.ScalarList_out
+
+# foreach_minimum/maximum dispatches to clamp_max/min
+- func: _foreach_maximum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow
+ CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda
+
+- func: _foreach_maximum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow_
+ CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda_
+ autogen: _foreach_maximum.Scalar_out
+
+# foreach_minimum/maximum dispatches to clamp_max/min
+- func: _foreach_maximum.List(Tensor[] self, Tensor[] other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow
+ CUDA: foreach_tensor_clamp_min_list_kernel_cuda
+
+- func: _foreach_maximum_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow_
+ CUDA: foreach_tensor_clamp_min_list_kernel_cuda_
+ autogen: _foreach_maximum.List_out
+
+# foreach_minimum/maximum dispatches to clamp_max/min
+- func: _foreach_maximum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow
+ CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda
+
+- func: _foreach_maximum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda_
+ autogen: _foreach_maximum.ScalarList_out
+
+- func: _foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow
+ CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda
+
+- func: _foreach_minimum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow_
+ CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda_
+ autogen: _foreach_minimum.Scalar_out
+
+- func: _foreach_minimum.List(Tensor[] self, Tensor[] other) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow
+ CUDA: foreach_tensor_clamp_max_list_kernel_cuda
+
+- func: _foreach_minimum_.List(Tensor(a!)[] self, Tensor[] other) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow_
+ CUDA: foreach_tensor_clamp_max_list_kernel_cuda_
+ autogen: _foreach_minimum.List_out
+
+- func: _foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow
+ CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda
+
+- func: _foreach_minimum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda_
+ autogen: _foreach_minimum.ScalarList_out
+
+- func: _foreach_addcdiv.Scalar(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcdiv_scalar_slow
+ CUDA: foreach_tensor_addcdiv_scalar_cuda
+
+- func: _foreach_addcdiv.ScalarList(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcdiv_scalarlist_slow
+ CUDA: foreach_tensor_addcdiv_scalarlist_cuda
+
+- func: _foreach_addcdiv.Tensor(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcdiv_tensor_slow
+ CUDA: foreach_tensor_addcdiv_tensor_cuda
+
+- func: _foreach_addcdiv_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcdiv_scalar_slow_
+ CUDA: foreach_tensor_addcdiv_scalar_cuda_
+ autogen: _foreach_addcdiv.Scalar_out
+
+- func: _foreach_addcdiv_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcdiv_scalarlist_slow_
+ CUDA: foreach_tensor_addcdiv_scalarlist_cuda_
+ autogen: _foreach_addcdiv.ScalarList_out
+
+- func: _foreach_addcdiv_.Tensor(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcdiv_tensor_slow_
+ CUDA: foreach_tensor_addcdiv_tensor_cuda_
+ autogen: _foreach_addcdiv.Tensor_out
+
+- func: _foreach_addcmul.Scalar(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcmul_scalar_slow
+ CUDA: foreach_tensor_addcmul_scalar_cuda
+
+- func: _foreach_addcmul.ScalarList(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcmul_scalarlist_slow
+ CUDA: foreach_tensor_addcmul_scalarlist_cuda
+
+- func: _foreach_addcmul.Tensor(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcmul_tensor_slow
+ CUDA: foreach_tensor_addcmul_tensor_cuda
+
+- func: _foreach_addcmul_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcmul_scalar_slow_
+ CUDA: foreach_tensor_addcmul_scalar_cuda_
+ autogen: _foreach_addcmul.Scalar_out
+
+- func: _foreach_addcmul_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcmul_scalarlist_slow_
+ CUDA: foreach_tensor_addcmul_scalarlist_cuda_
+ autogen: _foreach_addcmul.ScalarList_out
+
+- func: _foreach_addcmul_.Tensor(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_addcmul_tensor_slow_
+ CUDA: foreach_tensor_addcmul_tensor_cuda_
+ autogen: _foreach_addcmul.Tensor_out
+
+- func: _foreach_abs(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_abs_slow
+ CUDA: foreach_tensor_abs_cuda
+
+- func: _foreach_abs_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_abs_slow_
+ CUDA: foreach_tensor_abs_cuda_
+ autogen: _foreach_abs.out
+
+- func: _foreach_acos(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_acos_slow
+ CUDA: foreach_tensor_acos_cuda
+
+- func: _foreach_acos_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_acos_slow_
+ CUDA: foreach_tensor_acos_cuda_
+ autogen: _foreach_acos.out
+
+- func: _foreach_asin(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_asin_slow
+ CUDA: foreach_tensor_asin_cuda
+
+- func: _foreach_asin_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_asin_slow_
+ CUDA: foreach_tensor_asin_cuda_
+ autogen: _foreach_asin.out
+
+- func: _foreach_atan(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_atan_slow
+ CUDA: foreach_tensor_atan_cuda
+
+- func: _foreach_atan_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_atan_slow_
+ CUDA: foreach_tensor_atan_cuda_
+ autogen: _foreach_atan.out
+
+- func: _foreach_ceil(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_ceil_slow
+ CUDA: foreach_tensor_ceil_cuda
+
+- func: _foreach_ceil_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_ceil_slow_
+ CUDA: foreach_tensor_ceil_cuda_
+ autogen: _foreach_ceil.out
+
+- func: _foreach_cos(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_cos_slow
+ CUDA: foreach_tensor_cos_cuda
+
+- func: _foreach_cos_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_cos_slow_
+ CUDA: foreach_tensor_cos_cuda_
+ autogen: _foreach_cos.out
+
+- func: _foreach_cosh(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_cosh_slow
+ CUDA: foreach_tensor_cosh_cuda
+
+- func: _foreach_cosh_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_cosh_slow_
+ CUDA: foreach_tensor_cosh_cuda_
+ autogen: _foreach_cosh.out
+
+- func: _foreach_erf(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_erf_slow
+ CUDA: foreach_tensor_erf_cuda
+
+- func: _foreach_erf_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_erf_slow_
+ CUDA: foreach_tensor_erf_cuda_
+ autogen: _foreach_erf.out
+
+- func: _foreach_erfc(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_erfc_slow
+ CUDA: foreach_tensor_erfc_cuda
+
+- func: _foreach_erfc_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_erfc_slow_
+ CUDA: foreach_tensor_erfc_cuda_
+ autogen: _foreach_erfc.out
+
+- func: _foreach_exp(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_exp_slow
+ CUDA: foreach_tensor_exp_cuda
+
+- func: _foreach_exp_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_exp_slow_
+ CUDA: foreach_tensor_exp_cuda_
+ autogen: _foreach_exp.out
+
+- func: _foreach_expm1(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_expm1_slow
+ CUDA: foreach_tensor_expm1_cuda
+
+- func: _foreach_expm1_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_expm1_slow_
+ CUDA: foreach_tensor_expm1_cuda_
+ autogen: _foreach_expm1.out
+
+- func: _foreach_floor(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_floor_slow
+ CUDA: foreach_tensor_floor_cuda
+
+- func: _foreach_floor_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_floor_slow_
+ CUDA: foreach_tensor_floor_cuda_
+ autogen: _foreach_floor.out
+
+- func: _foreach_frac(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_frac_slow
+ CUDA: foreach_tensor_frac_cuda
+
+- func: _foreach_frac_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_frac_slow_
+ CUDA: foreach_tensor_frac_cuda_
+ autogen: _foreach_frac.out
+
+- func: _foreach_lerp.List(Tensor[] self, Tensor[] tensors1, Tensor[] weights) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_ternary_lerp_slow
+ CUDA: foreach_tensor_lerp_ternary_cuda
+ autogen: _foreach_lerp.List_out
+
+- func: _foreach_lerp_.List(Tensor(a!)[] self, Tensor[] tensors1, Tensor[] weights) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_ternary_lerp_slow_
+ CUDA: foreach_tensor_lerp_ternary_cuda_
+ autogen: _foreach_lerp.List_out
+
+- func: _foreach_lerp.Scalar(Tensor[] self, Tensor[] tensors1, Scalar weight) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_lerp_list_kernel_slow
+ CUDA: foreach_tensor_lerp_list_cuda
+ autogen: _foreach_lerp.Scalar_out
+
+- func: _foreach_lerp_.Scalar(Tensor(a!)[] self, Tensor[] tensors1, Scalar weight) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_lerp_list_kernel_slow_
+ CUDA: foreach_tensor_lerp_list_cuda_
+ autogen: _foreach_lerp.Scalar_out
+
+- func: _foreach_lerp.ScalarList(Tensor[] self, Tensor[] tensors1, Scalar[] weight) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_lerp_scalarlist_kernel_slow
+ CUDA: foreach_tensor_lerp_scalarlist_cuda
+ autogen: _foreach_lerp.ScalarList_out
+
+- func: _foreach_lerp_.ScalarList(Tensor(a!)[] self, Tensor[] tensors1, Scalar[] weight) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_lerp_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_lerp_scalarlist_cuda_
+ autogen: _foreach_lerp.ScalarList_out
+
+- func: _foreach_lgamma(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_lgamma_slow
+ CUDA: foreach_tensor_lgamma_cuda
+
+- func: _foreach_lgamma_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_lgamma_slow_
+ CUDA: foreach_tensor_lgamma_cuda_
+ autogen: _foreach_lgamma.out
+
+- func: _foreach_log(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log_slow
+ CUDA: foreach_tensor_log_cuda
+
+- func: _foreach_log_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log_slow_
+ CUDA: foreach_tensor_log_cuda_
+ autogen: _foreach_log.out
+
+- func: _foreach_log10(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log10_slow
+ CUDA: foreach_tensor_log10_cuda
+
+- func: _foreach_log10_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log10_slow_
+ CUDA: foreach_tensor_log10_cuda_
+ autogen: _foreach_log10.out
+
+- func: _foreach_log1p(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log1p_slow
+ CUDA: foreach_tensor_log1p_cuda
+
+- func: _foreach_log1p_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log1p_slow_
+ CUDA: foreach_tensor_log1p_cuda_
+ autogen: _foreach_log1p.out
+
+- func: _foreach_log2(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log2_slow
+ CUDA: foreach_tensor_log2_cuda
+
+- func: _foreach_log2_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_log2_slow_
+ CUDA: foreach_tensor_log2_cuda_
+ autogen: _foreach_log2.out
+
+- func: _foreach_max(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_max_slow
+ CUDA: foreach_tensor_max_cuda
+ autogen: _foreach_max.out
+
+- func: _foreach_neg(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_neg_slow
+ CUDA: foreach_tensor_neg_cuda
+
+- func: _foreach_neg_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_neg_slow_
+ CUDA: foreach_tensor_neg_cuda_
+ autogen: _foreach_neg.out
+
+- func: _foreach_norm.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_norm_slow
+ CUDA: foreach_tensor_norm_cuda
+ autogen: _foreach_norm.Scalar_out
+
+- func: _foreach_pow.List(Tensor[] self, Tensor[] exponent) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_pow_list_kernel_slow
+ CUDA: foreach_tensor_pow_list_kernel_cuda
+
+- func: _foreach_pow.Scalar(Tensor[] self, Scalar exponent) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_pow_scalar_kernel_slow
+ CUDA: foreach_tensor_pow_scalar_kernel_cuda
+
+- func: _foreach_pow.ScalarList(Tensor[] self, Scalar[] exponent) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_pow_scalarlist_kernel_slow
+ CUDA: foreach_tensor_pow_scalarlist_kernel_cuda
+
+- func: _foreach_pow.ScalarAndTensor(Scalar self, Tensor[] exponent) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_scalar_pow_list_kernel_slow
+ CUDA: foreach_scalar_pow_list_kernel_cuda
+
+- func: _foreach_pow_.List(Tensor(a!)[] self, Tensor[] exponent) -> ()
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_pow_list_kernel_slow_
+ CUDA: foreach_tensor_pow_list_kernel_cuda_
+ autogen: _foreach_pow.List_out
+
+- func: _foreach_pow_.Scalar(Tensor(a!)[] self, Scalar exponent) -> ()
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_pow_scalar_kernel_slow_
+ CUDA: foreach_tensor_pow_scalar_kernel_cuda_
+ autogen: _foreach_pow.Scalar_out
+
+- func: _foreach_pow_.ScalarList(Tensor(a!)[] self, Scalar[] exponent) -> ()
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_pow_scalarlist_kernel_slow_
+ CUDA: foreach_tensor_pow_scalarlist_kernel_cuda_
+ autogen: _foreach_pow.ScalarList_out
+
+- func: _foreach_reciprocal(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_reciprocal_slow
+ CUDA: foreach_tensor_reciprocal_cuda
+
+- func: _foreach_reciprocal_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_reciprocal_slow_
+ CUDA: foreach_tensor_reciprocal_cuda_
+ autogen: _foreach_reciprocal.out
+
+- func: _foreach_round(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_round_slow
+ CUDA: foreach_tensor_round_cuda
+
+- func: _foreach_round_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_round_slow_
+ CUDA: foreach_tensor_round_cuda_
+ autogen: _foreach_round.out
+
+- func: _foreach_rsqrt(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_rsqrt_slow
+ CUDA: foreach_tensor_rsqrt_cuda
+
+- func: _foreach_rsqrt_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_rsqrt_slow_
+ CUDA: foreach_tensor_rsqrt_cuda_
+ autogen: _foreach_rsqrt.out
+
+- func: _foreach_sigmoid(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sigmoid_slow
+ CUDA: foreach_tensor_sigmoid_cuda
+
+- func: _foreach_sigmoid_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sigmoid_slow_
+ CUDA: foreach_tensor_sigmoid_cuda_
+ autogen: _foreach_sigmoid.out
+
+- func: _foreach_sign(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sign_slow
+ CUDA: foreach_tensor_sign_cuda
+
+- func: _foreach_sign_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sign_slow_
+ CUDA: foreach_tensor_sign_cuda_
+ autogen: _foreach_sign.out
+
+- func: _foreach_sin(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sin_slow
+ CUDA: foreach_tensor_sin_cuda
+
+- func: _foreach_sin_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sin_slow_
+ CUDA: foreach_tensor_sin_cuda_
+ autogen: _foreach_sin.out
+
+- func: _foreach_sinh(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sinh_slow
+ CUDA: foreach_tensor_sinh_cuda
+
+- func: _foreach_sinh_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sinh_slow_
+ CUDA: foreach_tensor_sinh_cuda_
+ autogen: _foreach_sinh.out
+
+- func: _foreach_sqrt(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sqrt_slow
+ CUDA: foreach_tensor_sqrt_cuda
+
+- func: _foreach_sqrt_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_sqrt_slow_
+ CUDA: foreach_tensor_sqrt_cuda_
+ autogen: _foreach_sqrt.out
+
+- func: _foreach_tan(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_tan_slow
+ CUDA: foreach_tensor_tan_cuda
+
+- func: _foreach_tan_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_tan_slow_
+ CUDA: foreach_tensor_tan_cuda_
+ autogen: _foreach_tan.out
+
+- func: _foreach_tanh(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_tanh_slow
+ CUDA: foreach_tensor_tanh_cuda
+
+- func: _foreach_tanh_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_tanh_slow_
+ CUDA: foreach_tensor_tanh_cuda_
+ autogen: _foreach_tanh.out
+
+- func: _foreach_trunc(Tensor[] self) -> Tensor[]
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_trunc_slow
+ CUDA: foreach_tensor_trunc_cuda
+
+- func: _foreach_trunc_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_trunc_slow_
+ CUDA: foreach_tensor_trunc_cuda_
+ autogen: _foreach_trunc.out
+
+- func: _foreach_zero_(Tensor(a!)[] self) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_zero_slow_
+ CUDA: foreach_tensor_zero_cuda_
+ autogen: _foreach_zero, _foreach_zero.out
+
+- func: _foreach_copy_(Tensor(a!)[] self, Tensor[] src, bool non_blocking=False) -> ()
+ device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: foreach_tensor_copy_list_kernel_slow_
+ CUDA: foreach_tensor_copy_list_kernel_cuda_
+ autogen: _foreach_copy.out
+
+- func: _foreach_copy(Tensor[] self, Tensor[] src, bool non_blocking=False) -> Tensor[] self_out
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _foreach_copy
+
+- func: bucketize.Tensor(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor
+ dispatch:
+ CPU: bucketize_cpu
+ CUDA: bucketize_cuda
+ MPS: bucketize_mps
+
+- func: bucketize.Tensor_out(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: bucketize_out_cpu
+ CUDA: bucketize_out_cuda
+ MPS: bucketize_out_mps
+
+- func: bucketize.Scalar(Scalar self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor
+ dispatch:
+ CPU: bucketize_cpu
+ CUDA: bucketize_cuda
+ MPS: bucketize_mps
+ autogen: bucketize.Scalar_out
+
+- func: searchsorted.Tensor(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor
+ dispatch:
+ CPU: searchsorted_cpu
+ CUDA: searchsorted_cuda
+ MPS: searchsorted_mps
+
+- func: searchsorted.Tensor_out(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: searchsorted_out_cpu
+ CUDA: searchsorted_out_cuda
+ MPS: searchsorted_out_mps
+
+- func: searchsorted.Scalar(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor
+ dispatch:
+ CPU: searchsorted_cpu
+ CUDA: searchsorted_cuda
+ MPS: searchsorted_mps
+
+- func: searchsorted.Scalar_out(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU: searchsorted_out_cpu
+ CUDA: searchsorted_out_cuda
+ MPS: searchsorted_out_mps
+
+- func: _convert_indices_from_coo_to_csr(Tensor self, int size, *, bool out_int32=False) -> Tensor
+ structured_delegate: _convert_indices_from_coo_to_csr.out
+
+- func: _convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: _convert_indices_from_coo_to_csr_structured_cpu
+ CUDA: _convert_indices_from_coo_to_csr_structured_cuda
+
+- func: _convert_indices_from_csr_to_coo(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False) -> Tensor
+ structured_delegate: _convert_indices_from_csr_to_coo.out
+
+- func: _convert_indices_from_csr_to_coo.out(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ dispatch:
+ CPU: _convert_indices_from_csr_to_coo_structured_cpu
+ CUDA: _convert_indices_from_csr_to_coo_structured_cuda
+
+## NN wrappers
+
+- func: mse_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: mse_loss_out
+ MPS: mse_loss_out_mps
+
+- func: mse_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: mse_loss.out
+ python_module: nn
+
+- func: mse_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU, CUDA: mse_loss_backward_out
+ MPS: mse_loss_backward_out_mps
+
+- func: mse_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: mse_loss_backward
+ MPS: mse_loss_backward_mps
+
+- func: l1_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+ python_module: nn
+
+- func: multi_margin_loss.out(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: multi_margin_loss_cpu_out
+ CUDA: multi_margin_loss_cuda_out
+
+- func: multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: multi_margin_loss_cpu
+ CUDA: multi_margin_loss_cuda
+
+- func: multi_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: multi_margin_loss_cpu_backward_out
+ CUDA: multi_margin_loss_cuda_backward_out
+
+- func: multi_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: multi_margin_loss_cpu_backward
+ CUDA: multi_margin_loss_cuda_backward
+
+- func: multilabel_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+
+- func: multilabel_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+ python_module: nn
+
+- func: multilabel_margin_loss_forward.output(Tensor self, Tensor target, int reduction, *, Tensor(a!) output, Tensor(b!) is_target) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ dispatch:
+ CPU: multilabel_margin_loss_forward_out_cpu
+ CUDA: multilabel_margin_loss_forward_out_cuda
+
+- func: multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target)
+ python_module: nn
+ dispatch:
+ CPU: multilabel_margin_loss_forward_cpu
+ CUDA: multilabel_margin_loss_forward_cuda
+
+- func: multilabel_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: multilabel_margin_loss_backward_cpu_out
+ CUDA: multilabel_margin_loss_backward_cuda_out
+
+- func: multilabel_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: multilabel_margin_loss_backward_cpu
+ CUDA: multilabel_margin_loss_backward_cuda
+
+- func: nll_loss.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+
+- func: nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: nll_loss_nd_symint
+
+- func: nll_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: nll_loss_symint
+
+- func: nll_loss_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: nll_loss_forward_out_cpu
+ CUDA: nll_loss_forward_out_cuda
+ MPS: nll_loss_forward_out_mps
+
+- func: nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)
+ python_module: nn
+ structured_delegate: nll_loss_forward.output
+
+- func: nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: nll_loss_backward_out_cpu
+ CUDA: nll_loss_backward_out_cuda
+ MPS: nll_loss_backward_out_mps
+
+- func: nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
+ python_module: nn
+ structured_delegate: nll_loss_backward.grad_input
+
+- func: nll_loss2d.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+
+- func: nll_loss2d(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: nll_loss2d_symint
+
+- func: nll_loss2d_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ dispatch:
+ CPU: nll_loss2d_forward_out_cpu
+ CUDA: nll_loss2d_forward_out_cuda
+ MPS: nll_loss2d_forward_out_mps
+
+- func: nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight)
+ python_module: nn
+ dispatch:
+ CPU: nll_loss2d_forward_cpu
+ CUDA: nll_loss2d_forward_cuda
+ MPS: nll_loss2d_forward_mps
+
+- func: nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: nll_loss2d_backward_out_cpu
+ CUDA: nll_loss2d_backward_out_cuda
+ MPS: nll_loss2d_backward_out_mps
+
+- func: nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: nll_loss2d_backward_cpu
+ CUDA: nll_loss2d_backward_cuda
+ MPS: nll_loss2d_backward_mps
+
+- func: smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: smooth_l1_loss_out
+ MPS: smooth_l1_loss_out_mps
+
+- func: smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor
+ device_check: NoCheck # TensorIterator
+ structured_delegate: smooth_l1_loss.out
+ python_module: nn
+
+- func: smooth_l1_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: smooth_l1_loss_backward_out
+ CUDA: smooth_l1_loss_backward_out
+ MPS: smooth_l1_loss_backward_out_mps
+
+- func: smooth_l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: smooth_l1_loss_backward
+
+- func: huber_loss.out(Tensor self, Tensor target, int reduction=Mean, float delta=1.0, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU, CUDA: huber_loss_out
+ MPS: huber_loss_out_mps
+
+- func: huber_loss(Tensor self, Tensor target, int reduction=Mean, float delta=1.0) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: huber_loss
+ MPS: huber_loss_mps
+
+- func: huber_loss_backward.out(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU, CUDA: huber_loss_backward_out
+ MPS: huber_loss_backward_out_mps
+
+- func: huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: huber_loss_backward
+
+- func: soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: soft_margin_loss_out
+
+- func: soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: soft_margin_loss
+
+- func: soft_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: soft_margin_loss_backward_out
+
+- func: soft_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: soft_margin_loss_backward
+
+- func: elu.out(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: elu_out
+ MPS: elu_out_mps
+
+- func: elu(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor
+ structured_delegate: elu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ tags: pointwise
+
+- func: elu_backward.grad_input(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: elu_backward_out
+ MPS: elu_backward_out_mps
+
+- func: elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor
+ structured_delegate: elu_backward.grad_input
+ python_module: nn
+
+- func: elu_(Tensor(a!) self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor(a!)
+ structured_delegate: elu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+
+- func: glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: glu_out
+ MPS: glu_out_mps
+
+- func: glu(Tensor self, int dim=-1) -> Tensor
+ structured_delegate: glu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+
+- func: glu_backward.grad_input(Tensor grad_output, Tensor self, int dim, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: glu_backward_cpu_out
+ CUDA: glu_backward_cuda_out
+ MPS: glu_backward_mps_out
+
+- func: glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: glu_backward_cpu
+ CUDA: glu_backward_cuda
+ MPS: glu_backward_mps
+
+- func: glu_jvp(Tensor glu, Tensor x, Tensor dx, int dim) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: glu_jvp
+ autogen: glu_jvp.out
+
+- func: glu_backward_jvp(Tensor grad_x, Tensor grad_glu, Tensor x, Tensor dgrad_glu, Tensor dx, int dim) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: glu_backward_jvp
+ autogen: glu_backward_jvp.out
+
+- func: hardsigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardsigmoid_out
+ MPS: hardsigmoid_out_mps
+ QuantizedCPU: hardsigmoid_out_quantized_cpu
+
+- func: hardsigmoid(Tensor self) -> Tensor
+ structured_delegate: hardsigmoid.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ QuantizedCPU: hardsigmoid_quantized_cpu
+ tags: pointwise
+
+- func: hardsigmoid_(Tensor(a!) self) -> Tensor(a!)
+ structured_delegate: hardsigmoid.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+
+- func: hardsigmoid_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardsigmoid_backward_out
+ MPS: hardsigmoid_backward_out_mps
+
+- func: hardsigmoid_backward(Tensor grad_output, Tensor self) -> Tensor
+ structured_delegate: hardsigmoid_backward.grad_input
+ python_module: nn
+
+- func: hardtanh.out(Tensor self, Scalar min_val=-1, Scalar max_val=1, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA, MPS: hardtanh_out
+ QuantizedCPU: hardtanh_out_quantized_cpu
+
+- func: hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA, MPS: hardtanh
+ QuantizedCPU: hardtanh_quantized_cpu
+ tags: [pointwise, core]
+
+- func: hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardtanh_backward_out
+ MPS: hardtanh_backward_out_mps
+
+- func: hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardtanh_backward
+ MPS: hardtanh_backward_mps
+
+- func: hardtanh_(Tensor(a!) self, Scalar min_val=-1, Scalar max_val=1) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA, MPS: hardtanh_
+ QuantizedCPU: hardtanh_quantized_cpu_
+
+- func: hardswish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardswish_out
+ MPS: hardswish_out_mps
+
+- func: hardswish(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardswish
+ MPS: hardswish_mps
+
+- func: hardswish_(Tensor(a!) self) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardswish_
+ MPS: hardswish_mps_
+
+- func: hardswish_backward(Tensor grad_output, Tensor self) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU, CUDA: hardswish_backward
+ MPS: hardswish_backward_mps
+ autogen: hardswish_backward.out
+
+- func: leaky_relu.out(Tensor self, Scalar negative_slope=0.01, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: leaky_relu_out
+ MPS: leaky_relu_out_mps
+ QuantizedCPU: leaky_relu_out_quantized_cpu
+
+- func: leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor
+ structured_delegate: leaky_relu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ QuantizedCPU: leaky_relu_quantized_cpu
+ tags: core
+
+- func: leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: leaky_relu_backward_out
+ MPS: leaky_relu_backward_out_mps
+
+- func: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor
+ structured_delegate: leaky_relu_backward.grad_input
+ python_module: nn
+
+- func: leaky_relu_(Tensor(a!) self, Scalar negative_slope=0.01) -> Tensor(a!)
+ structured_delegate: leaky_relu.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ QuantizedCPU: leaky_relu_quantized_cpu_
+
+- func: log_sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+
+- func: log_sigmoid(Tensor self) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+
+- func: log_sigmoid_forward.output(Tensor self, *, Tensor(a!) output, Tensor(b!) buffer) -> (Tensor(a!), Tensor(b!))
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU: log_sigmoid_forward_out_cpu
+ CUDA: log_sigmoid_forward_out_cuda
+ MPS: log_sigmoid_forward_out_mps
+
+- func: log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer)
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU: log_sigmoid_forward_cpu
+ CUDA: log_sigmoid_forward_cuda
+ MPS: log_sigmoid_forward_mps
+
+- func: log_sigmoid_backward.grad_input(Tensor grad_output, Tensor self, Tensor buffer, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: log_sigmoid_backward_cpu_out
+ CUDA: log_sigmoid_backward_cuda_out
+ MPS: log_sigmoid_backward_mps_out
+
+- func: log_sigmoid_backward(Tensor grad_output, Tensor self, Tensor buffer) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: log_sigmoid_backward_cpu
+ CUDA: log_sigmoid_backward_cuda
+ MPS: log_sigmoid_backward_mps
+
+- func: rrelu_with_noise.out(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU: rrelu_with_noise_out_cpu
+ CUDA: rrelu_with_noise_out_cuda
+
+- func: rrelu_with_noise(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: rrelu_with_noise_cpu
+ CUDA: rrelu_with_noise_cuda
+ tags: nondeterministic_seeded
+ autogen: rrelu_with_noise_functional
+
+- func: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: rrelu_with_noise_backward
+ autogen: rrelu_with_noise_backward.out
+
+- func: rrelu_with_noise_(Tensor(a!) self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!)
+ python_module: nn
+ tags: nondeterministic_seeded
+ dispatch:
+ CPU: rrelu_with_noise_cpu_
+ CUDA: rrelu_with_noise_cuda_
+
+- func: softplus.out(Tensor self, Scalar beta=1, Scalar threshold=20, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: softplus_out
+ MPS: softplus_out_mps
+
+- func: softplus(Tensor self, Scalar beta=1, Scalar threshold=20) -> Tensor
+ structured_delegate: softplus.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ tags: pointwise
+
+- func: softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: softplus_backward_out
+ MPS: softplus_backward_out_mps
+
+- func: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor
+ structured_delegate: softplus_backward.grad_input
+ python_module: nn
+
+- func: softshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ dispatch:
+ CPU, CUDA: softshrink_out
+ MPS: softshrink_out_mps
+
+- func: softshrink(Tensor self, Scalar lambd=0.5) -> Tensor
+ structured_delegate: softshrink.out
+ device_check: NoCheck # TensorIterator
+ python_module: nn
+ tags: pointwise
+
+- func: softshrink_backward.grad_input(Tensor grad_output, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: nn
+ dispatch:
+ CPU, CUDA: softshrink_backward_out
+ MPS: softshrink_backward_out_mps
+
+- func: softshrink_backward(Tensor grad_output, Tensor self, Scalar lambd) -> Tensor
+ structured_delegate: softshrink_backward.grad_input
+ python_module: nn
+
+- func: adaptive_avg_pool2d.out(Tensor self, SymInt[2] output_size, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: adaptive_avg_pool2d_out_cpu
+ CUDA: adaptive_avg_pool2d_out_cuda
+ MPS: adaptive_avg_pool2d_out_mps
+ MkldnnCPU: mkldnn_adaptive_avg_pool2d_out_stub
+
+- func: adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: adaptive_avg_pool2d_symint
+
+- func: mkldnn_adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_adaptive_avg_pool2d
+
+- func: mkldnn_adaptive_avg_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ MkldnnCPU: mkldnn_adaptive_avg_pool2d_out
+
+- func: mkldnn_adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor
+ dispatch:
+ MkldnnCPU: mkldnn_adaptive_avg_pool2d_backward
+ autogen: mkldnn_adaptive_avg_pool2d_backward.out
+
+- func: _adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor
+ dispatch:
+ CPU: adaptive_avg_pool2d_cpu
+ CUDA: adaptive_avg_pool2d_cuda
+ MPS: adaptive_avg_pool2d_mps
+ QuantizedCPU: adaptive_avg_pool2d_quantized_cpu
+ QuantizedCUDA: adaptive_avg_pool2d_quantized_cuda
+ autogen: _adaptive_avg_pool2d.out
+ tags: core
+
+- func: _adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: adaptive_avg_pool2d_backward_cpu
+ CUDA: adaptive_avg_pool2d_backward_cuda
+ MPS: adaptive_avg_pool2d_backward_mps
+ autogen: _adaptive_avg_pool2d_backward.out
+ tags: core
+
+- func: adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: adaptive_avg_pool3d_out_cpu
+ CUDA: adaptive_avg_pool3d_out_cuda
+ QuantizedCPU: adaptive_avg_pool3d_out_quantized_cpu
+
+- func: adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: adaptive_avg_pool3d_symint
+
+- func: _adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor
+ dispatch:
+ CPU: adaptive_avg_pool3d_cpu
+ CUDA: adaptive_avg_pool3d_cuda
+ QuantizedCPU: adaptive_avg_pool3d_quantized_cpu
+ autogen: _adaptive_avg_pool3d.out
+ tags: core
+
+- func: adaptive_avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: adaptive_avg_pool3d_backward_out_cpu
+ CUDA: adaptive_avg_pool3d_backward_out_cuda
+
+- func: _adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: adaptive_avg_pool3d_backward_cpu
+ CUDA: adaptive_avg_pool3d_backward_cuda
+ autogen: _adaptive_avg_pool3d_backward.out
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: adaptive_max_pool2d_out_cpu
+ CUDA: adaptive_max_pool2d_out_cuda
+ MPS: adaptive_max_pool2d_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool2d(Tensor self, int[2] output_size) -> (Tensor, Tensor)
+ python_module: nn
+ structured_delegate: adaptive_max_pool2d.out
+
+- func: adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: adaptive_max_pool2d_backward_out_cpu
+ CUDA: adaptive_max_pool2d_backward_out_cuda
+ MPS: adaptive_max_pool2d_backward_out_mps
+
+- func: adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
+ python_module: nn
+ structured_delegate: adaptive_max_pool2d_backward.grad_input
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: adaptive_max_pool3d_out_cpu
+ CUDA: adaptive_max_pool3d_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor)
+ python_module: nn
+ structured_delegate: adaptive_max_pool3d.out
+
+- func: adaptive_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: adaptive_max_pool3d_backward_out_cpu
+ CUDA: adaptive_max_pool3d_backward_out_cuda
+
+- func: adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
+ python_module: nn
+ structured_delegate: adaptive_max_pool3d_backward.grad_input
+
+- func: avg_pool2d.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ precomputed:
+ - kernel_size -> int kH, int kW
+ - stride -> int dH, int dW
+ - padding -> int padH, int padW
+ dispatch:
+ CPU: avg_pool2d_out_cpu
+ CUDA: avg_pool2d_out_cuda
+ MPS: avg_pool2d_out_mps
+ MkldnnCPU: mkldnn_avg_pool2d_out
+
+- func: avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor
+ python_module: nn
+ structured_delegate: avg_pool2d.out
+ dispatch:
+ MkldnnCPU: mkldnn_avg_pool2d
+ QuantizedCPU: avg_pool2d_quantized_cpu
+ tags: core
+
+- func: avg_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: avg_pool2d_backward_out_cpu
+ CUDA: avg_pool2d_backward_out_cuda
+ MPS: avg_pool2d_backward_out_mps
+ MkldnnCPU: mkldnn_avg_pool2d_backward_out
+
+- func: avg_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor
+ python_module: nn
+ structured_delegate: avg_pool2d_backward.grad_input
+ dispatch:
+ MkldnnCPU: mkldnn_avg_pool2d_backward
+ tags: core
+
+- func: avg_pool3d.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: avg_pool3d_out_cpu
+ CUDA: avg_pool3d_out_cuda
+ MkldnnCPU: mkldnn_avg_pool3d_out
+
+- func: avg_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor
+ python_module: nn
+ structured_delegate: avg_pool3d.out
+ dispatch:
+ MkldnnCPU: mkldnn_avg_pool3d
+ QuantizedCPU: avg_pool3d_quantized_cpu
+ tags: core
+
+- func: avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: avg_pool3d_backward_out_cpu
+ CUDA: avg_pool3d_backward_out_cuda
+ MkldnnCPU: mkldnn_avg_pool3d_backward_out
+
+- func: avg_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor
+ python_module: nn
+ structured_delegate: avg_pool3d_backward.grad_input
+ dispatch:
+ MkldnnCPU: mkldnn_avg_pool3d_backward
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool2d.output(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: fractional_max_pool2d_out_cpu
+ CUDA: fractional_max_pool2d_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool2d(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples) -> (Tensor, Tensor)
+ python_module: nn
+ structured_delegate: fractional_max_pool2d.output
+
+- func: fractional_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: fractional_max_pool2d_backward_cpu
+ CUDA: fractional_max_pool2d_backward_cuda
+
+- func: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor
+ python_module: nn
+ structured_delegate: fractional_max_pool2d_backward.grad_input
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool3d.output(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ structured: True
+ precomputed:
+ - kernel_size -> int poolSizeT, int poolSizeH, int poolSizeW
+ - output_size -> int outputT, int outputH, int outputW
+ - int numBatch, int numPlanes, int inputT, int inputH, int inputW
+ dispatch:
+ CPU: fractional_max_pool3d_out_cpu
+ CUDA: fractional_max_pool3d_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: fractional_max_pool3d(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples) -> (Tensor, Tensor)
+ python_module: nn
+ structured_delegate: fractional_max_pool3d.output
+
+- func: fractional_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: fractional_max_pool3d_backward_out_cpu
+ CUDA: fractional_max_pool3d_backward_out_cuda
+
+- func: fractional_max_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: fractional_max_pool3d_backward_cpu
+ CUDA: fractional_max_pool3d_backward_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool2d_with_indices.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: max_pool2d_with_indices_out_cpu
+ CUDA: max_pool2d_with_indices_out_cuda
+ MPS: max_pool2d_with_indices_out_mps
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+ python_module: nn
+ structured_delegate: max_pool2d_with_indices.out
+ tags: core
+
+- func: max_pool2d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: max_pool2d_with_indices_backward_out_cpu
+ CUDA: max_pool2d_with_indices_backward_out_cuda
+ MPS: max_pool2d_with_indices_backward_out_mps
+
+- func: max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor
+ python_module: nn
+ structured_delegate: max_pool2d_with_indices_backward.grad_input
+ tags: core
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool3d_with_indices.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!))
+ python_module: nn
+ dispatch:
+ CPU: max_pool3d_with_indices_out_cpu
+ CUDA: max_pool3d_with_indices_out_cuda
+
+# Return: (Tensor output, Tensor indices)
+- func: max_pool3d_with_indices(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor)
+ python_module: nn
+ dispatch:
+ CPU: max_pool3d_with_indices_cpu
+ CUDA: max_pool3d_with_indices_cuda
+ tags: core
+
+- func: max_pool3d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: max_pool3d_with_indices_backward_out_cpu
+ CUDA: max_pool3d_with_indices_backward_out_cuda
+
+- func: max_pool3d_with_indices_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: max_pool3d_with_indices_backward_cpu
+ CUDA: max_pool3d_with_indices_backward_cuda
+
+- func: max_unpool2d.out(Tensor self, Tensor indices, SymInt[2] output_size, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: max_unpooling2d_forward_out_cpu
+ CUDA: max_unpooling2d_forward_out_cuda
+
+- func: max_unpool2d(Tensor self, Tensor indices, SymInt[2] output_size) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: max_unpooling2d_forward_cpu
+ CUDA: max_unpooling2d_forward_cuda
+
+- func: max_unpool3d.out(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: max_unpooling3d_forward_out_cpu
+ CUDA: max_unpooling3d_forward_out_cuda
+
+- func: max_unpool3d(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: max_unpooling3d_forward_cpu
+ CUDA: max_unpooling3d_forward_cuda
+
+- func: reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: reflection_pad1d_out_cpu
+ QuantizedCPU: reflection_pad1d_out_quantized_cpu
+ CUDA: reflection_pad1d_out_cuda
+ MPS: reflection_pad1d_out_mps
+
+- func: reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor
+ python_module: nn
+ structured_delegate: reflection_pad1d.out
+ tags: core
+
+- func: reflection_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: reflection_pad1d_backward_out_cpu
+ CUDA: reflection_pad1d_backward_out_cuda
+ MPS: reflection_pad1d_backward_out_mps
+
+- func: reflection_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor
+ python_module: nn
+ structured_delegate: reflection_pad1d_backward.grad_input
+
+- func: reflection_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU, QuantizedCPU: reflection_pad2d_out_cpu
+ CUDA: reflection_pad2d_out_cuda
+ MPS: reflection_pad2d_out_mps
+
+- func: reflection_pad2d(Tensor self, SymInt[4] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: reflection_pad2d_cpu
+ QuantizedCPU: reflection_pad2d_quantized_cpu
+ CUDA: reflection_pad2d_cuda
+ MPS: reflection_pad2d_mps
+ tags: core
+
+- func: reflection_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: reflection_pad2d_backward_out_cpu
+ CUDA: reflection_pad2d_backward_out_cuda
+ MPS: reflection_pad2d_backward_out_mps
+
+- func: reflection_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: reflection_pad2d_backward_cpu
+ CUDA: reflection_pad2d_backward_cuda
+ MPS: reflection_pad2d_backward_mps
+
+- func: reflection_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: reflection_pad3d_out_cpu
+ CUDA: reflection_pad3d_out_cuda
+ MPS: reflection_pad3d_out_mps
+
+- func: reflection_pad3d(Tensor self, SymInt[6] padding) -> Tensor
+ python_module: nn
+ structured_delegate: reflection_pad3d.out
+ tags: core
+
+- func: reflection_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: reflection_pad3d_backward_out_cpu
+ CUDA: reflection_pad3d_backward_out_cuda
+ MPS: reflection_pad3d_backward_out_mps
+
+- func: reflection_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor
+ python_module: nn
+ structured_delegate: reflection_pad3d_backward.grad_input
+
+- func: replication_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: replication_pad1d_out_cpu
+ CUDA: replication_pad1d_out_cuda
+ MPS: replication_pad1d_out_mps
+
+- func: replication_pad1d(Tensor self, SymInt[2] padding) -> Tensor
+ python_module: nn
+ structured_delegate: replication_pad1d.out
+
+- func: replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: replication_pad1d_backward_out_cpu
+ CUDA: replication_pad1d_backward_out_cuda
+ MPS: replication_pad1d_backward_out_mps
+
+- func: replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor
+ python_module: nn
+ structured_delegate: replication_pad1d_backward.grad_input
+
+- func: replication_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: replication_pad2d_out_cpu
+ CUDA: replication_pad2d_out_cuda
+ MPS: replication_pad2d_out_mps
+
+- func: replication_pad2d(Tensor self, SymInt[4] padding) -> Tensor
+ python_module: nn
+ structured_delegate: replication_pad2d.out
+ tags: core
+
+- func: replication_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: replication_pad2d_backward_out_cpu
+ CUDA: replication_pad2d_backward_out_cuda
+ MPS: replication_pad2d_backward_out_mps
+
+- func: replication_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: replication_pad2d_backward_cpu
+ CUDA: replication_pad2d_backward_cuda
+ MPS: replication_pad2d_backward_mps
+
+- func: replication_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: replication_pad3d_out_cpu
+ CUDA: replication_pad3d_out_cuda
+ MPS: replication_pad3d_out_mps
+
+- func: replication_pad3d(Tensor self, SymInt[6] padding) -> Tensor
+ python_module: nn
+ structured_delegate: replication_pad3d.out
+ tags: core
+
+
+- func: replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: replication_pad3d_backward_out_cpu
+ CUDA: replication_pad3d_backward_out_cuda
+ MPS: replication_pad3d_backward_out_mps
+
+- func: replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: replication_pad3d_backward_cpu
+ CUDA: replication_pad3d_backward_cuda
+ MPS: replication_pad3d_backward_mps
+
+- func: _pad_circular(Tensor self, SymInt[] pad) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: _pad_circular_symint
+
+- func: _pad_enum(Tensor self, SymInt[] pad, int mode, float? value=None) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: _pad_enum_symint
+
+- func: pad(Tensor self, SymInt[] pad, str mode="constant", float? value=None) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeImplicitAutograd: pad_symint
+
+- func: upsample_linear1d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_linear1d.vec_out
+
+- func: upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_bilinear2d.vec_out
+ tags: core
+
+- func: _upsample_bilinear2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: _upsample_bilinear2d_aa.vec_out
+
+- func: upsample_trilinear3d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_trilinear3d.vec_out
+
+- func: upsample_bicubic2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_bicubic2d.vec_out
+
+- func: _upsample_bicubic2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: _upsample_bicubic2d_aa.vec_out
+
+- func: upsample_nearest1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_nearest1d.vec_out
+
+- func: _upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: _upsample_nearest_exact1d.vec_out
+
+- func: upsample_nearest2d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_nearest2d.vec_out
+ tags: core
+
+- func: _upsample_nearest_exact2d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: _upsample_nearest_exact2d.vec_out
+
+- func: upsample_nearest3d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: upsample_nearest3d.vec_out
+
+- func: _upsample_nearest_exact3d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor
+ python_module: nn
+ autogen: _upsample_nearest_exact3d.vec_out
+
+# NOTE: all of the non-"vec" upsample overloads are only kept for backward compatibility.
+- func: upsample_linear1d.out(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_linear1d_out_cpu
+ CUDA: upsample_linear1d_out_cuda
+ MPS: upsample_linear1d_out_mps
+
+- func: upsample_linear1d(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_linear1d.out
+
+- func: upsample_linear1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_linear1d_backward_out_cpu
+ CUDA: upsample_linear1d_backward_out_cuda
+ MPS: upsample_linear1d_backward_out_mps
+
+- func: upsample_linear1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_linear1d_backward.grad_input
+
+- func: upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_bilinear2d_out_cpu
+ CUDA: upsample_bilinear2d_out_cuda
+ MPS: upsample_bilinear2d_out_mps
+
+- func: upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_bilinear2d.out
+ dispatch:
+ QuantizedCPU: upsample_bilinear2d_quantized_cpu
+
+- func: upsample_bilinear2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_bilinear2d_backward_out_cpu
+ CUDA: upsample_bilinear2d_backward_out_cuda
+ MPS: upsample_bilinear2d_backward_out_mps
+
+- func: upsample_bilinear2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_bilinear2d_backward.grad_input
+
+- func: _upsample_bilinear2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_bilinear2d_aa_out_cpu
+ CUDA: _upsample_bilinear2d_aa_out_cuda
+
+- func: _upsample_bilinear2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_bilinear2d_aa.out
+
+- func: _upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_bilinear2d_aa_backward_out_cpu
+ CUDA: _upsample_bilinear2d_aa_backward_out_cuda
+
+- func: _upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_bilinear2d_aa_backward.grad_input
+
+- func: upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_bicubic2d_out_cpu
+ CUDA: upsample_bicubic2d_out_cuda
+ MPS: upsample_bicubic2d_out_mps
+
+- func: upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_bicubic2d.out
+
+- func: upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_bicubic2d_backward_out_cpu
+ CUDA: upsample_bicubic2d_backward_out_cuda
+ MPS: upsample_bicubic2d_backward_out_mps
+
+- func: upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_bicubic2d_backward.grad_input
+
+- func: _upsample_bicubic2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_bicubic2d_aa_out_cpu
+ CUDA: _upsample_bicubic2d_aa_out_cuda
+
+- func: _upsample_bicubic2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_bicubic2d_aa.out
+
+- func: _upsample_bicubic2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_bicubic2d_aa_backward_out_cpu
+ CUDA: _upsample_bicubic2d_aa_backward_out_cuda
+
+- func: _upsample_bicubic2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_bicubic2d_aa_backward.grad_input
+
+- func: upsample_trilinear3d.out(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_trilinear3d_out_cpu
+ CUDA: upsample_trilinear3d_out_cuda
+
+- func: upsample_trilinear3d(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_trilinear3d.out
+
+- func: upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_trilinear3d_backward_out_cpu
+ CUDA: upsample_trilinear3d_backward_out_cuda
+
+- func: upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_trilinear3d_backward.grad_input
+
+- func: upsample_nearest1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_nearest1d_out_cpu
+ CUDA: upsample_nearest1d_out_cuda
+ MPS: upsample_nearest1d_out_mps
+
+- func: _upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_nearest_exact1d_out_cpu
+ CUDA: _upsample_nearest_exact1d_out_cuda
+ MPS: _upsample_nearest_exact1d_out_mps
+
+- func: upsample_nearest1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_nearest1d.out
+
+- func: _upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_nearest_exact1d.out
+
+- func: upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_nearest1d_backward_out_cpu
+ CUDA: upsample_nearest1d_backward_out_cuda
+ MPS: upsample_nearest1d_backward_out_mps
+
+- func: _upsample_nearest_exact1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_nearest_exact1d_backward_out_cpu
+ CUDA: _upsample_nearest_exact1d_backward_out_cuda
+ MPS: _upsample_nearest_exact1d_backward_out_mps
+
+- func: upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_nearest1d_backward.grad_input
+
+- func: _upsample_nearest_exact1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_nearest_exact1d_backward.grad_input
+
+- func: upsample_nearest2d.out(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_nearest2d_out_cpu
+ CUDA: upsample_nearest2d_out_cuda
+ MPS: upsample_nearest2d_out_mps
+
+- func: _upsample_nearest_exact2d.out(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_nearest_exact2d_out_cpu
+ CUDA: _upsample_nearest_exact2d_out_cuda
+ MPS: _upsample_nearest_exact2d_out_mps
+
+- func: upsample_nearest2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_nearest2d.out
+ dispatch:
+ QuantizedCPU: upsample_nearest2d_quantized_cpu
+
+- func: _upsample_nearest_exact2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_nearest_exact2d.out
+ dispatch:
+ QuantizedCPU: _upsample_nearest_exact2d_quantized_cpu
+
+- func: upsample_nearest2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_nearest2d_backward_out_cpu
+ CUDA: upsample_nearest2d_backward_out_cuda
+ MPS: upsample_nearest2d_backward_out_mps
+
+- func: _upsample_nearest_exact2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_nearest_exact2d_backward_out_cpu
+ CUDA: _upsample_nearest_exact2d_backward_out_cuda
+ MPS: _upsample_nearest_exact2d_backward_out_mps
+
+- func: upsample_nearest2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_nearest2d_backward.grad_input
+
+- func: _upsample_nearest_exact2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_nearest_exact2d_backward.grad_input
+
+- func: upsample_nearest3d.out(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_nearest3d_out_cpu
+ CUDA: upsample_nearest3d_out_cuda
+
+- func: _upsample_nearest_exact3d.out(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_nearest_exact3d_out_cpu
+ CUDA: _upsample_nearest_exact3d_out_cuda
+
+- func: upsample_nearest3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_nearest3d.out
+ dispatch:
+ QuantizedCPU: upsample_nearest3d_quantized_cpu
+
+- func: _upsample_nearest_exact3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_nearest_exact3d.out
+ dispatch:
+ QuantizedCPU: _upsample_nearest_exact3d_quantized_cpu
+
+- func: upsample_nearest3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: upsample_nearest3d_backward_out_cpu
+ CUDA: upsample_nearest3d_backward_out_cuda
+
+- func: _upsample_nearest_exact3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: _upsample_nearest_exact3d_backward_out_cpu
+ CUDA: _upsample_nearest_exact3d_backward_out_cuda
+
+- func: upsample_nearest3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: upsample_nearest3d_backward.grad_input
+
+- func: _upsample_nearest_exact3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor
+ python_module: nn
+ structured_delegate: _upsample_nearest_exact3d_backward.grad_input
+
+- func: sigmoid_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: sigmoid_backward_out
+ MPS: sigmoid_backward_out_mps
+ tags: pointwise
+
+- func: sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor
+ python_module: nn
+ structured_delegate: sigmoid_backward.grad_input
+ tags: pointwise
+
+- func: logit_backward.grad_input(Tensor grad_output, Tensor self, float? eps=None, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: logit_backward_out
+ MPS: logit_backward_out_mps
+ tags: pointwise
+
+- func: logit_backward(Tensor grad_output, Tensor self, float? eps=None) -> Tensor
+ python_module: nn
+ structured_delegate: logit_backward.grad_input
+ tags: pointwise
+
+- func: tanh_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: tanh_backward_out
+ MPS: tanh_backward_out_mps
+ tags: pointwise
+
+- func: tanh_backward(Tensor grad_output, Tensor output) -> Tensor
+ python_module: nn
+ structured_delegate: tanh_backward.grad_input
+
+# What's a thnn_conv_ versus a slow_conv_?
+#
+# Historically, we have inefficient implementations of convolutions
+# coming from the THNN/THCUNN library. These convolutions typically
+# operated by computing the Toeplitz matrix and then doing a matrix
+# multiply with the input; this is very memory inefficient! However,
+# occasionally, we really don't have anything better, so it's helpful
+# to have these fallbacks when there is no more optimized implementation
+# in cudnn or mkldnn, etc. Both thnn_ and slow_ convolutions fall
+# into this bucket.
+#
+# The difference between these two designations, is that thnn_ refers
+# to a convolution that is still written in the "legacy" style; that is,
+# C code in the THNN/ or THCUNN/ directory. A slow_ convolution is
+# one that is written in the native style: modern C++. Algorithmically,
+# these are the same thing, but we give them different prefixes to
+# make the operational distinction clear.
+ tags: pointwise
+
+- func: slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ structured: True
+ dispatch:
+ CPU: slow_conv_transpose2d_structured_cpu
+ CUDA: slow_conv_transpose2d_structured_cuda
+
+- func: slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor
+ python_module: nn
+ structured_delegate: slow_conv_transpose2d.out
+
+- func: slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: slow_conv_transpose3d_out_cpu
+ CUDA: slow_conv_transpose3d_out_cuda
+
+- func: slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: slow_conv_transpose3d_cpu
+ CUDA: slow_conv_transpose3d_cuda
+
+- func: thnn_conv2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+
+- func: thnn_conv2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0) -> Tensor
+ python_module: nn
+
+- func: _slow_conv2d_forward.output(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) output) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: slow_conv2d_forward_out_cpu
+ CUDA: slow_conv2d_forward_out_cuda
+
+- func: _slow_conv2d_forward(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: slow_conv2d_forward_cpu
+ CUDA: slow_conv2d_forward_cuda
+
+- func: _slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!))
+ python_module: nn
+ dispatch:
+ CPU: slow_conv2d_backward_out_cpu
+ CUDA: slow_conv2d_backward_out_cuda
+
+- func: _slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias)
+ python_module: nn
+ dispatch:
+ CPU: slow_conv2d_backward_cpu
+ CUDA: slow_conv2d_backward_cuda
+ autogen: _slow_conv2d_backward.output_mask_out
+
+- func: _conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ python_module: nn
+ dispatch:
+ CUDA: conv_depthwise2d_cuda_out
+
+- func: _conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor
+ python_module: nn
+ dispatch:
+ CUDA: conv_depthwise2d_cuda
+
+- func: conv_depthwise3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, SymInt[3] dilation) -> Tensor
+ python_module: nn
+ dispatch:
+ CUDA: conv_depthwise3d_cuda
+ autogen: conv_depthwise3d.out
+
+- func: slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+
+- func: slow_conv3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0) -> Tensor
+ python_module: nn
+
+- func: slow_conv3d_forward.output(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, *, Tensor(a!) output) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: slow_conv3d_forward_out_cpu
+
+- func: slow_conv3d_forward(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: slow_conv3d_forward_cpu
+
+- func: slow_conv_dilated2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: slow_conv_dilated2d_cpu
+ CUDA: slow_conv_dilated2d_cuda
+ autogen: slow_conv_dilated2d.out
+
+- func: slow_conv_dilated3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: slow_conv_dilated3d_cpu
+ CUDA: slow_conv_dilated3d_cuda
+ autogen: slow_conv_dilated3d.out
+
+- func: col2im.out(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: col2im_out_cpu
+ CUDA: col2im_out_cuda
+
+- func: col2im(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: col2im_cpu
+ CUDA: col2im_cuda
+ tags: core
+
+- func: column_stack(Tensor[] tensors) -> Tensor
+
+- func: column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: im2col.out(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: nn
+ dispatch:
+ CPU: im2col_out_cpu
+ CUDA: im2col_out_cuda
+ MPS: im2col_out_mps
+
+- func: im2col(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: im2col_cpu
+ CUDA: im2col_cuda
+ MPS: im2col_mps
+
+- func: isfinite(Tensor self) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ tags: pointwise
+
+- func: isinf(Tensor self) -> Tensor
+ variants: function, method
+ device_check: NoCheck
+ device_guard: False
+ dispatch:
+ CompositeExplicitAutograd: isinf
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_isinf
+ SparseCPU, SparseCUDA: isinf_sparse
+ SparseMeta: isinf_sparse_meta
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isinf_sparse_csr
+ autogen: isinf.out
+ tags: [core, pointwise]
+
+- func: record_stream(Tensor(a!) self, Stream s) -> ()
+ variants: method
+ dispatch:
+ CUDA: record_stream_cuda
+
+- func: isposinf(Tensor self) -> Tensor
+ variants: function, method
+ structured_delegate: isposinf.out
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_isposinf
+ SparseCPU, SparseCUDA: isposinf_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isposinf_sparse_csr
+ tags: pointwise
+
+- func: isposinf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: isposinf_out
+ SparseCPU, SparseCUDA: isposinf_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isposinf_sparse_csr_out
+ tags: pointwise
+
+- func: isneginf(Tensor self) -> Tensor
+ variants: function, method
+ structured_delegate: isneginf.out
+ dispatch:
+ NestedTensorCPU, NestedTensorCUDA: NestedTensor_isneginf
+ SparseCPU, SparseCUDA: isneginf_sparse
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isneginf_sparse_csr
+ tags: pointwise
+
+- func: isneginf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: isneginf_out
+ SparseCPU, SparseCUDA: isneginf_sparse_out
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: isneginf_sparse_csr_out
+ tags: pointwise
+
+# NOTE [_add_batch_dim and _remove_batch_dim]
+# _add_batch_dim and _remove_batch_dim are meant to be used in the implementation
+# of the vmap frontend API (see torch/_vmap_internals.py). They are not
+# user-facing, hence the leading underscore. Please don't use them them anywhere else.
+- func: _add_batch_dim(Tensor self, int batch_dim, int level) -> Tensor
+ variants: function
+
+# See NOTE [_add_batch_dim and _remove_batch_dim]
+- func: _remove_batch_dim(Tensor self, int level, SymInt batch_size, int out_dim) -> Tensor
+ variants: function
+
+## Functions related to the `torch.special` namespace
+# Note [special namespace binding]
+# Functions in the special python module should have their names start with
+# "special_" underscore and be bound to the desired Python name in
+# torch/special/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/special.h.
+# The "special_" names should be hidden from the user and not documented.
+
+- func: special_entr(Tensor self) -> Tensor
+ structured_delegate: special_entr.out
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_entr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: special
+ variants: function
+ dispatch:
+ CPU, CUDA: special_entr_out
+ tags: pointwise
+
+- func: special_ndtri(Tensor self) -> Tensor
+ structured_delegate: special_ndtri.out
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_ndtri.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: special
+ variants: function
+ dispatch:
+ CPU, CUDA: special_ndtri_out
+ tags: pointwise
+
+- func: special_log_ndtr(Tensor self) -> Tensor
+ structured_delegate: special_log_ndtr.out
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_log_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: special
+ variants: function
+ dispatch:
+ CPU, CUDA: special_log_ndtr_out
+ tags: pointwise
+
+- func: special_expm1(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_exp2(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_psi(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_digamma(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_gammaln(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_gammaln.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_erf(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_erfc(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+
+- func: special_erfcx(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+ structured_delegate: special_erfcx.out
+ tags: pointwise
+
+- func: special_erfcx.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: special_erfcx_out
+ tags: pointwise
+
+- func: special_erfinv(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+
+- func: special_ndtr(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_xlog1py(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ structured_delegate: special_xlog1py.out
+ tags: pointwise
+
+- func: special_xlog1py.self_scalar(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_xlog1py
+ tags: pointwise
+
+- func: special_xlog1py.other_scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_xlog1py
+ tags: pointwise
+
+- func: special_xlog1py.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: special
+ variants: function
+ dispatch:
+ CPU, CUDA: special_xlog1py_out
+ tags: pointwise
+
+- func: special_xlog1py.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_xlog1py_out
+ tags: pointwise
+
+- func: special_xlog1py.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_xlog1py_out
+ tags: pointwise
+
+- func: special_xlogy(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+
+- func: special_xlogy.self_scalar(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+
+- func: special_xlogy.other_scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+
+- func: special_xlogy.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+
+- func: special_xlogy.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+
+- func: special_xlogy.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+
+- func: special_zeta(Tensor self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ structured_delegate: special_zeta.out
+ tags: pointwise
+
+- func: special_zeta.self_scalar(Scalar self, Tensor other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_zeta
+ tags: pointwise
+
+- func: special_zeta.other_scalar(Tensor self, Scalar other) -> Tensor
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_zeta
+ tags: pointwise
+
+- func: special_zeta.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ structured: True
+ structured_inherits: TensorIteratorBase
+ python_module: special
+ variants: function
+ dispatch:
+ CPU, CUDA: special_zeta_out
+ tags: pointwise
+
+- func: special_zeta.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_zeta_out
+ tags: pointwise
+
+- func: special_zeta.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck # TensorIterator
+ python_module: special
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: special_zeta_out
+ tags: pointwise
+
+- func: special_i0(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_i0e(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+ structured_delegate: special_i0e.out
+ tags: pointwise
+
+- func: special_i0e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: special_i0e_out
+ tags: pointwise
+
+- func: special_i1(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+ structured_delegate: special_i1.out
+ tags: pointwise
+
+- func: special_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA, MPS: special_i1_out
+ tags: pointwise
+
+- func: special_i1e(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+ structured_delegate: special_i1e.out
+ tags: pointwise
+
+- func: special_i1e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ structured: True
+ structured_inherits: TensorIteratorBase
+ dispatch:
+ CPU, CUDA: special_i1e_out
+ tags: pointwise
+
+- func: special_logit(Tensor self, float? eps=None) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+
+- func: special_polygamma(int n, Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+
+- func: special_logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+
+- func: special_expit(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_expit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_sinc(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_round(Tensor self, *, int decimals=0) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_round.out(Tensor self, *, int decimals=0, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_log1p(Tensor self) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_log_softmax(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_gammainc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_gammainc(Tensor self, Tensor other) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_gammaincc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_gammaincc(Tensor self, Tensor other) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_multigammaln(Tensor self, int p) -> Tensor
+ python_module: special
+ variants: function
+
+- func: special_multigammaln.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: special
+ variants: function
+
+- func: special_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+ python_module: special
+ variants: function
+
+## Functions related to the fast Fourier transform and the torch.fft namespace
+# Note [FFT namespace binding]
+# Functions in the fft python module should have their names start with
+# "fft_" underscore and be bound to the desired Python name in
+# torch/fft/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/fft.h.
+# The "fft_" names should be hidden from the user and not documented.
+#
+# See fft_fft as an example.
+
+# torch.fft.fft
+# NOTE: NOT an alias for torch.fft, which has different semantics
+- func: fft_fft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_fft_symint
+
+- func: fft_fft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_fft_symint_out
+
+- func: fft_ifft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ifft_symint
+
+- func: fft_ifft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ifft_symint_out
+
+- func: fft_rfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_rfft_symint
+
+- func: fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_rfft_symint_out
+
+- func: fft_irfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_irfft_symint
+
+- func: fft_irfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_irfft_symint_out
+
+- func: fft_hfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_hfft_symint
+
+- func: fft_hfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_hfft_symint_out
+
+- func: fft_ihfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ihfft_symint
+
+- func: fft_ihfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ihfft_symint_out
+
+- func: fft_fft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_fft2_symint
+
+- func: fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_fft2_symint_out
+
+- func: fft_ifft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ifft2_symint
+
+- func: fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ifft2_symint_out
+
+- func: fft_rfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_rfft2_symint
+
+- func: fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_rfft2_symint_out
+
+- func: fft_irfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_irfft2_symint
+
+- func: fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_irfft2_symint_out
+
+- func: fft_hfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_hfft2_symint
+
+- func: fft_hfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_hfft2_symint_out
+
+- func: fft_ihfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ihfft2_symint
+
+- func: fft_ihfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ihfft2_symint_out
+
+- func: fft_fftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_fftn_symint
+
+- func: fft_fftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_fftn_symint_out
+
+- func: fft_ifftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ifftn_symint
+
+- func: fft_ifftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ifftn_symint_out
+
+- func: fft_rfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_rfftn_symint
+
+- func: fft_rfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_rfftn_symint_out
+
+- func: fft_irfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_irfftn_symint
+
+- func: fft_irfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_irfftn_symint_out
+
+- func: fft_hfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_hfftn_symint
+
+- func: fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_hfftn_symint_out
+
+- func: fft_ihfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ihfftn_symint
+
+- func: fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
+ use_const_ref_for_mutable_tensors: True
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: fft_ihfftn_symint_out
+
+- func: fft_fftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: fft_fftfreq
+
+- func: fft_fftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: fft_fftfreq_out
+
+- func: fft_rfftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: fft_rfftfreq
+
+- func: fft_rfftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: fft
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: fft_rfftfreq_out
+
+- func: fft_fftshift(Tensor self, int[1]? dim=None) -> Tensor
+ python_module: fft
+ variants: function
+
+- func: fft_ifftshift(Tensor self, int[1]? dim=None) -> Tensor
+ python_module: fft
+ variants: function
+
+## Functions for linear algebra and the torch.linalg namespace
+# Note [linalg namespace binding]
+# Functions in the linalg python module should have their names start with
+# "linalg_" and be bound to the desired Python name in
+# torch/linalg/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/linalg.h.
+# The "linalg_" names should be hidden from the user and not documented.
+#
+# See linalg_det as an example.
+
+# "_ex" stands for experimental
+- func: linalg_cholesky_ex(Tensor self, *, bool upper=False, bool check_errors=False) -> (Tensor L, Tensor info)
+ python_module: linalg
+ structured_delegate: linalg_cholesky_ex.L
+
+- func: linalg_cholesky_ex.L(Tensor self, *, bool upper=False, bool check_errors=False, Tensor(a!) L, Tensor(b!) info) -> (Tensor(a!) L, Tensor(b!) info)
+ python_module: linalg
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_cholesky_ex_out
+
+- func: linalg_cholesky(Tensor self, *, bool upper=False) -> Tensor
+ python_module: linalg
+
+- func: linalg_cholesky.out(Tensor self, *, bool upper=False, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_cross(Tensor self, Tensor other, *, int dim=-1) -> Tensor
+ python_module: linalg
+ variants: function
+ structured_delegate: linalg_cross.out
+ dispatch:
+ ZeroTensor: linalg_cross_zerotensor
+
+- func: linalg_cross.out(Tensor self, Tensor other, *, int dim=-1, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ structured: True
+ dispatch:
+ CPU, CUDA, MPS: linalg_cross_out
+
+# linalg.lu_factor
+- func: linalg_lu_factor(Tensor A, *, bool pivot=True) -> (Tensor LU, Tensor pivots)
+ python_module: linalg
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: linalg_lu_factor
+ MPS: linalg_lu_factor_mps
+
+- func: linalg_lu_factor.out(Tensor A, *, bool pivot=True, Tensor(a!) LU, Tensor(b!) pivots) -> (Tensor(a!) LU, Tensor(b!) pivots)
+ python_module: linalg
+ variants: function
+ dispatch:
+ CompositeImplicitAutograd: linalg_lu_factor_out
+ MPS: linalg_lu_factor_out_mps
+
+- func: linalg_lu_factor_ex(Tensor A, *, bool pivot=True, bool check_errors=False) -> (Tensor LU, Tensor pivots, Tensor info)
+ python_module: linalg
+ structured_delegate: linalg_lu_factor_ex.out
+ variants: function
+
+- func: linalg_lu_factor_ex.out(Tensor A, *, bool pivot=True, bool check_errors=False, Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info)
+ python_module: linalg
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_lu_factor_ex_out
+
+# linalg.lu
+- func: linalg_lu(Tensor A, *, bool pivot=True) -> (Tensor P, Tensor L, Tensor U)
+ python_module: linalg
+ structured_delegate: linalg_lu.out
+ variants: function
+
+- func: linalg_lu.out(Tensor A, *, bool pivot=True, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U)
+ python_module: linalg
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_lu_out
+
+# linalg.lu_solve
+- func: linalg_lu_solve(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False) -> Tensor
+ python_module: linalg
+ structured_delegate: linalg_lu_solve.out
+ variants: function
+
+- func: linalg_lu_solve.out(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_lu_solve_out
+
+# linalg.det
+- func: _linalg_det(Tensor A) -> (Tensor result, Tensor LU, Tensor pivots)
+ structured_delegate: _linalg_det.result
+
+- func: _linalg_det.result(Tensor A, *, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots)
+ structured: True
+ dispatch:
+ CPU, CUDA: _linalg_det_out
+
+- func: linalg_det(Tensor A) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_det.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+# torch.det, alias for torch.linalg.det
+- func: det(Tensor self) -> Tensor
+ variants: function, method
+
+- func: linalg_ldl_factor_ex(Tensor self, *, bool hermitian=False, bool check_errors=False) -> (Tensor LD, Tensor pivots, Tensor info)
+ structured_delegate: linalg_ldl_factor_ex.out
+ python_module: linalg
+ variants: function
+
+- func: linalg_ldl_factor_ex.out(Tensor self, *, bool hermitian=False, bool check_errors=False, Tensor(a!) LD, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LD, Tensor(b!) pivots, Tensor(c!) info)
+ structured: True
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_ldl_factor_ex_out
+
+- func: linalg_ldl_factor(Tensor self, *, bool hermitian=False) -> (Tensor LD, Tensor pivots)
+ python_module: linalg
+ variants: function
+
+- func: linalg_ldl_factor.out(Tensor self, *, bool hermitian=False, Tensor(a!) LD, Tensor(b!) pivots) -> (Tensor(a!) LD, Tensor(b!) pivots)
+ python_module: linalg
+ variants: function
+
+- func: linalg_ldl_solve(Tensor LD, Tensor pivots, Tensor B, *, bool hermitian=False) -> Tensor
+ structured_delegate: linalg_ldl_solve.out
+ python_module: linalg
+ variants: function
+
+- func: linalg_ldl_solve.out(Tensor LD, Tensor pivots, Tensor B, *, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+ structured: True
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_ldl_solve_out
+
+- func: linalg_lstsq(Tensor self, Tensor b, float? rcond=None, *, str? driver=None) -> (Tensor solution, Tensor residuals, Tensor rank, Tensor singular_values)
+ python_module: linalg
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: linalg_lstsq
+ tags: dynamic_output_shape
+
+- func: linalg_lstsq.out(Tensor self, Tensor b, float? rcond=None, *, str? driver=None, Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values) -> (Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values)
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_lstsq_out
+ tags: dynamic_output_shape
+
+# torch.linalg.matmul, alias for torch.matmul
+- func: linalg_matmul(Tensor self, Tensor other) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_vecdot(Tensor x, Tensor y, *, int dim=-1) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_vecdot.out(Tensor x, Tensor y, *, int dim=-1, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_matrix_exp(Tensor self) -> Tensor
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_matrix_exp
+ autogen: linalg_matrix_exp.out
+
+- func: _linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet, Tensor LU, Tensor pivots)
+ structured_delegate: _linalg_slogdet.sign
+
+- func: _linalg_slogdet.sign(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots) -> (Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots)
+ structured: True
+ dispatch:
+ CPU, CUDA: _linalg_slogdet_out
+
+- func: linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet)
+ python_module: linalg
+
+- func: linalg_slogdet.out(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet)
+ python_module: linalg
+
+- func: slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet)
+ variants: function, method
+
+- func: slogdet.out(Tensor self, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet)
+ variants: function
+
+- func: logdet(Tensor self) -> Tensor
+ variants: function, method
+
+- func: linalg_eig(Tensor self) -> (Tensor eigenvalues, Tensor eigenvectors)
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_eig
+
+- func: linalg_eig.out(Tensor self, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+ python_module: linalg
+ dispatch:
+ CPU, CUDA: linalg_eig_out
+
+- func: _linalg_eigvals(Tensor self) -> Tensor
+ python_module: linalg
+ dispatch:
+ CPU, CUDA: _linalg_eigvals
+
+- func: linalg_eigvals(Tensor self) -> Tensor
+ python_module: linalg
+
+- func: linalg_eigvals.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ dispatch:
+ CPU, CUDA: linalg_eigvals_out
+
+# This function is exposes the `compute_v` flag, which is then used to implement `linalg.eigh` and
+# `linalg.eigvalsh` as composite functions that call this one
+- func: _linalg_eigh(Tensor A, str UPLO="L", bool compute_v=True) -> (Tensor eigenvalues, Tensor eigenvectors)
+ structured_delegate: _linalg_eigh.eigenvalues
+
+- func: _linalg_eigh.eigenvalues(Tensor A, str UPLO="L", bool compute_v=True, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+ structured: True
+ dispatch:
+ CPU, CUDA: _linalg_eigh_out
+
+- func: linalg_eigh(Tensor self, str UPLO="L") -> (Tensor eigenvalues, Tensor eigenvectors)
+ python_module: linalg
+
+- func: linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+ python_module: linalg
+
+- func: linalg_eigvalsh(Tensor self, str UPLO="L") -> Tensor
+ python_module: linalg
+
+- func: linalg_eigvalsh.out(Tensor self, str UPLO="L", *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_householder_product(Tensor input, Tensor tau) -> Tensor
+ python_module: linalg
+ variants: function
+ dispatch:
+ CPU, CUDA: linalg_householder_product
+
+- func: linalg_householder_product.out(Tensor input, Tensor tau, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ dispatch:
+ CPU, CUDA: linalg_householder_product_out
+
+- func: linalg_inv_ex(Tensor A, *, bool check_errors=False) -> (Tensor inverse, Tensor info)
+ python_module: linalg
+ structured_delegate: linalg_inv_ex.inverse
+
+- func: linalg_inv_ex.inverse(Tensor A, *, bool check_errors=False, Tensor(a!) inverse, Tensor(b!) info) -> (Tensor(a!) inverse, Tensor(b!) info)
+ python_module: linalg
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_inv_ex_out
+ MPS: linalg_inv_ex_out_mps
+
+- func: linalg_inv(Tensor A) -> Tensor
+ python_module: linalg
+
+- func: linalg_inv.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: inverse(Tensor self) -> Tensor
+ variants: function, method
+
+- func: inverse.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: inner(Tensor self, Tensor other) -> Tensor
+ variants: function, method
+
+- func: inner.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: outer(Tensor self, Tensor vec2) -> Tensor
+ variants: function, method
+
+- func: outer.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
+
+# torch.ger, alias for torch.outer
+- func: ger(Tensor self, Tensor vec2) -> Tensor
+ variants: function, method
+
+- func: ger.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!)
+
+- func: linalg_norm(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_norm.ord_str(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_norm.out(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_vector_norm(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ python_module: linalg
+ variants: function
+ structured_delegate: linalg_vector_norm.out
+
+- func: linalg_vector_norm.out(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_vector_norm_out
+ MPS: linalg_vector_norm_out_mps
+
+- func: linalg_matrix_norm(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ python_module: linalg
+
+- func: linalg_matrix_norm.out(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_matrix_norm.str_ord(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor
+ python_module: linalg
+
+- func: linalg_matrix_norm.str_ord_out(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+# This function is exposes the `compute_uv` flag, which is then used to implement `linalg.svd` and
+# `linalg.svdvals` as composite functions that call this one
+- func: _linalg_svd(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh)
+ variants: function
+ structured_delegate: _linalg_svd.U
+
+- func: _linalg_svd.U(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh)
+ structured: True
+ dispatch:
+ CPU, CUDA: _linalg_svd_out
+
+- func: linalg_svd(Tensor A, bool full_matrices=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh)
+ python_module: linalg
+ variants: function
+
+- func: linalg_svd.U(Tensor A, bool full_matrices=True, *, str? driver=None, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh)
+ python_module: linalg
+ variants: function
+
+- func: linalg_svdvals(Tensor A, *, str? driver=None) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_svdvals.out(Tensor A, *, str? driver=None, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_cond(Tensor self, Scalar? p=None) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_cond.out(Tensor self, Scalar? p=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_cond.p_str(Tensor self, str p) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_cond.p_str_out(Tensor self, str p, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_pinv.atol_rtol_tensor(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor
+ python_module: linalg
+ variants: function
+ dispatch:
+ # calls svd, which calls mH() (view op)
+ # also calls narrow()
+ CompositeExplicitAutogradNonFunctional: linalg_pinv
+
+- func: linalg_pinv.atol_rtol_tensor_out(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: linalg_pinv_out
+
+- func: linalg_pinv.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor
+ cpp_no_default_args: ['atol', 'rtol']
+ python_module: linalg
+ variants: function
+
+- func: linalg_pinv.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+ cpp_no_default_args: ['atol', 'rtol']
+ python_module: linalg
+ variants: function
+
+- func: linalg_pinv(Tensor self, float rcond, bool hermitian=False) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_pinv.rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_pinv.out(Tensor self, float rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_pinv.out_rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: _linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor LU, Tensor pivots, Tensor info)
+ structured_delegate: _linalg_solve_ex.result
+
+- func: _linalg_solve_ex.result(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info)
+ structured: True
+ dispatch:
+ CPU, CUDA: _linalg_solve_ex_out
+
+- func: linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor info)
+ python_module: linalg
+
+- func: linalg_solve_ex.out(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) info) -> (Tensor(a!) result, Tensor(b!) info)
+ python_module: linalg
+
+- func: linalg_solve(Tensor A, Tensor B, *, bool left=True) -> Tensor
+ python_module: linalg
+
+- func: _spsolve(Tensor A, Tensor B, *, bool left=True) -> Tensor
+ python_module: sparse
+ dispatch:
+ SparseCsrCUDA: _sparse_csr_linear_solve
+
+- func: linalg_solve.out(Tensor A, Tensor B, *, bool left=True, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_tensorinv(Tensor self, int ind=2) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_tensorinv.out(Tensor self, int ind=2, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_tensorsolve(Tensor self, Tensor other, int[]? dims=None) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_tensorsolve.out(Tensor self, Tensor other, int[]? dims=None, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_qr(Tensor A, str mode='reduced') -> (Tensor Q, Tensor R)
+ python_module: linalg
+ variants: function
+ structured_delegate: linalg_qr.out
+
+- func: linalg_qr.out(Tensor A, str mode='reduced', *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R)
+ python_module: linalg
+ structured: True
+ dispatch:
+ CPU, CUDA: linalg_qr_out
+
+- func: linalg_matrix_power(Tensor self, int n) -> Tensor
+ python_module: linalg
+
+- func: linalg_matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+- func: linalg_matrix_rank.atol_rtol_tensor(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank.atol_rtol_tensor_out(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor
+ cpp_no_default_args: ['atol', 'rtol']
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!)
+ cpp_no_default_args: ['atol', 'rtol']
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank(Tensor self, float tol, bool hermitian=False) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank.out(Tensor self, float tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank.tol_tensor(Tensor input, Tensor tol, bool hermitian=False) -> Tensor
+ python_module: linalg
+ variants: function
+
+- func: linalg_matrix_rank.out_tol_tensor(Tensor input, Tensor tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+ variants: function
+
+- func: linalg_multi_dot(Tensor[] tensors) -> Tensor
+ python_module: linalg
+
+- func: linalg_multi_dot.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)
+ python_module: linalg
+
+## Functions related to the `torch.nested` namespace
+# Note [nested namespace binding]
+# Functions in the nested python module should have their names start with
+# "nested_" underscore and be bound to the desired Python name in
+# torch/nested/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/nested.h.
+# The "nested_" names should be hidden from the user and not documented.
+
+- func: nested_to_padded_tensor(Tensor self, float padding, int[]? output_size=None) -> Tensor
+ python_module: nested
+ variants: function
+
+## Functions that are only for testing
+# It is undocumented and should not be used outside of tests.
+- func: _test_serialization_subcmul(Tensor self, Tensor other, Scalar alpha=1) -> Tensor
+
+# Note: for testing COW materialization within `at::parallel_for` loop function
+- func: _test_parallel_materialize(Tensor self, int num_parallel, bool skip_first=False) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _test_parallel_materialize
+
+# Note: this function is only for testing.
+- func: _test_optional_intlist(Tensor values, int[]? addends) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: _test_optional_intlist
+ autogen: _test_optional_intlist.out
+
+# Note: this function is only for testing.
+- func: _test_optional_filled_intlist(Tensor values, int[2]? addends) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: _test_optional_intlist
+ autogen: _test_optional_filled_intlist.out
+
+# Note: this function is only for testing.
+- func: _test_optional_floatlist(Tensor values, float[]? addends) -> Tensor
+ python_module: nn
+ dispatch:
+ CPU: _test_optional_floatlist
+ autogen: _test_optional_floatlist.out
+
+# Note: this function is only for testing.
+- func: _test_string_default(Tensor dummy, str a="\"'\\", str b='"\'\\') -> Tensor
+ python_module: nn
+
+# Note: this function is only for testing.
+- func: _test_ambiguous_defaults.a(Tensor dummy, int a=1, int b=1) -> Tensor
+ python_module: nn
+
+# Note: this function is only for testing.
+- func: _test_ambiguous_defaults.b(Tensor dummy, int a=2, str b="2") -> Tensor
+ cpp_no_default_args: ['a', 'b']
+ python_module: nn
+
+# Note: this function is only for testing.
+- func: _test_warn_in_autograd(Tensor self) -> Tensor
+ python_module: nn
+ dispatch:
+ CompositeExplicitAutograd: _test_warn_in_autograd
+ autogen: _test_warn_in_autograd.out
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch.fullcoverage(Tensor self) -> Tensor
+ dispatch:
+ # the NestedTensor keys are necessary because NestedTensor has been removed
+ # from the CompositeExplicitAutograd keyset see Note [NestedTensor Not Included in Backend Keys]
+ CompositeExplicitAutograd, NestedTensorCPU, NestedTensorCUDA: _test_autograd_multiple_dispatch_fullcoverage
+ autogen: _test_autograd_multiple_dispatch.fullcoverage_out
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch.ntonly(Tensor self, bool b) -> Tensor
+ dispatch:
+ CompositeImplicitAutograd, NestedTensorCPU, NestedTensorCUDA: _test_autograd_multiple_dispatch_ntonly
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch_view(Tensor(a) self) -> Tensor(a)
+ dispatch:
+ CompositeExplicitAutograd: _test_autograd_multiple_dispatch_view
+
+# Note: this function is only for testing.
+- func: _test_autograd_multiple_dispatch_view_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _test_autograd_multiple_dispatch_view_copy
+ tags: view_copy
+ autogen: _test_autograd_multiple_dispatch_view_copy.out
+
+- func: segment_reduce(Tensor data, str reduce, *, Tensor? lengths=None, Tensor? indices=None, Tensor? offsets=None, int axis=0, bool unsafe=False, Scalar? initial=None) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: segment_reduce_kernel
+ autogen: segment_reduce.out
+
+- func: _segment_reduce_backward(Tensor grad, Tensor output, Tensor data, str reduce, *, Tensor? lengths=None, Tensor? offsets=None, int axis=0, Scalar? initial=None) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA: _segment_reduce_backward_kernel
+ autogen: _segment_reduce_backward.out
+
+- func: pad_sequence(Tensor[] sequences, bool batch_first=False, float padding_value=0.0, str padding_side="right") -> Tensor
+ python_module: nn
+ variants: function
+
+- func: flatten_dense_tensors(Tensor[] tensors) -> Tensor
+ variants: function
+ python_module: nn
+
+- func: unflatten_dense_tensors(Tensor flat, Tensor[] tensors) -> Tensor[]
+ variants: function
+ python_module: nn
+
+- func: _nested_tensor_from_tensor_list(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _nested_tensor_from_tensor_list
+ autogen: _nested_tensor_from_tensor_list.out
+
+- func: _fw_primal_copy(Tensor self, int level) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _fw_primal_copy
+ tags: view_copy
+ autogen: _fw_primal_copy.out
+
+- func: _make_dual_copy(Tensor primal, Tensor tangent, int level) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _make_dual_copy
+ tags: view_copy
+ autogen: _make_dual_copy.out
+
+- func: view_as_real_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: view_as_real_copy
+ tags: view_copy
+ autogen: view_as_real_copy.out
+
+- func: view_as_complex_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: view_as_complex_copy
+ tags: view_copy
+ autogen: view_as_complex_copy.out
+
+- func: _conj_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _conj_copy
+ tags: view_copy
+ autogen: _conj_copy.out
+
+- func: _neg_view_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _neg_view_copy
+ tags: view_copy
+ autogen: _neg_view_copy.out
+
+- func: as_strided_copy(Tensor self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: as_strided_copy_symint
+ tags: view_copy
+ autogen: as_strided_copy.out
+
+- func: _sparse_broadcast_to_copy(Tensor self, int[] size) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _sparse_broadcast_to_copy
+ tags: view_copy
+ autogen: _sparse_broadcast_to_copy.out
+
+- func: diagonal_copy(Tensor self, int offset=0, int dim1=0, int dim2=1) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: diagonal_copy
+ tags: view_copy
+ autogen: diagonal_copy.out
+
+- func: expand_copy(Tensor self, SymInt[] size, *, bool implicit=False) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: expand_copy_symint
+ tags: view_copy
+ autogen: expand_copy.out
+
+- func: permute_copy(Tensor self, int[] dims) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: permute_copy
+ tags: view_copy
+ autogen: permute_copy.out
+
+- func: _reshape_alias_copy(Tensor self, SymInt[] size, SymInt[] stride) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _reshape_alias_copy_symint
+ tags: view_copy
+ autogen: _reshape_alias_copy.out
+
+- func: select_copy.int(Tensor self, int dim, SymInt index) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: select_copy_symint
+ SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta: select_copy_sparse_csr
+ tags: view_copy
+ autogen: select_copy.int_out
+
+- func: detach_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: detach_copy
+ tags: view_copy
+ autogen: detach_copy.out
+
+- func: slice_copy.Tensor(Tensor self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: slice_copy_Tensor_symint
+ tags: view_copy
+ autogen: slice_copy.Tensor_out
+
+- func: split_copy.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[]
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: split_copy_Tensor_symint
+ tags: view_copy
+
+- func: split_with_sizes_copy(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[]
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: split_with_sizes_copy_symint
+ tags: view_copy
+
+- func: squeeze_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: squeeze_copy
+ tags: view_copy
+ autogen: squeeze_copy.out
+
+- func: squeeze_copy.dim(Tensor self, int dim) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: squeeze_copy_dim
+ tags: view_copy
+ autogen: squeeze_copy.dim_out
+
+- func: squeeze_copy.dims(Tensor self, int[] dim) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: squeeze_copy_dims
+ tags: view_copy
+ autogen: squeeze_copy.dims_out
+
+- func: t_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: t_copy
+ tags: view_copy
+ autogen: t_copy.out
+
+- func: transpose_copy.int(Tensor self, int dim0, int dim1) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: transpose_copy_int
+ tags: view_copy
+ autogen: transpose_copy.int_out
+
+- func: unsqueeze_copy(Tensor self, int dim) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: unsqueeze_copy
+ tags: view_copy
+ autogen: unsqueeze_copy.out
+
+- func: _indices_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _indices_copy
+ tags: view_copy
+ autogen: _indices_copy.out
+
+- func: _values_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: _values_copy
+ tags: view_copy
+ autogen: _values_copy.out
+
+- func: indices_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: indices_copy
+ tags: view_copy
+ autogen: indices_copy.out
+
+- func: values_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: values_copy
+ tags: view_copy
+ autogen: values_copy.out
+
+- func: crow_indices_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: crow_indices_copy
+ tags: view_copy
+ autogen: crow_indices_copy.out
+
+- func: col_indices_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: col_indices_copy
+ tags: view_copy
+ autogen: col_indices_copy.out
+
+- func: ccol_indices_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: ccol_indices_copy
+ tags: view_copy
+ autogen: ccol_indices_copy.out
+
+- func: row_indices_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: row_indices_copy
+ tags: view_copy
+ autogen: row_indices_copy.out
+
+- func: unbind_copy.int(Tensor self, int dim=0) -> Tensor[]
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: unbind_copy_int
+ tags: view_copy
+
+- func: unbind_copy.int_out(Tensor self, int dim=0, *, Tensor(a!)[] out) -> ()
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: unbind_copy_int_out
+
+- func: split_copy.Tensor_out(Tensor self, SymInt split_size, int dim=0, *, Tensor(a!)[] out) -> ()
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: split_copy_Tensor_out
+
+
+- func: split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: split_with_sizes_copy_out
+ CUDA: split_with_sizes_copy_out_cuda
+
+- func: view_copy(Tensor self, SymInt[] size) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: view_copy_symint
+ tags: view_copy
+ autogen: view_copy.out
+
+- func: view_copy.dtype(Tensor self, ScalarType dtype) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: view_copy_dtype
+ tags: view_copy
+ autogen: view_copy.dtype_out
+
+- func: unfold_copy(Tensor self, int dimension, int size, int step) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: unfold_copy
+ tags: view_copy
+ autogen: unfold_copy.out
+
+- func: alias_copy(Tensor self) -> Tensor
+ variants: function
+ dispatch:
+ CompositeExplicitAutogradNonFunctional: alias_copy
+ tags: view_copy
+ autogen: alias_copy.out
+
+- func: to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor
+ variants: method
+ dispatch:
+ NestedTensorCPU: NestedTensor_to_padded_tensor_generic
+ NestedTensorCUDA: NestedTensor_to_padded_tensor_cuda
+ autogen: to_padded_tensor.out
+
+- func: _jagged_to_padded_dense_forward(Tensor values, Tensor[] offsets, SymInt[] max_lengths, float padding_value=0.0) -> Tensor
+ variants: function
+ dispatch:
+ CUDA: _fbgemm_jagged_to_padded_dense_forward
+ CPU: _jagged_to_padded_dense_forward_cpu
+
+- func: _padded_dense_to_jagged_forward(Tensor dense, Tensor[] offsets, SymInt? total_L=None) -> Tensor
+ variants: function
+ dispatch:
+ CUDA: _fbgemm_dense_to_jagged_forward_symint
+ CPU: _padded_dense_to_jagged_forward_cpu
+
+- func: _nested_from_padded_tensor(Tensor padded, Tensor offsets, Tensor dummy, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None, SymInt? sum_S=None) -> Tensor
+ variants: function
+ device_check: NoCheck
+ dispatch: {}
+
+- func: _nested_tensor_softmax_with_shape(Tensor self, Tensor query) -> Tensor
+ dispatch:
+ NestedTensorCPU: NestedTensor_softmax_dropout
+ NestedTensorCUDA: NestedTensor_softmax_dropout_cuda
+ tags: nondeterministic_seeded
+
+- func: _safe_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: _safe_softmax
+ NestedTensorCPU, NestedTensorCUDA: _safe_softmax
+
+# Apparently, putting "forward" in the name will cause Python bindings to be skipped, so "fwd" it is.
+- func: _transformer_encoder_layer_fwd(Tensor src, int embed_dim, int num_heads, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, bool use_gelu, bool norm_first, float eps, Tensor norm_weight_1, Tensor norm_bias_1, Tensor norm_weight_2, Tensor norm_bias_2, Tensor ffn_weight_1, Tensor ffn_bias_1, Tensor ffn_weight_2, Tensor ffn_bias_2, Tensor? mask=None, int? mask_type=None) -> Tensor
+ variants: function
+ dispatch:
+ CPU, CUDA, NestedTensorCPU, NestedTensorCUDA: transformer_encoder_layer_forward
+ autogen: _transformer_encoder_layer_fwd.out
+
+- func: _native_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None) -> (Tensor, Tensor)
+ variants: function
+ dispatch:
+ CPU, NestedTensorCPU: native_multi_head_attention_cpu
+ CUDA, NestedTensorCUDA: native_multi_head_attention_cuda
+ autogen: _native_multi_head_attention.out
+
+- func: scaled_dot_product_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None, bool enable_gqa=False) -> Tensor
+ python_module: nn
+ variants: function
+ autogen: scaled_dot_product_attention.out
+ tags: nondeterministic_seeded
+
+# This aten function is kept so that we can test the choice function from Python
+- func: _fused_sdp_choice(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None, bool enable_gqa=False) -> int
+ dispatch:
+ Meta: _fused_sdp_choice_meta
+ CPU, NestedTensorCPU: _fused_sdp_choice_cpp
+ CUDA, NestedTensorCUDA: _fused_sdp_choice_cuda
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_attention_math(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None, bool enable_gqa=False) -> (Tensor, Tensor)
+ variants: function
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_attention_math_for_mps(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None) -> (Tensor, Tensor)
+ dispatch:
+ MPS: _scaled_dot_product_attention_math_mps
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_flash_attention(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+ dispatch:
+ CUDA: _scaled_dot_product_flash_attention_cuda
+ NestedTensorCUDA: _scaled_dot_product_flash_attention_nestedtensor_cuda
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_flash_attention_for_cpu(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor output, Tensor logsumexp)
+ dispatch:
+ CPU: _scaled_dot_product_flash_attention_cpu
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_fused_attention_overrideable(Tensor query, Tensor key, Tensor value, Tensor? attn_bias=None, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+ dispatch:
+ CompositeExplicitAutograd: _scaled_dot_product_fused_attention_overrideable
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CUDA: _scaled_dot_product_flash_attention_backward_cuda
+ NestedTensorCUDA: _scaled_dot_product_flash_attention_backward_nested
+
+- func: _scaled_dot_product_flash_attention_for_cpu_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, float dropout_p, bool is_causal, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CPU: _scaled_dot_product_flash_attention_cpu_backward
+
+- func: _scaled_dot_product_fused_attention_overrideable_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor attn_bias, bool[4] grad_input_mask, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value, Tensor grad_attn_bias)
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CompositeExplicitAutograd: _scaled_dot_product_fused_attention_overrideable_backward
+
+- func: _scaled_dot_product_efficient_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, *, float? scale=None) -> (Tensor output, Tensor log_sumexp, Tensor philox_seed, Tensor philox_offset)
+ dispatch:
+ CUDA: _scaled_dot_product_efficient_attention_cuda
+ NestedTensorCUDA: _scaled_dot_product_efficient_attention_nestedtensor_cuda
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, Tensor attn_bias, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, float dropout_p, bool[4] grad_input_mask, bool is_causal=False, *, float? scale=None) -> (Tensor, Tensor, Tensor, Tensor)
+ device_check: NoCheck
+ dispatch:
+ CUDA: _scaled_dot_product_efficient_attention_backward_cuda
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_cudnn_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+ dispatch:
+ CUDA: _scaled_dot_product_cudnn_attention_cuda
+ tags: nondeterministic_seeded
+
+- func: _scaled_dot_product_cudnn_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor attn_bias, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, *, float? scale=None) -> (Tensor, Tensor, Tensor)
+ dispatch:
+ CUDA: _scaled_dot_product_cudnn_attention_backward_cuda
+ tags: nondeterministic_seeded
+
+- func: _flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)
+ variants: function
+ dispatch:
+ CUDA: _flash_attention_forward
+ tags: nondeterministic_seeded
+
+- func: _flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None) -> (Tensor, Tensor, Tensor)
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CUDA: _flash_attention_backward
+
+# Returns output, logsumexp if compute_logsumexp
+- func: _efficient_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt? max_seqlen_q, SymInt? max_seqlen_k, float dropout_p, int custom_mask_type, bool compute_log_sumexp=False, *, float? scale=None, Tensor? seqlen_k=None, int? window_size=None) -> (Tensor output, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, SymInt max_seqlen_batch_q, SymInt max_seqlen_batch_k)
+ variants: function
+ dispatch:
+ CUDA: _efficient_attention_forward
+ tags: nondeterministic_seeded
+
+- func: _efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor out, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt max_seqlen_q, SymInt max_seqlen_k, Tensor logsumexp, float dropout_p, Tensor philox_seed, Tensor philox_offset, int custom_mask_type, bool bias_requires_grad, *, float? scale=None, int? num_splits_key=None, int? window_size=None, bool shared_storage_dqdkdv=False) -> (Tensor, Tensor, Tensor, Tensor)
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CUDA: _efficient_attention_backward
+
+- func: _triton_scaled_dot_attention(Tensor q, Tensor k, Tensor v, float dropout_p=0.0) -> Tensor
+ variants: function
+ dispatch:
+ CUDA: triton_scaled_dot_attention
+ tags: nondeterministic_seeded
+ autogen: _triton_scaled_dot_attention.out
+
+- func: _fill_mem_eff_dropout_mask_(Tensor(a!) self, float dropout_p, int seed, int offset) -> Tensor(a!)
+ variants: function
+ dispatch:
+ CUDA: _fill_mem_eff_dropout_mask_
+ tags: nondeterministic_seeded
+
+- func: _triton_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None) -> Tensor
+ variants: function
+ dispatch:
+ CUDA: triton_multi_head_attention
+ autogen: _triton_multi_head_attention.out
+
+- func: special_airy_ai(Tensor x) -> Tensor
+ python_module: special
+ structured_delegate: special_airy_ai.out
+ variants: function
+ tags: pointwise
+
+- func: special_airy_ai.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_airy_ai_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_j0(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_bessel_j0.out
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_j0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_bessel_j0_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_j1(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_bessel_j1.out
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_j1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_bessel_j1_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_y0(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_bessel_y0.out
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_bessel_y0_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_y1(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_bessel_y1.out
+ variants: function
+ tags: pointwise
+
+- func: special_bessel_y1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_bessel_y1_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_chebyshev_polynomial_t.out
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_t
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_t
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_t.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_chebyshev_polynomial_t_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_t.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_t_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_t.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_t_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_chebyshev_polynomial_u.out
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_u
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_u
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_chebyshev_polynomial_u_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_u_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_u_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_chebyshev_polynomial_v.out
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_v
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_v
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_v.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_chebyshev_polynomial_v_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_v.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_v_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_v.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_v_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_chebyshev_polynomial_w.out
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_w
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_w
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_chebyshev_polynomial_w_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_w_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_chebyshev_polynomial_w_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_h(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_hermite_polynomial_h.out
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_h.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_h
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_h.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_h
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_h.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_hermite_polynomial_h_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_h.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_h_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_h.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_h_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_he(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_hermite_polynomial_he.out
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_he.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_he
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_he.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_he
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_he.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_hermite_polynomial_he_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_he.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_he_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_hermite_polynomial_he.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_hermite_polynomial_he_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_laguerre_polynomial_l(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_laguerre_polynomial_l.out
+ variants: function
+ tags: pointwise
+
+- func: special_laguerre_polynomial_l.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_laguerre_polynomial_l
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_laguerre_polynomial_l.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_laguerre_polynomial_l
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_laguerre_polynomial_l.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_laguerre_polynomial_l_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_laguerre_polynomial_l.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_laguerre_polynomial_l_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_laguerre_polynomial_l.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_laguerre_polynomial_l_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_legendre_polynomial_p(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_legendre_polynomial_p.out
+ variants: function
+ tags: pointwise
+
+- func: special_legendre_polynomial_p.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_legendre_polynomial_p
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_legendre_polynomial_p.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_legendre_polynomial_p
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_legendre_polynomial_p.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_legendre_polynomial_p_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_legendre_polynomial_p.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_legendre_polynomial_p_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_legendre_polynomial_p.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_legendre_polynomial_p_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_i0(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_modified_bessel_i0.out
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_modified_bessel_i0_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_i1(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_modified_bessel_i1.out
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_modified_bessel_i1_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_k0(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_modified_bessel_k0.out
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_modified_bessel_k0_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_k1(Tensor self) -> Tensor
+ python_module: special
+ structured_delegate: special_modified_bessel_k1.out
+ variants: function
+ tags: pointwise
+
+- func: special_modified_bessel_k1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_modified_bessel_k1_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_scaled_modified_bessel_k0(Tensor x) -> Tensor
+ python_module: special
+ structured_delegate: special_scaled_modified_bessel_k0.out
+ variants: function
+ tags: pointwise
+
+- func: special_scaled_modified_bessel_k0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_scaled_modified_bessel_k0_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_scaled_modified_bessel_k1(Tensor x) -> Tensor
+ python_module: special
+ structured_delegate: special_scaled_modified_bessel_k1.out
+ variants: function
+ tags: pointwise
+
+- func: special_scaled_modified_bessel_k1.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_scaled_modified_bessel_k1_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_shifted_chebyshev_polynomial_t.out
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_shifted_chebyshev_polynomial_t_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_t.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_shifted_chebyshev_polynomial_u.out
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_shifted_chebyshev_polynomial_u_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_shifted_chebyshev_polynomial_v.out
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_shifted_chebyshev_polynomial_v_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_v.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor
+ device_check: NoCheck
+ python_module: special
+ structured_delegate: special_shifted_chebyshev_polynomial_w.out
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ device_check: NoCheck
+ dispatch:
+ CPU, CUDA: special_shifted_chebyshev_polynomial_w_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_shifted_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w_out
+ device_check: NoCheck
+ python_module: special
+ variants: function
+ tags: pointwise
+
+- func: special_spherical_bessel_j0(Tensor x) -> Tensor
+ python_module: special
+ structured_delegate: special_spherical_bessel_j0.out
+ variants: function
+ tags: pointwise
+
+- func: special_spherical_bessel_j0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)
+ dispatch:
+ CPU, CUDA: special_spherical_bessel_j0_out
+ python_module: special
+ structured_inherits: TensorIteratorBase
+ structured: True
+ variants: function
+ tags: pointwise
+
+# Aux function used in the test TestPythonDispatch.test_kwarg_only_and_positional_default
+# within test/test_python_dispatch.py
+- func: _foobar(Tensor self, bool arg1=True, bool arg2=True, *, bool arg3=True) -> Tensor
+ dispatch:
+ CPU: foobar
+ autogen: _foobar.out
+
+- func: _fused_adam_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+ variants: function
+ dispatch:
+ CPU: _fused_adam_kernel_cpu_
+ CUDA: _fused_adam_kernel_cuda_
+ MPS: _fused_adam_kernel_mps_
+ autogen: _fused_adam, _fused_adam.out
+
+- func: _fused_adam_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now),
+ # but still skip the device check as the Tensor LR can be on CPU
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CPU: _fused_adam_kernel_cpu_
+ CUDA: _fused_adam_kernel_cuda_
+ MPS: _fused_adam_kernel_mps_
+ autogen: _fused_adam.tensor_lr, _fused_adam.tensor_lr_out
+
+- func: _fused_adamw_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+ variants: function
+ dispatch:
+ CPU: _fused_adamw_kernel_cpu_
+ CUDA: _fused_adamw_kernel_cuda_
+ MPS: _fused_adamw_kernel_mps_
+ autogen: _fused_adamw, _fused_adamw.out
+
+- func: _fused_adamw_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now),
+ # but still skip the device check as the Tensor LR can be on CPU
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CPU: _fused_adamw_kernel_cpu_
+ CUDA: _fused_adamw_kernel_cuda_
+ MPS: _fused_adamw_kernel_mps_
+ autogen: _fused_adamw.tensor_lr, _fused_adamw.tensor_lr_out
+
+- func: _fused_sgd_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+ variants: function
+ dispatch:
+ CPU: _fused_sgd_kernel_cpu_
+ CUDA: _fused_sgd_kernel_cuda_
+ MPS: _fused_sgd_kernel_mps_
+ autogen: _fused_sgd, _fused_sgd.out
+
+- func: _fused_sgd_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now).
+ # but still skip the device check as the Tensor LR can be on CPU
+ device_check: NoCheck
+ variants: function
+ dispatch:
+ CPU: _fused_sgd_kernel_cpu_
+ CUDA: _fused_sgd_kernel_cuda_
+ MPS: _fused_sgd_kernel_mps_
+ autogen: _fused_sgd.tensor_lr, _fused_sgd.tensor_lr_out
+
+- func: _fused_adagrad_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] state_sums, Tensor(d!)[] state_steps, *, float lr, float lr_decay, float weight_decay, float eps, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> ()
+ variants: function
+ dispatch:
+ CPU: _fused_adagrad_kernel_cpu_
+ autogen: _fused_adagrad, _fused_adagrad.out
+
+# This op is ONLY used by pytorch/XLA in functionalization, and should never show up in vanilla eager mode or in any pytorch tracing contexts.
+- func: _propagate_xla_data(Tensor input, Tensor output) -> ()
+ variants: function
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/native/tags.yaml b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/native/tags.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..c2aa5ba4cd20bc9f8e6e4b9434a220ca55ef0b86
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/native/tags.yaml
@@ -0,0 +1,80 @@
+# This yaml file contains all the possible tags that can be defined in `tags` in `native_functions.yaml`
+
+- tag: inplace_view
+ desc: |
+ This tag indicates if an operator *only* modifies the tensor metadata
+- tag: pt2_compliant_tag
+ desc: |
+ This tag indicates if the operator is guaranteed to
+ work with the PT2 compilation APIs (torch.compile,
+ torch.export, etc). If you add this tag to an
+ operator, please use
+ `torch.testing._internal.optest.opcheck` to test that
+ the operator has been registered correctly and
+ works with torch.compile
+- tag: view_copy
+ desc: |
+ This tag indicates operators that are *_copy* variants
+ of view/aliasing operators. If an operator has a view_copy tag,
+ then it should have the name {op}_copy, where {op} is a view operator.
+- tag: dynamic_output_shape
+ desc: |
+ This tag indicates if an operator's output's shape depends on input Tensor
+ data.
+- tag: data_dependent_output
+ desc: |
+ Operator has a non-Tensor output whose value is dependent on the data
+ of Tensor inputs. Among other things, this implies that this operator
+ cannot be run with meta tensor (since data is not available), nor
+ can it be symbolically traced.
+- tag: generated
+ desc: |
+ This tag indicates that the operator doesn't have an explicit entry in
+ native_functions.yaml, and instead was generated automatically by the codegen.
+- tag: nondeterministic_seeded
+ desc: |
+ This tag indicates if an operator is nondeterministically seeded
+ (i.e., is random) such that the operator intentionally produces
+ different results when run twice on the same inputs, but this randomness
+ is controlled by a Generator which, if reseeded would give you the
+ same result.
+- tag: nondeterministic_bitwise
+ desc: |
+ This tag indicates if an operator doesn't guarantee bitwise equivalence
+ across different runs of an operator with identical inputs.
+- tag: needs_fixed_stride_order
+ desc: |
+ This tag indicates that the operator should be passed Tensors following
+ the same stride permutation as observed in eager when compiled in inductor.
+ Only one of {needs_fixed_stride_order, flexible_layout} can apply; if
+ multiple are assigned then we assume the most restrictive one.
+- tag: flexible_layout
+ desc: |
+ This tag indicates that the custom operator can accept inputs with varying
+ strides/storage_offset and that when compiled, Inductor is allowed to change
+ the strides/storage_offset of inputs to the custom operator.
+ Only one of {needs_fixed_stride_order, flexible_layout} can apply; if
+ multiple are assigned then we assume the most restrictive one.
+
+# NOTE [Core ATen Ops]
+- tag: core
+ desc: |
+ Core aten ops is a subset of aten ops that remains after aten-to-aten decomposition and
+ functionalization pass. Core aten ops are fully functional and adhere to single static
+ assignment (SSA): this implies there will be no `inplace` or `_out` variants in this opset.
+ This opset is designed to serve as the functional IR to interface with compiler backends.
+ In contrast to primTorch, core aten opset doesn't decompose ops into explicit
+ type promotion and broadcasting ops.
+ Core aten ops is also effectively the opset produced by torchdynamo.export(aten_graph=True),
+ and thus can be used as an opset for export purpose.
+- tag: pointwise
+ desc: |
+ Pointwise operators are operators where each element of the output is computed only by accessing
+ the corresponding element of all the broadcasted inputs. The output shape will be the broadcasted
+ shape of the inputs.
+- tag: maybe_aliasing_or_mutating
+ desc: |
+ For some ops, we can't statically determine whether the op is functional or not. Note that this is only
+ relevant to CIA ops that decompose before functionalization/autograd. It is useful to
+ know this information for export as we would want to decompose these ops as they are unsafe to be
+ preserved.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1e2cdef2ba05d346a852d1873251df006a5a6bba
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp
@@ -0,0 +1,36 @@
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+// ${generated_comment}
+
+namespace at {
+
+namespace {
+struct OpNameEquals final {
+ bool operator()(const std::pair& lhs, const std::pair& rhs) const {
+ return 0 == strcmp(lhs.first, rhs.first) && 0 == strcmp(lhs.second, rhs.second);
+ }
+};
+
+struct OpNameHash final {
+ size_t operator()(const std::pair& p) const {
+ // use std::hash because std::hash would hash pointers and not pointed-to strings
+ return std::hash()(p.first) ^ (~ std::hash()(p.second));
+ }
+};
+}
+
+bool is_custom_op(const c10::OperatorName& opName) {
+ static std::unordered_set, OpNameHash, OpNameEquals> ops {
+ ${aten_ops}
+ {"", ""}
+ };
+ return ops.count(std::make_pair(
+ opName.name.c_str(), opName.overload_name.c_str())) == 0;
+}
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a950b6356078215e04328e3d1eca6df19d0060a4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp
@@ -0,0 +1,73 @@
+#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+// ${generated_comment}
+
+#include
+#include
+#include
+
+#ifndef AT_PER_OPERATOR_HEADERS
+#include
+#else
+#include
+$ops_headers
+#endif
+
+namespace at {
+namespace native {
+
+// This file contains a number of kernels for aten functions that are fully code-generated.
+// TODO: rename this file to something more generic.
+
+namespace {
+at::Tensor clone_arg(const at::Tensor& t) {
+ return t.clone();
+}
+
+std::vector clone_arg(const at::TensorList& t_list) {
+ std::vector out(t_list.size());
+ for (const auto& i : c10::irange(t_list.size())) {
+ out[i] = t_list[i].clone();
+ }
+ return out;
+}
+
+// duped with gen_resize_out_helper from structured kernels
+void copy_arg(const at::Tensor& dst, const at::Tensor& src) {
+ TORCH_CHECK(src.dtype() == dst.dtype(),
+ "Expected out tensor to have dtype ", src.dtype(), ", but got ", dst.dtype(), " instead");
+ TORCH_CHECK(src.device() == dst.device(),
+ "Expected out tensor to have device ", src.device(), ", but got ", dst.device(), " instead");
+ dst.copy_(src);
+}
+
+void copy_arg(const at::TensorList& dst, const at::TensorList& src) {
+ TORCH_INTERNAL_ASSERT(dst.size() == src.size());
+ for (const auto& i : c10::irange(dst.size())) {
+ copy_arg(dst[i], src[i]);
+ }
+}
+
+// TODO: this doesn't handle restriding empty tensors correctly; see
+// gen_resize_out_helper for the correct algorithm
+
+void resize_out_helper(const at::Tensor& dst, const at::Tensor& src) {
+ at::native::resize_output(dst, src.sizes());
+}
+
+void resize_out_helper(const at::TensorList& dst, const at::TensorList& src) {
+ TORCH_INTERNAL_ASSERT(dst.size() == src.size());
+ for (const auto& i : c10::irange(dst.size())) {
+ at::native::resize_output(dst[i], src[i].sizes());
+ }
+}
+}
+
+
+${CompositeViewCopyKernel_Definitions}
+
+${GeneratedCompositeFunctional_Definitions}
+
+${GeneratedCompositeOut_Definitions}
+
+} // namespace native
+} // namespace at
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..4bd999183177c647735f6db51ae19619113b2df2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h
@@ -0,0 +1,23 @@
+#pragma once
+// ${generated_comment}
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include
+#include
+#include
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include
+
+namespace at {
+
+namespace ${dispatch_namespace} {
+
+${dispatch_namespaced_declarations}
+
+} // namespace ${dispatch_namespace}
+} // namespace at
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..4532acdf7f790e4dd520bfe4879c693e52f958d4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h
@@ -0,0 +1,29 @@
+#include
+
+// TODO Undo all logic introduced for Note [Avoiding Include Cycles In Static Dispatch]
+// Code introduced to avoid cyclic dependency in static dispatch is no longer
+// needed as static dispatch logic is moved from TensorBody.h, which caused cycles in the first place,
+// to Operators.cpp for supporting multiple backends with multiple kernels.
+//
+// Note [Avoiding Include Cycles In Static Dispatch]
+// In order to avoid #include cycles in the static dispatch build, we've carefully split out
+// the static function definition files into {DispatchKey}Functions.h and {DispatchKey}Functions_inl.h.
+//
+// Without this split, the include cycle looks like TensorBody.h -> CPUFunctions.h -> TensorBody.h.
+// - TensorBody.h #includes CPUFunctions.h in the static dispatch build, because the tensor methods
+// all need to call into the fastpath C++ API defined in CPUFunctions.h. The methods are also all
+// directly inlined into TensorBody.h.
+// - CPUFunctions.h #includes TensorBody.h because it contains function declarations for the entire C++ API,
+// which include functions that have defaultable std::optional arguments.
+// That requires knowing the full Tensor class definition.
+//
+// We break the cycle by doing the following:
+// - Split out CPUFunction.h into two files: CPUFunctions.h and CPUFunctions_inl.h
+// - CPUFunction.h is a dummy file that just includes the Tensor class and includes CPUFunctions_inl.,
+// - CPUFunctions_inl.h includes everything else
+// - (only in the static dispatch build) TensorBody.h makes sure to finish defining the Tensor class,
+// and then it includes CPUFunctions_inl.h.
+// - All other files that want the cpu fastpath functions can include CPUFunctions.h directly.
+// - This also means that static dispatch build, CPUFunctions.h only needs to
+// #include TensorBody.h, and it will automatically bring in CPUFunctions_inl.h.
+${inline_headers}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h
new file mode 100644
index 0000000000000000000000000000000000000000..7e9fe55a26ba9915b231d541880e3e8c9dd2bcec
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h
@@ -0,0 +1,22 @@
+#pragma once
+// ${generated_comment}
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include
+#include
+#include
+
+#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on all pytorch operators, meaning the \
+ file will need to be re-compiled every time an operator is changed or added. \
+ Consider including a specific operator from \
+ . \
+ See NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
+#endif
+
+${DispatchKeyFunctions_inl_includes}
+
+
+${dispatch_namespaced_declarations}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..604a7bcb6275616ebe98756378f7feaffe4a6856
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp
@@ -0,0 +1,13 @@
+// ${generated_comment}
+${includes}
+${native_functions_include}
+
+namespace {
+${helper_fns}
+} // namespace
+
+${namespace_prologue}
+
+${native_function_definitions}
+
+${namespace_epilogue}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h
new file mode 100644
index 0000000000000000000000000000000000000000..e616b4d7ef360ab4e2223a55a11fe5d423efc8c2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// an external backend might generate file within its code tree
+// and check all the source files within the tree with clang-format.
+// so, disable it since the backend might have a different config.
+// clang-format off
+
+// ${generated_comment}
+
+#include
+
+${namespace_prologue}
+
+struct ${class_name} {
+
+${dispatch_declarations}
+
+};
+${namespace_epilogue}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Function.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Function.h
new file mode 100644
index 0000000000000000000000000000000000000000..1cde26cfdae4d48769e0986d7390900dd4aa3556
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Function.h
@@ -0,0 +1,26 @@
+#pragma once
+
+// ${generated_comment}
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+${static_dispatch_ops_headers}
+
+${operator_includes}
+
+namespace at {
+
+${function_definitions}
+
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h
new file mode 100644
index 0000000000000000000000000000000000000000..2a817670b7cd6dd80404fc6a512c51e3ed8b8352
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h
@@ -0,0 +1,33 @@
+#pragma once
+
+// ${generated_comment}
+
+#include
+
+namespace at {
+namespace functionalization {
+
+enum class InverseReturnMode {
+ /// Specifies that functional inverses should always return a view.
+ AlwaysView,
+ /// Specifies that functional inverses should always return a non-view / copy.
+ NeverView,
+ /// Specifies that functional inverses should return a view unless a (copying) scatter
+ /// inverse exists, in which case that will be used instead.
+ /// This avoids as_strided() calls that can be difficult for subclasses to handle.
+ ViewOrScatterInverse,
+};
+
+struct FunctionalInverses {
+
+${view_inverse_declarations}
+
+// NB: These are not generated! They're manually implemented in the template.
+// TODO: Change codegen to generate these. See the following link:
+// https://github.com/pytorch/pytorch/blob/main/torchgen/model.py#L2583-L2585
+static at::Tensor chunk_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int chunks, int dim);
+static at::Tensor narrow_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int dim, c10::SymInt start, c10::SymInt length);
+
+};
+}
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Functions.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Functions.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..01ca697f71e06829d735d17e18f325c974abc394
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Functions.cpp
@@ -0,0 +1,103 @@
+#include
+
+#include
+#include
+#include
+
+namespace at {
+
+Tensor TensorMaker::make_tensor() {
+ AutoDispatchBelowADInplaceOrView guard{}; // TODO: Remove.
+ tracer::impl::NoTracerDispatchMode tracer_guard{};
+
+ check_size_nonnegative(sizes_);
+
+ TORCH_CHECK_VALUE(
+ !deleter_ || !ctx_,
+ "The deleter and context arguments are mutually exclusive.");
+
+ if (device_ == std::nullopt) {
+ device_ = globalContext().getDeviceFromPtr(data_, opts_.device().type());
+ }
+
+ if (opts_.device().has_index()) {
+ // clang-format off
+ TORCH_CHECK_VALUE(
+ opts_.device() == *device_,
+ "Specified device ", opts_.device(), " does not match device of data ", *device_);
+ // clang-format on
+ }
+
+ std::size_t size_bytes = computeStorageSize();
+
+ DataPtr data_ptr{};
+ if (deleter_) {
+ data_ptr = makeDataPtrFromDeleter();
+ } else {
+ data_ptr = makeDataPtrFromContext();
+ }
+
+ TORCH_CHECK(!resizeable_ || allocator_ != nullptr, "Must specify an allocator with allocator() if you want to use resizeable_storage()");
+ Storage storage{Storage::use_byte_size_t{}, size_bytes, std::move(data_ptr), /*allocator=*/allocator_, /*resizable=*/resizeable_};
+
+ Tensor tensor = detail::make_tensor(
+ std::move(storage), opts_.computeDispatchKey(), opts_.dtype());
+
+ TensorImpl* tensor_impl = tensor.unsafeGetTensorImpl();
+ if (strides_) {
+ tensor_impl->set_sizes_and_strides(sizes_, *strides_);
+ } else {
+ tensor_impl->set_sizes_contiguous(sizes_);
+ }
+ if (storage_offset_) {
+ tensor_impl->set_storage_offset(*storage_offset_);
+ }
+
+ return tensor;
+ }
+
+ std::size_t TensorMaker::computeStorageSize() const noexcept {
+ std::size_t itemsize = opts_.dtype().itemsize();
+
+ if (strides_) {
+ auto storage_size = detail::computeStorageNbytes(sizes_, *strides_, itemsize);
+ if (storage_offset_) {
+ storage_size += storage_offset_.value();
+ }
+ return storage_size;
+ }
+
+ std::size_t size = 1;
+ for (std::int64_t s : sizes_) {
+ size *= static_cast(s);
+ }
+ auto storage_size = size * itemsize;
+ if (storage_offset_) {
+ storage_size += storage_offset_.value();
+ }
+ return storage_size;
+ }
+
+ inline DataPtr TensorMaker::makeDataPtrFromDeleter() noexcept {
+ return InefficientStdFunctionContext::makeDataPtr(data_, std::move(deleter_), *device_);
+ }
+
+ inline DataPtr TensorMaker::makeDataPtrFromContext() noexcept {
+ return DataPtr{data_, ctx_.release(), ctx_.get_deleter(), *device_};
+ }
+
+ IntArrayRef TensorMaker::makeTempSizes() const noexcept {
+ static std::int64_t zeros[5] = {0, 0, 0, 0, 0};
+ if (opts_.has_memory_format()) {
+ MemoryFormat format = *opts_.memory_format_opt();
+ if (format == MemoryFormat::ChannelsLast) {
+ return IntArrayRef(zeros, 4);
+ }
+ if (format == MemoryFormat::ChannelsLast3d) {
+ return IntArrayRef(zeros, 5);
+ }
+ }
+ return IntArrayRef(zeros, 1);
+ }
+
+} // namespace at
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Functions.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Functions.h
new file mode 100644
index 0000000000000000000000000000000000000000..55fa67c5bddb2f4abc730396c3affe4d75479753
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/Functions.h
@@ -0,0 +1,143 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml, \
+ meaning the file will need to be re-compiled every time an operator \
+ is changed or added. Consider if your change would be better placed in \
+ another file, or if a more specific header might achieve the same goal. \
+ See NOTE: [Tensor vs. TensorBase]
+#endif
+
+#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
+#error This change adds a dependency on all pytorch operators, meaning the \
+ file will need to be re-compiled every time an operator is changed or added. \
+ Consider including a specific operator from and \
+ see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
+#endif
+
+// NOTE: [TORCH_ASSERT_ONLY_METHOD_OPERATORS]
+//
+// In ATen, certain generated headers files include the definitions of
+// every single operator in PyTorch. Unfortunately this means every
+// time an operator signature is updated or changed in
+// native_functions.yaml, you (and every other PyTorch developer) need
+// to recompile every source file that includes any of these headers.
+//
+// To break up these header dependencies, and improve incremental
+// build times for all PyTorch developers. These headers are split
+// into per-operator headers in the `ATen/ops` folder. This limits
+// incremental builds to only changes to methods of `Tensor`, or files
+// that use the specific operator being changed. With `at::sum` as an
+// example, you should include
+//
+// // instead of ATen/Functions.h
+// // instead of ATen/NativeFunctions.h
+// // instead of ATen/Operators.h
+// // instead of ATen/CPUFunctions.h
+//
+// However, even if you're careful to use this in your own code.
+// `Functions.h` might be included indirectly through another header
+// without you realising. To avoid this, you can add
+//
+// #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
+//
+// to the top of your source file. This way any time the non-specific
+// headers are included, the compiler will error out.
+//
+// Also, be aware that `ops` are not available in all build
+// configurations (namely fb-internal) so you must guard these
+// includes with `#ifdef AT_PER_OPERATOR_HEADERS`. e.g.
+//
+// #ifndef AT_PER_OPERATOR_HEADERS
+// #include
+// #else
+// #include
+// #endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+${Functions_includes}
+
+namespace at {
+
+${Functions_declarations}
+
+// Special C++ only overloads for std()-like functions (See gh-40287)
+// These are needed because int -> bool conversion takes precedence over int -> IntArrayRef
+// So, for example std(0) would select the std(unbiased=False) overload
+TORCH_API inline Tensor var(const Tensor& self, int dim) {
+ return at::var(self, IntArrayRef{dim});
+}
+TORCH_API inline std::tuple var_mean(const Tensor& self, int dim) {
+ return at::var_mean(self, IntArrayRef{dim});
+}
+TORCH_API inline Tensor std(const Tensor& self, int dim) {
+ return at::std(self, IntArrayRef{dim});
+}
+TORCH_API inline std::tuple std_mean(const Tensor& self, int dim) {
+ return at::std_mean(self, IntArrayRef{dim});
+}
+
+inline int64_t numel(const Tensor& tensor) {
+ return tensor.numel();
+}
+
+inline int64_t size(const Tensor& tensor, int64_t dim) {
+ return tensor.size(dim);
+}
+
+inline int64_t stride(const Tensor& tensor, int64_t dim) {
+ return tensor.stride(dim);
+}
+
+inline bool is_complex(const Tensor& tensor) {
+ return tensor.is_complex();
+}
+
+inline bool is_floating_point(const Tensor& tensor) {
+ return tensor.is_floating_point();
+}
+
+inline bool is_signed(const Tensor& tensor) {
+ return tensor.is_signed();
+}
+
+inline bool is_inference(const Tensor& tensor) {
+ return tensor.is_inference();
+}
+
+inline bool _is_zerotensor(const Tensor& tensor) {
+ return tensor._is_zerotensor();
+}
+
+inline bool is_conj(const Tensor& tensor) {
+ return tensor.is_conj();
+}
+
+inline Tensor conj(const Tensor& tensor) {
+ return tensor.conj();
+}
+
+inline bool is_neg(const Tensor& tensor) {
+ return tensor.is_neg();
+}
+
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/LazyIr.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/LazyIr.h
new file mode 100644
index 0000000000000000000000000000000000000000..6f3867cbd91d2f6331908372de5f1434107f664d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/LazyIr.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// This file contains autogenerated LazyTensor IR nodes
+${lazy_ir_sysinc}
+${lazy_ir_inc}
+
+${namespace_prologue}
+using at::operator<<;
+
+// kNullValue is used to contribute a static hash value any time
+// a node has an Optional input that is nullopt. It is important
+// to differentiate between HASH(std::nullopt, something) and HASH(something, std::nullopt),
+// and using kNullValue in the hash function in the order of arguments
+// serves this purpose.
+static const torch::lazy::Value kNullValue = torch::lazy::Value();
+
+${ir_declarations}
+
+${namespace_epilogue}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h
new file mode 100644
index 0000000000000000000000000000000000000000..df0f621c9620d3075a23a1af2da621d79cdb712f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h
@@ -0,0 +1,11 @@
+#pragma once
+
+${lazy_non_native_ir_inc}
+
+// This file contains autogenerated LazyTensor Non Native IR nodes
+
+${namespace_prologue}
+
+${non_native_ir_nodes}
+
+${namespace_epilogue}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h
new file mode 100644
index 0000000000000000000000000000000000000000..b6fe7ba41de0850908d3de589363a58cd97cf0ce
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h
@@ -0,0 +1,24 @@
+#pragma once
+
+// ${generated_comment}
+
+#ifdef TORCH_ASSERT_NO_OPERATORS
+#error This change adds a dependency on native_functions.yaml, \
+ meaning the file will need to be re-compiled every time an operator \
+ is changed or added. Consider if your change would be better placed in \
+ another file, or if a more specific header might achieve the same goal. \
+ See NOTE: [Tensor vs. TensorBase]
+#endif
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include
+
+${MethodOperators_includes}
+
+namespace at {
+namespace _ops {
+${MethodOperators_declarations}
+} // namespace _ops
+} // namespace at
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h
new file mode 100644
index 0000000000000000000000000000000000000000..323849f0dbc73d1340594ffcc5ba692975290a76
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h
@@ -0,0 +1,17 @@
+#pragma once
+
+// ${generated_comment}
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include