response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Check that we don't choke on non-contigous tensors | def test_no_contiguous(dtype):
"""Check that we don't choke on non-contigous tensors"""
shape = (8, 384, 128)
# Get the same inputs
torch.random.manual_seed(0)
torch.cuda.manual_seed(0)
X = torch.normal(0, 1, size=shape, device="cuda", requires_grad=True, dtype=dtype)
X = X.transpose(2, 1)... |
Check that PyTorch and Triton softmax give the same result | def test_softmax_parity(shape, amp, log, masking, causal, contiguous):
"""Check that PyTorch and Triton softmax give the same result"""
torch.random.manual_seed(0)
# Check the result of a FW pass
X = torch.normal(0, 1, size=shape, device="cuda", requires_grad=False)
if not contiguous:
# Ma... |
Check that the fallback paths are correct | def test_softmax_parity_fallback(log, masking, causal, contiguous, device):
"""Check that the fallback paths are correct"""
torch.random.manual_seed(0)
shape = (16, 16)
# Check the result of a FW pass
X = torch.normal(0, 1, size=shape, device=device, requires_grad=False)
if not contiguous:
... |
Create block tables and pages K/V cache for testing paged attention.
Args:
cache_k, cache_v: K/V caches, each of shape [B, MAX_T, H_kv, D].
Note that these tensors are unexpanded,
i.e. for multiquery case cache_k.shape[2] = 1
kv_seqlens: list of K/V sequence lengths
BLOCK_N: number of tokens... | def pack_kv_cache(
cache_k: torch.Tensor,
cache_v: torch.Tensor,
kv_seqlens: List[int],
BLOCK_N: int,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Create block tables and pages K/V cache for testing paged attention.
Args:
cache_k, cache_v: K/V caches, each of shape [B, M... |
Benchmark the runtime of the provided function.
Args:
fn: Function to benchmark
rep: Repetition time (in ms)
grad_to_none: Reset the gradient of the provided tensor to None
Returns:
Benchmarked runtime in ms | def do_bench_cudagraph(
fn: Callable, rep: int = 20, grad_to_none: Optional[List[torch.Tensor]] = None
) -> float:
"""
Benchmark the runtime of the provided function.
Args:
fn: Function to benchmark
rep: Repetition time (in ms)
grad_to_none: Reset the gradient of the provided ten... |
Generates lists of lengths of query blocks and corresponding key blocks.
The total number of queries will be bs * q_len and the
total number of keys will be bs * kv_len.
max_q_minus_k: maximum allowed num_queries - num_keys.
For "bottom-right" masks it's 0, we need to have more keys than
queries, otherwise some... | def _rand_seqlens(
r: random.Random,
bs: int,
q_len: int,
kv_len: int,
max_q_minus_k: Optional[int],
) -> Tuple[Sequence[int], Sequence[int]]:
"""
Generates lists of lengths of query blocks and corresponding key blocks.
The total number of queries will be bs * q_len and the
total num... |
Returns the list of operators used inside `function` with
*args and **kwargs | def list_operators(function, *args, **kwargs):
"""
Returns the list of operators used inside `function` with
*args and **kwargs
"""
verbose_mode = VerboseTorchDispatchMode()
with verbose_mode:
function(*args, **kwargs)
return verbose_mode.operators |
An activation checkpoint context_fn for selectively deciding what to
store and what to recompute. Accepts a custom policy.
Args:
policy_fn(Union[List[Op], callable]): policy for deciding what to
store (instead of recompute). If it's a function, it should
be of form (func, *args, **kwargs) -> bool wh... | def selective_checkpoint_context_fn(policy_fn=None):
"""An activation checkpoint context_fn for selectively deciding what to
store and what to recompute. Accepts a custom policy.
Args:
policy_fn(Union[List[Op], callable]): policy for deciding what to
store (instead of recompute). If it's... |
Wrapper around torch.utils.checkpoint that accepts a custom policy
function for selectively deciding what to store and what to recompute
Args:
function: describes what to run in the forward pass of the model or
part of the model. It should also know how to handle the inputs
passed as the tuple. For ... | def checkpoint(
function, *args, preserve_rng_state=True, policy_fn=None, **kwargs
) -> Any:
"""Wrapper around torch.utils.checkpoint that accepts a custom policy
function for selectively deciding what to store and what to recompute
Args:
function: describes what to run in the forward pass of th... |
Use ProfileOperatorsTorchDispatchMode to get runtime and memory info.
Args:
function: The function to optimize which will be selectively checkpointed. Usually the forward pass
of the model.
*args: Arguments to pass in to the given ``function``.
Returns:
A list of tuples, where each tuples contains... | def _analyze_operators(function, *args) -> List[ProfileMetadata]:
"""
Use ProfileOperatorsTorchDispatchMode to get runtime and memory info.
Args:
function: The function to optimize which will be selectively checkpointed. Usually the forward pass
of the model.
*args: Arguments to... |
Given a function, its arguments, and the maximum amount of memory available,
find the subset of operators that can be optimized to reduce runtime while still fitting within the memory budget.
Args:
function: The function to optimize which will be selectively checkpointed. Usually the forward pass
of the mo... | def get_optimal_checkpoint_policy(function, *args, memory_budget: float) -> Callable:
"""
Given a function, its arguments, and the maximum amount of memory available,
find the subset of operators that can be optimized to reduce runtime while still fitting within the memory budget.
Args:
functio... |
Given a list of operator names, their corresponding runtimes, and the maximum amount of memory available,
find the subset of operators that can be optimized to reduce runtime while still fitting within the memory budget.
Uses https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.milp.html
Args:
memor... | def _optimize_runtime_with_given_memory(
memory: torch.Tensor,
runtimes: torch.Tensor,
max_memory: float,
view_like_ops: List[int],
inplace_ops: List[Tuple[int, ...]],
random_ops: List[int],
force_store_random: bool,
) -> torch.Tensor:
"""
Given a list of operator names, their corres... |
Wrap a module with selective activation checkpointing.
It behaves similarly to PyTorch's checkpoint_wrapper, but gives the possibility
to the user to either specify a handcrafted policy_fn, or to let an optimization
algorithm to select the policy given a user-specified memory_budget.
The user should either specify th... | def selective_checkpoint_wrapper(
module: torch.nn.Module,
memory_budget: Optional[float] = None,
policy_fn: Optional[Callable] = None,
):
"""
Wrap a module with selective activation checkpointing.
It behaves similarly to PyTorch's checkpoint_wrapper, but gives the possibility
to the user t... |
Given a superset of the inputs and a reference config class,
return exactly the needed config | def generate_matching_config(superset: Dict[str, Any], config_class: Any) -> Any:
"""Given a superset of the inputs and a reference config class,
return exactly the needed config"""
# Extract the required fields
field_names = list(map(lambda x: x.name, fields(config_class)))
subset = {k: v for k, v... |
Printout the contents of a dict as a human-readable and Markdown compatible array | def pretty_print(results, title, units) -> None:
"""Printout the contents of a dict as a human-readable and Markdown compatible array"""
print(title)
header = " Units: {:<45}".format(units)
print("| " + header + "|" + "".join("{0:<20}|".format(k) for k in results.keys()))
offset = len(header)
p... |
Graph out the contents of a dict.
Dash key means that if the result label has this key, then it will be displayed with a dash | def pretty_plot(
results, title, units: str, filename=None, dash_key="", legend_loc="lower right"
):
"""Graph out the contents of a dict.
Dash key means that if the result label has this key, then it will be displayed with a dash
"""
if not filename:
filename = title + ".png"
# Sanitiz... |
Graph out the contents of a dict.
Dash key means that if the result label has this key, then it will be displayed with a dash | def pretty_barplot(results, title, units: str, filename=None, dash_key=""):
"""Graph out the contents of a dict.
Dash key means that if the result label has this key, then it will be displayed with a dash
"""
if not filename:
filename = title + ".png"
# Sanitize the filename
filename =... |
Remove a file like rm -f. | def rmf(filename: str) -> None:
"""Remove a file like rm -f."""
try:
os.remove(filename)
except FileNotFoundError:
pass |
A context to get tempfiles and ensure they are cleaned up. | def temp_files_ctx(num: int) -> Generator:
"""A context to get tempfiles and ensure they are cleaned up."""
files = [tempfile.mkstemp()[1] for _ in range(num)]
yield tuple(files)
# temp files could have been removed, so we use rmf.
for name in files:
rmf(name) |
Returns a `benchmark.Compare` object, except that if we have runs
with different algorithms, we also add the algorithm name
in the column titles | def _finalize_results(results: List[Tuple[Dict[str, Any], Any]]) -> List[Any]:
"""
Returns a `benchmark.Compare` object, except that if we have runs
with different algorithms, we also add the algorithm name
in the column titles
"""
all_algorithms: Set[str] = set()
all_description: Set[str] =... |
Create CLI argument parser. | def create_argparser() -> argparse.ArgumentParser:
"""
Create CLI argument parser.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--fn", default=None, type=str, help="Only benchmark this function"
)
parser.add_argument(
"--label", default=None, type=str, help="S... |
Helper function to run benchmarks.
Supports loading previous results for comparison, and saving current results to file. | def benchmark_main_helper(
benchmark_fn, cases: List[Dict[str, Any]], arg_parser=None, **kwargs
) -> None:
"""
Helper function to run benchmarks.
Supports loading previous results for comparison, and saving current results to file.
"""
arg_parser = arg_parser or create_argparser()
args = arg... |
Yield all combinations of parameters in the grid (as a dict) | def grid_parameters(grid: Dict):
"""
Yield all combinations of parameters in the grid (as a dict)
"""
grid_copy = dict(grid)
# Turn single value in an Iterable
for k in grid_copy:
if not isinstance(grid_copy[k], Iterable):
grid_copy[k] = [grid_copy[k]]
for p in itertoo... |
See DeepNet_.
Returns alpha and beta depending on the number of encoder and decoder layers,
first tuple is for the encoder and second for the decoder
.. _DeepNet: https://arxiv.org/pdf/2203.00555v1.pdf | def get_deepnorm_coefficients(
encoder_layers: int, decoder_layers: int
) -> Tuple[Optional[DeepNormCoefficients], Optional[DeepNormCoefficients]]:
"""
See DeepNet_.
Returns alpha and beta depending on the number of encoder and decoder layers,
first tuple is for the encoder and second for the decod... |
Builds a multihead attention from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_attention",
"foo": "bar"}` will find a class that was registered as "my_attention"
(see :func:`register_attention`) and call .from_con... | def build_multi_head_attention(
multi_head_config: Union[MultiHeadDispatchConfig, Dict[str, Any]],
):
"""Builds a multihead attention from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_attention",
... |
Returns a 2d pattern that samples 1 every k elements in the attention mask.
Can be seen as a form of downsampling, where every pixel attends to a downsampled
version of the input. | def dilated_2d_pattern(H, W, k=2):
"""
Returns a 2d pattern that samples 1 every k elements in the attention mask.
Can be seen as a form of downsampling, where every pixel attends to a downsampled
version of the input.
"""
d_h = local_nd_distance(H, W, p=1, weights=(1, 0))
d_w = local_nd_dis... |
Block sparsify a tensor, given a mask and block size | def block_sparsify_tensor(x, mask, block_size):
"""
Block sparsify a tensor, given a mask and block size
"""
ret = torch.empty(
(x.size(0), mask.sum(), block_size, block_size), dtype=x.dtype, device=x.device
)
for idx, (h, i, j) in enumerate(zip(*mask.nonzero(as_tuple=True))):
r... |
Given a mask pattern and blocksize, return the corresponding layout
which makes sure that all the positives in the mask are covered | def pattern_to_layout(mask: torch.Tensor, block_size: int) -> torch.Tensor:
r"""
Given a mask pattern and blocksize, return the corresponding layout
which makes sure that all the positives in the mask are covered
"""
assert mask.ndim >= 2, "We're expecting [Heads, Seq, Seq] or [Seq, Seq]"
_shoul... |
Use the additive bias computation from ALiBi_ to generate a mask.
Note that this mask can in turn be used to generate a blocksparse attention computation layout
.. note: mask_shape is expected to hold the [heads, seq, seq] dimensions
.. _ALiBi: https://arxiv.org/pdf/2108.12409.pdf | def alibi_pattern(threshold: float, mask_shape: torch.Size) -> torch.Tensor:
r"""
Use the additive bias computation from ALiBi_ to generate a mask.
Note that this mask can in turn be used to generate a blocksparse attention computation layout
.. note: mask_shape is expected to hold the [heads, seq, seq... |
create a pattern of shape [heads, seq, seq] out of a blocksparse
layout of shape [heads, seq/block_size, seq/block_size] | def layout_to_pattern(layout: torch.Tensor, block_size: int):
r"""
create a pattern of shape [heads, seq, seq] out of a blocksparse
layout of shape [heads, seq/block_size, seq/block_size]
"""
return torch.kron(layout, torch.ones(block_size, block_size)) |
Computing the Moore-Penrose inverse.
Use an iterative method from (Razavi et al. 2014) to approximate the Moore-Penrose inverse via efficient
matrix-matrix multiplications. | def iterative_pinv(softmax_mat: torch.Tensor, n_iter=6, pinverse_original_init=False):
"""
Computing the Moore-Penrose inverse.
Use an iterative method from (Razavi et al. 2014) to approximate the Moore-Penrose inverse via efficient
matrix-matrix multiplications.
"""
i = torch.eye(
soft... |
Builds an attention from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_attention",
"foo": "bar"}` will find a class that was registered as "my_attention"
(see :func:`register_attention`) and call .from_config on it... | def build_attention(config: Union[Dict[str, Any], AttentionConfig]):
"""Builds an attention from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_attention",
"foo": "bar"}` will find a class that was r... |
Builds a feedforward from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_feedforward",
"foo": "bar"}` will find a class that was registered as "my_feedforward"
(see :func:`register_feedforward`) and call .from_confi... | def build_feedforward(config: Union[Dict[str, Any], FeedforwardConfig]):
"""Builds a feedforward from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_feedforward",
"foo": "bar"}` will find a class tha... |
Builds a position encoding from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_position_encoding",
"foo": "bar"}` will find a class that was registered as "my_position_encoding"
(see :func:`register_positional_embed... | def build_positional_embedding(config: Union[Dict[str, Any], PositionEmbeddingConfig]):
"""Builds a position encoding from a config.
This assumes a 'name' key in the config which is used to determine what
attention class to instantiate. For instance, a config `{"name": "my_position_encoding",
"foo": "b... |
Handle all the supported residual path configurations.
..Note: we return the appropriate constructor, not an actual layer | def _get_ln_factory(
d_model: int,
residual_norm_style: Optional[ResidualNormStyle],
use_triton: bool,
residual: bool,
normalization: NormalizationType = NormalizationType.LayerNorm,
residual_scale: float = 1.0,
):
"""
Handle all the supported residual path configurations.
..Note: w... |
Best effort - OmegaConf supports limited typing, so we may fail to import
certain config classes. For example, pytorch typing are not supported. | def import_xformer_config_schema():
"""
Best effort - OmegaConf supports limited typing, so we may fail to import
certain config classes. For example, pytorch typing are not supported.
"""
cs = ConfigStore.instance()
for k, v in {
"ff": FEEDFORWARD_REGISTRY,
"pe": POSITION_EMBED... |
Provide the xFormers factory with weight init routines.
Supported initializations are:
- Small: follow the method outlined in `Transformer Without Tears`_
- ViT: follow the initialization in the reference ViT_ codebase
- Timm: follow the initialization in the reference Timm_ codebase
- Moco: follow the initialization ... | def get_weight_init_fn(init_choice: xFormerWeightInit):
"""
Provide the xFormers factory with weight init routines.
Supported initializations are:
- Small: follow the method outlined in `Transformer Without Tears`_
- ViT: follow the initialization in the reference ViT_ codebase
- Timm: follow t... |
Fills the input `Tensor` with values according to the method
described in `Transformer Without Tears`_, using a uniform distribution.
This is a variation of the Xavier init. The resulting tensor will have values sampled from
:math:`\mathcal{U}(-a, a)` where
.. math::
a = \text{gain} \times \sqrt{\frac{6}{\text{fa... | def _small_init_(tensor: torch.Tensor, gain: float = 1.0) -> torch.Tensor:
r"""Fills the input `Tensor` with values according to the method
described in `Transformer Without Tears`_, using a uniform distribution.
This is a variation of the Xavier init. The resulting tensor will have values sampled from
... |
ViT weight initialization, matching JAX (Flax) impl | def _init_weights_vit_jax(
module: nn.Module,
name: str = "",
head_bias: float = 0.0,
gain: float = 1.0,
deepnorm_style: bool = False,
**kwargs,
):
"""ViT weight initialization, matching JAX (Flax) impl"""
if is_ffn(name):
_maybe_init_tensor(module, "bias", nn.init.normal_, std=... |
ViT weight initialization, matching moco-v3 impl minus fixed PatchEmbed | def _init_weights_vit_moco(
module: nn.Module,
name: str = "",
gain: float = 1.0,
**kwargs,
):
"""ViT weight initialization, matching moco-v3 impl minus fixed PatchEmbed"""
assert (
"deepnorm_style" not in kwargs.keys()
), "This initialization method does not support deepnorm"
... |
Follow the `Transformer Without Tears`_ initialization for self-attention | def _init_weights_small(
module: nn.Module,
name: str = "",
head_bias: float = 0.0,
gain: float = 1.0,
deepnorm_style: bool = False,
**kwargs,
):
"""Follow the `Transformer Without Tears`_ initialization for self-attention"""
if is_ffn(name):
_maybe_init_tensor(module, "weight",... |
ViT weight initialization, original timm impl (for reproducibility).
See DeepNet_ for all the DeepNorm specific codepaths | def _init_weights_vit_timm(
module: nn.Module,
name: str = "",
gain: float = 1.0,
deepnorm_style: bool = False,
**kwargs,
):
"""
ViT weight initialization, original timm impl (for reproducibility).
See DeepNet_ for all the DeepNorm specific codepaths
"""
if isinstance(module, n... |
A small helper to generate hierarchical xformers configurations,
which correspond for instance to poolformer or swin architectures.
Contrary to more "classical" Transformer architectures, which conserve the sequence/context
length across layers, hierarchical Transformers trade the sequence length for the embedding dim... | def get_hierarchical_configuration(
layer_base_configs: List[BasicLayerConfig],
residual_norm_style: ResidualNormStyle = ResidualNormStyle.Pre,
use_rotary_embeddings: bool = True,
mlp_multiplier: int = 4,
in_channels: int = 3,
dim_head: Optional[int] = None,
):
"""
A small helper to gene... |
In-place scaling+index_add
Indices in ``index`` are assumed to be unique
The max index in ``index`` is assumed to be less than the size of dim0 of ``input``.
:Note:
The FW pass is done in-place (``input`` is modified)
:Equivalent pytorch code:
.. code-block:: python
return torch.index_add(input, dim=0, s... | def scaled_index_add(
input: torch.Tensor, # [B, M, D]
index: torch.Tensor, # [Bi] - int64
source: torch.Tensor, # [Bi, M, D]
scaling: Optional[torch.Tensor] = None, # [D]
alpha: float = 1.0,
) -> torch.Tensor:
"""
In-place scaling+index_add
Indices in ``index`` are assumed to be un... |
Indices in ``index`` are assumed to be unique
In each (index, source) pair, the max index in ``index`` is assumed to be less than the size of dim0 of ``source``
:Example:
Given:
- ``sources[0]`` of shape ``[S0, D0]``
- ``indices[0]`` of shape ``[I0]``
- ``sources[1]`` of shape ``[S1, D1]``
- ``indices[1]`` of shape `... | def index_select_cat(
sources: Sequence[torch.Tensor], indices: Sequence[torch.Tensor]
) -> torch.Tensor:
"""
Indices in ``index`` are assumed to be unique
In each (index, source) pair, the max index in ``index`` is assumed to be less than the size of dim0 of ``source``
:Example:
Given:
- ... |
Initializes pipes between processes of a `ProcessGroup`, that can be used
to exchange `torch.Tensor` later | def init_ipc(
group: dist.ProcessGroup,
device: Union[torch.device, str] = "cuda",
) -> List[Optional[IPCPipe]]:
"""
Initializes pipes between processes of a `ProcessGroup`, that can be used
to exchange `torch.Tensor` later
"""
if isinstance(device, str):
device = torch.device(device... |
RMS Normalization along the last dimension.
This is similar to torch.nn.functional.normalize but with eps being added
instead of max.
Expects x contiguous of shape (..., dim), and returns normalized data
of the same shape. For each dim-length vector x, the result has
x / sqrt( x*x.sum() + eps)
If weights are in... | def rms_norm(x, weight: Optional[torch.Tensor], eps: float = 1e-6):
"""
RMS Normalization along the last dimension.
This is similar to torch.nn.functional.normalize but with eps being added
instead of max.
Expects x contiguous of shape (..., dim), and returns normalized data
of the same shape.... |
An addition fused with rms_norm.
z = rms_norm_add(x, y, weight, eps)
is equivalent to
x += y
z = rms_norm(x, weight, eps)
where x, y and z are all contiguous.
This functionality is experimental. Its API might be changed without warnings.
Use it at your own risk. | def rms_norm_add(
x: torch.Tensor, y: torch.Tensor, weight: Optional[torch.Tensor], eps: float = 1e-6
):
"""
An addition fused with rms_norm.
z = rms_norm_add(x, y, weight, eps)
is equivalent to
x += y
z = rms_norm(x, weight, eps)
where x, y and z are all contiguous.
... |
Performs RoPE (rotary embeddings) and kv-cache emplacement for a heterogeneous
batch for inference in the style given by
BlockDiagonalCausalWithOffsetPaddedKeysMask.
The batch is concatenated along the sequence dimension, so the
actual dim-0 length of all tensors is 1.
xq, xk and xv should be (1, slen, n_heads, dim), ... | def rope_padded(
xq: torch.Tensor,
xk: torch.Tensor,
xv: torch.Tensor,
cache_k: torch.Tensor,
cache_v: torch.Tensor,
attn_bias: BlockDiagonalCausalWithOffsetPaddedKeysMask,
*,
theta: float = 10000.0,
out_q: Optional[torch.Tensor] = None,
first_seqpos: Optional[torch.Tensor] = Non... |
Performs a fused all-gather followed by a linear op
It is equivalent to the following plain PyTorch code:
# like scattered_input but with first dim multiplied by group's world size
gathered_input = scattered_input.new_empty(...)
dist.all_gather_into_tensor(gathered_input, scattered_input, group=group)
return torch.nn... | def fused_allgather_and_linear(
scattered_input: torch.Tensor,
weight: Union[torch.Tensor, List[torch.Tensor]],
*,
group: dist.ProcessGroup,
out: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
num_stripes: int = 1,
timeout_s: int = 60 * 60,
scale_scattered_input: Optional[torc... |
Performs a fused linear op followed by a reduce-scatter
It is equivalent to the following plain PyTorch code:
gathered_output = torch.nn.functional.linear(gathered_input, weight)
# like gathered_output but with first dim divided by group's world size
scattered_output = gathered_output.new_empty(...)
dist.reduce_scatt... | def fused_linear_and_reducescatter(
gathered_input: torch.Tensor,
weight: Union[torch.Tensor, List[torch.Tensor]],
*,
group: dist.ProcessGroup,
out: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
num_stripes: int = 1,
timeout_s: int = 60 * 60,
scale_gathered_input: Optional[to... |
Returns the version of the cusparselt.so library that ships with pytorch 2.2+ | def _get_cusparselt_torch_version() -> Tuple[int, int, int]:
"""
Returns the version of the cusparselt.so library that ships with pytorch 2.2+
"""
lib_path = _get_cusparselt_lib()
if lib_path is None:
return (0, 0, 0)
lib = ctypes.CDLL(lib_path)
def get_version_part(version_part: in... |
Computes a SwiGLU block given the weights/bias of the 3
linear layers.
- It is recommended to keep ``op=None`` so the best implementation available for the inputs will be used.
:Equivalent pytorch code:
.. code-block:: python
x1 = F.linear(x, w1, b1)
x2 = F.linear(x, w2, b2)
hidden = F.silu(x1) * x... | def swiglu(
x: torch.Tensor,
w1: torch.Tensor,
b1: Optional[torch.Tensor],
w2: torch.Tensor,
b2: Optional[torch.Tensor],
w3: torch.Tensor,
b3: Optional[torch.Tensor],
*,
op: Optional[SwiGLUOp] = None,
) -> torch.Tensor:
"""
Computes a SwiGLU block given the weights/bias of th... |
Computes a SwiGLU block given the weights/bias of the 3
linear layers.
:Equivalent pytorch code:
.. code-block:: python
x1 = F.linear(x, w1, b1)
x2 = F.linear(x, w2, b2)
hidden = F.silu(x1) * x2
return F.linear(hidden, w3, b3)
:Supported hardware:
This operator is only optimized on A100+ on ``torch... | def swiglu_packed(
x: torch.Tensor,
w1w2: torch.Tensor,
b1b2: Optional[torch.Tensor],
w3: torch.Tensor,
b3: Optional[torch.Tensor],
*,
op: SwiGLUOp,
) -> torch.Tensor:
"""
Computes a SwiGLU block given the weights/bias of the 3
linear layers.
:Equivalent pytorch code:
.... |
Multiply two matrices given as grids of tiles
It performs the matmul between A and B, which are given as two-dimensional
grids of tiles (i.e., blocks), represented as lists of lists of tensors.
The output will itself be a matrix in such a form. Formally:
out[m][n] = sum(a[m][k] @ b[k][n] for k in range(...))
wit... | def tiled_matmul(
a: List[List[torch.Tensor]],
b: List[List[torch.Tensor]],
) -> List[List[torch.Tensor]]:
"""Multiply two matrices given as grids of tiles
It performs the matmul between A and B, which are given as two-dimensional
grids of tiles (i.e., blocks), represented as lists of lists of tens... |
If the tensors are already stacked on dimension :code:`dim`, returns the strides of the stacked tensors. Otherwise returns :code:`None`. | def get_stack_strides(
tensors: Sequence[torch.Tensor], dim: int
) -> Optional[Tuple[int, ...]]:
"""
If the tensors are already stacked on dimension :code:`dim`, \
returns the strides of the stacked tensors. \
Otherwise returns :code:`None`.
"""
if len(tensors) <= 1 or dim > tensors[... |
Does exactly the same as :attr:`torch.unbind` for the forward.
In backward, avoids a :attr:`torch.cat` if the gradients
are already multiple views of the same storage | def unbind(x: torch.Tensor, dim: int) -> Tuple[torch.Tensor, ...]:
"""
Does exactly the same as :attr:`torch.unbind` for the forward.
In backward, avoids a :attr:`torch.cat` if the gradients
are already multiple views of the same storage
"""
return _Unbind.apply(x, dim) |
Does exactly the same as :attr:`torch.stack` if the tensors can be concatenated
without any memory operation. Otherwise returns None. | def stack_or_none(tensors: Sequence[torch.Tensor], dim: int) -> torch.Tensor:
"""
Does exactly the same as :attr:`torch.stack` if the tensors can be concatenated
without any memory operation. Otherwise returns None.
"""
return _StackOrNone.apply(dim, *tensors) |
CK kernel throws "Memory access fault by GPU node-2" when B * T >= 2**20, might be some index overflow.
To reproduce, remove this function and run benchmark_mem_eff_attention with ParlAI model shape (256, 4096, 16, 64).
This needs further debugging, for now let's not support such shapes. | def _check_large_shapes(reasons: List[str], inp: Inputs) -> None:
"""CK kernel throws "Memory access fault by GPU node-2" when B * T >= 2**20, might be some index overflow.
To reproduce, remove this function and run benchmark_mem_eff_attention with ParlAI model shape (256, 4096, 16, 64).
This needs further ... |
Computes the best operator for forward
Raises:
NotImplementedError: if not operator was found
Returns:
AttentionOp: The best operator for the configuration | def _dispatch_fw(inp: Inputs, needs_gradient: bool) -> Type[AttentionFwOpBase]:
"""Computes the best operator for forward
Raises:
NotImplementedError: if not operator was found
Returns:
AttentionOp: The best operator for the configuration
"""
return _run_priority_list(
"mem... |
We want to be able to collapse the G/H dimensions together | def _check_strides_for_bmghk(x: torch.Tensor, name: str, reasons: List[str]) -> None:
"""
We want to be able to collapse the G/H dimensions together
"""
if x.ndim == 5:
stride_g, stride_h = x.stride(2), x.stride(3)
if x.shape[2] == 1:
return
if x.shape[3] == 1 or str... |
Implements the memory-efficient attention mechanism following
`"Self-Attention Does Not Need O(n^2) Memory" <http://arxiv.org/abs/2112.05682>`_.
:Inputs shape:
- Input tensors must be in format ``[B, M, H, K]``, where B is the batch size, M the sequence length, H the number of heads, and K the embeding size p... | def memory_efficient_attention(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None,
p: float = 0.0,
scale: Optional[float] = None,
*,
op: Optional[AttentionOp] = None,
output_dtype: Optional[torch.dtype] = None,... |
Calculates the forward pass of :attr:`xformers.ops.memory_efficient_attention`. | def memory_efficient_attention_forward(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None,
p: float = 0.0,
scale: Optional[float] = None,
*,
op: Optional[Type[AttentionFwOpBase]] = None,
output_dtype: Optional[... |
Returns a tuple (output, lse), where `lse` can be used to compute the backward pass later.
See :attr:`xformers.ops.memory_efficient_attention` for an explanation of the arguments
See :attr:`xformers.ops.memory_efficient_attention_backward` for running the backward pass | def memory_efficient_attention_forward_requires_grad(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None,
p: float = 0.0,
scale: Optional[float] = None,
*,
op: Optional[Type[AttentionFwOpBase]] = None,
output_dt... |
Computes the gradient of the attention.
Returns a tuple (dq, dk, dv)
See :attr:`xformers.ops.memory_efficient_attention` for an explanation of the arguments.
`lse` is the tensor returned by
:attr:`xformers.ops.memory_efficient_attention_forward_requires_grad` | def memory_efficient_attention_backward(
grad: torch.Tensor,
output: torch.Tensor,
lse: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None,
p: float = 0.0,
scale: Optional[float] = None,
*,
... |
Warning: grad/ctx.out is potentially in BMK format | def _memory_efficient_attention_backward(
ctx: Context,
inp: Inputs,
grad: torch.Tensor,
op: Optional[Type[AttentionBwOpBase]],
*,
_skip_op_checks: bool = False,
) -> Gradients:
"""Warning: grad/ctx.out is potentially in BMK format"""
inp.validate_inputs()
if grad.ndim != inp.query.n... |
Returns a tuple (output, lse), where `output` is the attention and `lse`
is a least squared error. The cat'ed outputs of calls to this with the same query
and separate keys and values can be merged with merge_attentions to obtain
the attention of the queries against the disjoint union of the keys and values. | def memory_efficient_attention_partial(
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None,
p: float = 0.0,
scale: Optional[float] = None,
*,
op: Optional[Type[AttentionFwOpBase]] = None,
output_dtype: Optional[... |
Combine attention output computed on different parts of K/V for the same
query to get attention on the whole K/V. See https://arxiv.org/abs/2402.05099
The result is equal to
Out_full = (Out1 * exp(LSE1) + Out2 * exp(LSE2) + ...) / (exp(LSE1) + exp(LSE2) + ...)
LSE_full = log(exp(LSE1) + exp(LSE2) + ...)
Args:
... | def merge_attentions(
attn_split: Union[torch.Tensor, List[torch.Tensor]],
lse_split: Union[torch.Tensor, List[torch.Tensor]],
write_lse: bool = True,
output_dtype: Optional[torch.dtype] = None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""
Combine attention output computed on different ... |
Each letter in this diagram is a whole row of length dim.
INPUT xq xk xv
head_dim ─►
batch qqqqqq kk vv
│ qqqqqq kk vv
▼ qqqqqq kk vv
head_idx: (goes across all heads of all 3 inputs)
▲ ▲ ▲ ▲ ▲ ▲
│ │ ... | def _rope_padded_kernel(
xq,
xk,
xv,
out_q,
cache_k,
cache_v,
seqstartq,
seqstartk,
seqlenk,
theta,
first_seqpos,
seqpos,
k_start: tl.constexpr,
v_start: tl.constexpr,
n_groups,
dim: tl.constexpr, # dimension of each head
stride_xqM,
stride_xqG,
... |
A more compact way to define a triton.Config, so it fits on one line | def gen_config(
block_m: int,
block_n: int,
block_k: int,
stages: int,
warps: int,
split_k: int = 1,
group_m: int = 8,
) -> triton.Config:
"""A more compact way to define a triton.Config, so it fits on one line"""
return triton.Config(
{
"BLOCK_M": block_m,
... |
Call into Triton's upstream cost model, with the right args
The upstream function expects arguments to have certain names. Since we
renamed a few of them in our implementation, we rename them back.
At the time of writing (July 2023) the arguments that Triton expects are:
M, N, K, A, B, C, BLOCK_M, BLOCK_N, BLOCK_K, S... | def our_estimate_matmul_time(B1, C1, N1, N2, N3, **kwargs):
"""Call into Triton's upstream cost model, with the right args
The upstream function expects arguments to have certain names. Since we
renamed a few of them in our implementation, we rename them back.
At the time of writing (July 2023) the ar... |
A more compact way to define a triton.Config, so it fits on one line | def gen_config(
block_m: int,
block_n: int,
block_k: int,
stages: int,
warps: int,
split_k: int = 1,
group_m: int = 8,
) -> triton.Config:
"""A more compact way to define a triton.Config, so it fits on one line"""
return triton.Config(
{
"BLOCK_M": block_m,
... |
Call into Triton's upstream cost model, with the right args
The upstream function expects arguments to have certain names. Since we
renamed a few of them in our implementation, we rename them back.
At the time of writing (July 2023) the arguments that Triton expects are:
M, N, K, A, B, C, BLOCK_M, BLOCK_N, BLOCK_K, S... | def our_estimate_matmul_time(
A11, B11, C11, M1, M2, M3, N1, N2, N3, K1, K2, K3, **kwargs
):
"""Call into Triton's upstream cost model, with the right args
The upstream function expects arguments to have certain names. Since we
renamed a few of them in our implementation, we rename them back.
At t... |
A pre-configured profiler that will run on the first ~20 steps of the training
It will provide multiple traces that can be exploited later.
Use it in a context manager around your training loop, and call `xformers.profiler.step`
before starting the next iteration.
:Examples:
.. code-block:: python
import torch
... | def profile(
output_dir: str,
module: Optional[nn.Module] = None,
schedule: Sequence[Tuple[Any, int, int]] = DEFAULT_SCHEDULE,
):
"""
A pre-configured profiler that will run on the first ~20 steps of the training
It will provide multiple traces that can be exploited later.
Use it in a contex... |
See `xformers.profiler.profile` | def step() -> None:
"""See `xformers.profiler.profile`"""
# Silently return if no profiler is enabled
if _Profiler._CURRENT_PROFILER is None:
return
_Profiler._CURRENT_PROFILER.step() |
Currently only implemented for GPUs | def get_device_limits(device) -> DeviceLimit:
"""Currently only implemented for GPUs"""
if device is not None and device.type == "cuda":
device_sm = torch.cuda.get_device_capability(device)
device_name = torch.cuda.get_device_name(device)
for lim in DEVICE_LIMITS:
if lim.s... |
Count flops for convolution. Note only multiplication is
counted. Computation for addition and bias is ignored.
Flops for a transposed convolution are calculated as
flops = (x_shape[2:] * prod(w_shape) * batch_size).
Args:
x_shape (list(int)): The input shape before convolution.
w_shape (list(int)): The filter ... | def conv_flop_count(
x_shape: List[int],
w_shape: List[int],
out_shape: List[int],
transposed: bool = False,
) -> float:
"""
Count flops for convolution. Note only multiplication is
counted. Computation for addition and bias is ignored.
Flops for a transposed convolution are calculated a... |
Count flops for convolution. | def conv_flop(inputs: List[Any], outputs: List[Any]):
"""
Count flops for convolution.
"""
x, w = inputs[:2]
x_shape, w_shape, out_shape = (get_shape(x), get_shape(w), get_shape(outputs[0]))
transposed = inputs[6]
return conv_flop_count(x_shape, w_shape, out_shape, transposed=transposed) |
Converts dense 2d matrix to a csr sparse matrix. | def _nonzero_mask_to_sparse_csr_indices(mask, device):
"""Converts dense 2d matrix to a csr sparse matrix."""
assert len(mask.shape) == 2
index_dtype = torch.int32
# Calculate the offset of each row.
row_offsets = mask.sum(dim=-1, dtype=index_dtype).cumsum(dim=-1, dtype=index_dtype)
row_offset... |
Converts dense 2d matrix to a csr sparse matrix. | def _dense_to_sparse(matrix, device):
"""Converts dense 2d matrix to a csr sparse matrix."""
assert len(matrix.shape) == 2
value_dtype = torch.float32
# Extract the nonzero values.
mask = matrix != 0
values = matrix[mask].to(dtype=value_dtype, device=device)
row_indices, row_offsets, colu... |
Apply dropout on the input tensor.
Optionally add a bias, the computation will be fused. | def dropout(
x: torch.Tensor,
p: float,
bias: Optional[torch.Tensor] = None,
activation: Optional[Activation] = None,
):
"""
Apply dropout on the input tensor.
Optionally add a bias, the computation will be fused.
"""
assert p <= 1.0 and p >= 0.0
if p == 1.0:
return tor... |
ReLU_ activation function
.. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html | def relu(x):
"""
ReLU_ activation function
.. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html
"""
return tl.where(x >= 0, x, 0.0) |
Squared ReLU activation, as proposed in the Primer_ paper.
.. _Primer: https://arxiv.org/abs/2109.08668 | def squared_relu(x):
"""
Squared ReLU activation, as proposed in the Primer_ paper.
.. _Primer: https://arxiv.org/abs/2109.08668
"""
x_sq = x * x
return tl.where(x > 0.0, x_sq, 0.0) |
Star ReLU activation, as proposed in the "MetaFormer Baselines for Vision"_ paper.
.. _ "MetaFormer Baselines for Vision": https://arxiv.org/pdf/2210.13452.pdf | def star_relu(x):
"""
Star ReLU activation, as proposed in the "MetaFormer Baselines for Vision"_ paper.
.. _ "MetaFormer Baselines for Vision": https://arxiv.org/pdf/2210.13452.pdf
"""
x_sq = x * x
return 0.8944 * tl.where(x > 0.0, x_sq, 0.0) - 0.4472 |
LeakyReLU_ activation
.. _LeakyReLU: https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html | def leaky_relu(x):
"""
LeakyReLU_ activation
.. _LeakyReLU: https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html
"""
return tl.where(x >= 0.0, x, 0.01 * x) |
GeLU_ activation - Gaussian error linear unit
.. _GeLU: https://arxiv.org/pdf/1606.08415.pdf | def gelu(x):
"""
GeLU_ activation - Gaussian error linear unit
.. _GeLU: https://arxiv.org/pdf/1606.08415.pdf
"""
return 0.5 * x * (1 + tanh(_kAlpha * (x + 0.044715 * x * x * x))) |
SmeLU_ activation - Smooth ReLU with beta=2.0
.. _SmeLU: https://arxiv.org/pdf/2202.06499.pdf | def smelu(x):
"""
SmeLU_ activation - Smooth ReLU with beta=2.0
.. _SmeLU: https://arxiv.org/pdf/2202.06499.pdf
"""
beta = 2.0
relu = tl.where(x >= beta, x, 0.0)
return tl.where(tl.abs(x) <= beta, (x + beta) * (x + beta) / (4.0 * beta), relu) |
Apply dropout on an input tensor
Y : Output (M, N)
X : Input (M, N)
BIAS (N,)
SEEDS (M,)
p : dropout probability | def k_dropout_fw(
Y, X, BIAS, SEEDS,
stride,
M, N,
p: tl.constexpr,
is_fp16: tl.constexpr, # autotune
ACTIVATION: tl.constexpr,
# Meta-parameters
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
SIZE_RAND_BLOCK: tl.constexpr,
USE_BIAS: tl.constexpr,
):
"""
Apply dropout... |
Apply dropout on an input tensor
GRAD_OUT (M, N)
GRAD_BIAS (N,)
GRAD_IN (M, N)
BIAS (N,)
SEEDS (N,)
p : dropout probability | def k_dropout_bw(
GRAD_IN, GRAD_BIAS, GRAD_OUT,
INPUTS, BIAS, SEEDS,
stride_grad, stride_inputs,
M, N,
p: tl.constexpr,
is_fp16: tl.constexpr, # autotune
ACTIVATION: tl.constexpr,
# Meta-parameters
BLOCK_M: tl.constexpr, # heuristics
BLOCK_N: tl.constexpr,
SIZE_RAND_BLOCK: ... |
Go over all the activation inputs, compute the corresponding gradient | def kernel_bw(
# Pointers to matrices
GRAD_ACT, GRAD_OUT, ACT_INPUTS,
# Matrix dimensions
N,
# The stride variables represent how much to increase the ptr by when moving by 1
# element in a particular dimension. E.g. stride_am is how much to increase a_ptr
# by to get the element one row dow... |
Compute grad_in = activation^-1(grad_out) @ weight.transpose()
.. note: The weight buffer is transposed on the fly
.. note: Activation gradient needs to be a Triton kernel | def fused_matmul_backward(
grad_out: torch.Tensor,
inputs: torch.Tensor,
act_in: Optional[torch.Tensor],
weight: torch.Tensor,
trainable_weight: bool,
trainable_bias: bool,
activation_grad: int = 0,
):
"""
Compute grad_in = activation^-1(grad_out) @ weight.transpose()
.. note: T... |
Kernel for computing Out = activation(A x W + C)
- Input has shape (M, K)
- Weight has shape (K, N)
- Bias has shape (N,)
- Output has shape (M, N)
- ActInputs (optional) has shape (M, N)
'ActInputs' optionally saves the A x W + C intermediate for backward computations
This kernel will consolidate over K | def kernel_fma(
# Pointers to matrices
OUT, ACT_INPUTS, INPUT, WEIGHT, bias,
# Matrix dimensions
M, N, K,
# The stride variables represent how much to increase the ptr by when moving by 1
# element in a particular dimension. E.g. stride_am is how much to increase a_ptr
# by to get the elemen... |
Compute e = activation(x @ weight + bias).
This wrapper kicks the `kernel_fma` Triton kernel | def fused_matmul(
x: torch.Tensor,
weight: torch.Tensor,
bias: Optional[torch.Tensor],
activation=0,
save_act_inputs: bool = False
):
"""
Compute e = activation(x @ weight + bias).
This wrapper kicks the `kernel_fma` Triton kernel
"""
if not x.is_contiguous():
x = x.cont... |
Fused layernorm kernel over a 3d tensor.
The layer norm is applied over the last dimension.
Compute
y = (x - E(x))/(sqrt(var(x) + epsilon)) * gamma + beta | def layer_norm_fw(X, Y, W, B, M, V, stride, N, eps, affine: tl.constexpr, BLOCK_SIZE_N: tl.constexpr):
# fmt: on
"""
Fused layernorm kernel over a 3d tensor.
The layer norm is applied over the last dimension.
Compute
y = (x - E(x))/(sqrt(var(x) + epsilon)) * gamma + beta
"""
row = ... |
Fused softmax kernel over a 3d tensor.
The softmax is applied over the last dimension, meaning that this is equivalent to torch.softmax(tensor, dim=-1)
Note, if the last dimension is large, say 128K elements, the kernel compile time can shot up to many minutes when
the kernel is run for the first time. | def _softmax(
Y, X, M,
stride_ym, stride_yn,
stride_xm, stride_xn,
stride_mn,
K,
# Meta-params
depth: tl.constexpr,
causal: tl.constexpr,
use_mask: tl.constexpr,
log: tl.constexpr,
):
# fmt: om
"""
Fused softmax kernel over a 3d tensor.
The softmax is applied ove... |
Compute the softmax gradients.
..Note: Not autotuning for now because this would lead to broken accumulated gradients | def _softmax_backward(
GradIn, GradOut, Out,
stride_bm, stride_bn,
stride_gm, stride_gn,
stride_om, stride_on,
K,
# meta-params
depth: tl.constexpr,
causal: tl.constexpr,
log: tl.constexpr,
):
# fmt: on
"""
Compute the softmax gradients.
..Note: Not autotuning for no... |
Applies the Softmax function to an 3-dimensional input Tensor
rescaling them so that the elements of the n-dimensional output Tensor
lie in the range [0,1] and sum to 1.
Softmax is defined as:
.. math::
\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
.. warning: softmax is computed on the last dimensi... | def softmax(
x: torch.Tensor, mask: Optional[torch.Tensor] = None, causal: bool = False
) -> torch.Tensor:
r"""Applies the Softmax function to an 3-dimensional input Tensor
rescaling them so that the elements of the n-dimensional output Tensor
lie in the range [0,1] and sum to 1.
Softmax is defined... |
Applies the :math:`\log(\text{Softmax}(x))` function to an 3-dimensional
input Tensor. The LogSoftmax formulation can be simplified as:
.. math::
\text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right)
Args:
x: input tensor.
Returns:
a Tensor of the same dimension and shape as t... | def log_softmax(
x: torch.Tensor, mask: Optional[torch.Tensor] = None, causal: bool = False
) -> torch.Tensor:
r"""Applies the :math:`\log(\text{Softmax}(x))` function to an 3-dimensional
input Tensor. The LogSoftmax formulation can be simplified as:
.. math::
\text{LogSoftmax}(x_{i}) = \log\le... |
Specializes a triton kernel with variable number of inputs
to a specific number of inputs `N`.
NOTE: Because it's quite costly to call `triton.jit`,
we cache the returned value with `lru_cache` | def unroll_varargs(kernel, N: int):
"""
Specializes a triton kernel with variable number of inputs
to a specific number of inputs `N`.
NOTE: Because it's quite costly to call `triton.jit`,
we cache the returned value with `lru_cache`
"""
global _FILENAME_TO_SRC, _getlines_orig
k = trito... |
Remove the lexer/parser modules that are dynamically created. | def clean_tables():
"""Remove the lexer/parser modules that are dynamically created."""
for f in TABLES:
if os.path.isfile(f):
os.remove(f)
print("Removed " + f) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.