Registry / llm-agents / local-attention

local-attention

JSON →
library1.11.2pypypi✓ verified 85d ago

local-attention is a Python library by lucidrains that implements local attention mechanisms with configurable windowing and lookback/lookforward options, primarily for language modeling tasks. It leverages PyTorch for efficient computation and is actively maintained with frequent minor and patch releases.

pip install local-attention
INSTALL
IMPORT
SIG · LOCAL-ATTENTION
L
local-attention
llm-agentspythonv1.11.2
Install
65.7s avg
Import
5497ms
Disk
4787MB
Pass rate
4/ 10
Env Coverage4 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.11.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✕ build_error
✓ 74.78s
py 3.11
✕ build_error
✓ 68.08s
py 3.12
✕ build_error
✓ 63.48s
py 3.13
✕ build_error
✓ 56.65s
py 3.9
✕ build_error
2/4 runs
4787MB installed
● package 4787MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

LocalAttention
from local_attention import LocalAttention

Initializes a `LocalAttention` module with specified windowing parameters and applies it to a dummy input tensor. This example demonstrates a causal attention setup suitable for autoregressive models.

import torch from local_attention import LocalAttention # Ensure reproducibility torch.manual_seed(42) # Define the local attention layer # window_size defines the local neighborhood. # look_backward=1 means each token looks at (window_size) tokens to its left. # look_forward=0 means it does not look at tokens to its right (causal). attn = LocalAttention( window_size = 512, look_backward = 1, look_forward = 0, dropout = 0., causal = True, # Set to True for autoregressive models exact_windowsize = False ) # Create a dummy input tensor: (batch, sequence_length, feature_dimension) # For example, a batch of 1 sequence, 1024 tokens long, with 512 features per token. x = torch.randn(1, 1024, 512) # Apply local attention y = attn(x) print(f"Input shape: {x.shape}") print(f"Output shape: {y.shape}") # The output shape should be the same as the input shape assert x.shape == y.shape print("Local attention applied successfully.")
Debug
Known issues
gotchaMisunderstanding the interplay between `window_size`, `look_backward`, `look_forward`, and `causal` can lead to unintended attention patterns or incorrect information flow. For instance, `causal=True` combined with `look_forward > 0` might not behave as expected for strict autoregression.
fix
Carefully consult the documentation and examples for each parameter. Test with small synthetic inputs to verify the attention mask behavior, especially for autoregressive tasks where strict causality is essential.
affects: All versions
gotchaAs a PyTorch-based library, ensuring input tensors are on the correct device (CPU/GPU) and have compatible data types (`torch.float32`, `torch.float16`) is crucial. Mismatches frequently cause runtime errors or significantly degraded performance.
fix
Explicitly move tensors to the target device (e.g., `tensor.to(device)`) and ensure `dtype` consistency, especially when mixing `local-attention` with other PyTorch components or models loaded with different dtypes.
affects: All versions
gotchaThe library expects input tensors of shape `(batch, sequence_length, feature_dimension)`. Incorrectly shaped inputs, particularly transposing `sequence_length` and `feature_dimension`, are a common source of `RuntimeError` or `ValueError`.
fix
Verify your input tensor's dimensions before passing it to `LocalAttention`. If necessary, use `tensor.transpose(1, 2)` or `einops.rearrange` to correct the shape.
affects: All versions
gotchaVersion 1.11.0 updated the internal `look_around()` function to use native PyTorch functionality. While not a public API breaking change, it represents a significant internal optimization. If you were relying on previous internal behaviors (e.g., via subclassing or monkey-patching), this change could affect your custom logic.
fix
Review custom implementations that might interact with the internal `look_around` logic. For standard usage, this update is a transparent improvement.
affects: >=1.11.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'local_attention.attention'
The user is attempting to import the LocalAttention class from a non-existent sub-module `local_attention.attention` instead of directly from the top-level `local_attention` package.
fix
Change the import statement to `from local_attention import LocalAttention`.
RuntimeError: expected input to be a tensor
The input `x` passed to the `LocalAttention` module's `forward` method is not a `torch.Tensor` (e.g., it's a list, NumPy array, or Python scalar).
fix
Convert the input data to a `torch.Tensor` using `torch.tensor()` or `torch.from_numpy()` before passing it to the attention module. Example: `x = torch.randn(1, 1024, 512)` or `x = torch.tensor(your_list_or_array, dtype=torch.float32)`.
AttributeError: 'tuple' object has no attribute 'shape'
This error occurs when a tuple (or another object without a `shape` attribute) is passed as input to `LocalAttention` where a `torch.Tensor` is expected, which possesses a `shape` attribute.
fix
Ensure the input `x` is a `torch.Tensor`. If it's a tuple of tensors, concatenate them, or if it's a simple tuple of data, convert it to a tensor. Example: `x = torch.tensor(your_tuple_data, dtype=torch.float32)` or `x = torch.cat(your_tuple_of_tensors, dim=-1)`.
Upgrade
Version history
1.11.2latest on PyPI · released Jul 16, 2025
Audit
Dependencies
torchrequiredCore deep learning framework dependency for tensor operations and model building.
einopsrequiredUsed for flexible and readable tensor manipulations (rearranging, reducing, repeating).
Agent activity
14 hits · last 30 days
node
12
OpenAI (training)
1
Resources
local-attention — pip install local-attention · libregistry