blksprs 0.2b4__py3-none-any.whl → 1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,97 @@
1
+ import torch
2
+ from torch import Tensor
3
+
4
+
5
+ def validate_dimensions(*tensors: Tensor) -> None:
6
+ if _skip_validation():
7
+ return
8
+
9
+ for tensor in tensors:
10
+ if tensor.dim() != 3:
11
+ raise ValueError("Tensor must have 3 dimensions")
12
+
13
+
14
+ def validate_contiguous(*tensors: Tensor) -> None:
15
+ if _skip_validation():
16
+ return
17
+
18
+ for tensor in tensors:
19
+ if not tensor.is_contiguous():
20
+ raise ValueError("Tensor must be contiguous")
21
+
22
+
23
+ def validate_dtype_float(*tensors: Tensor) -> None:
24
+ if _skip_validation():
25
+ return
26
+
27
+ for tensor in tensors:
28
+ if tensor.dtype != torch.float32:
29
+ raise ValueError("Tensor must have float32 dtype")
30
+
31
+
32
+ def validate_dtype_int(*tensors: Tensor) -> None:
33
+ if _skip_validation():
34
+ return
35
+
36
+ for tensor in tensors:
37
+ if tensor.dtype != torch.int32 and tensor.dtype != torch.int64:
38
+ raise ValueError("Tensor must have int32 or int64 dtype")
39
+
40
+
41
+ def validate_device(*tensors: Tensor) -> None:
42
+ if _skip_validation():
43
+ return
44
+
45
+ device = None
46
+
47
+ for i, tensor in enumerate(tensors):
48
+ if i == 0:
49
+ device = tensor.device
50
+
51
+ if not device.type == 'cuda':
52
+ raise ValueError("Tensors must be on GPU")
53
+
54
+ if tensor.device != device:
55
+ raise ValueError("Tensors must be on same device")
56
+
57
+
58
+ def validate_sparsity(sparsity_block_size: int, *tensor_sparsity_layout_tuples: tuple[Tensor, Tensor]) -> None:
59
+ if _skip_validation():
60
+ return
61
+
62
+ for (tensor, sparsity_layout) in tensor_sparsity_layout_tuples:
63
+ _validate_sparsity_layout_values(sparsity_layout)
64
+
65
+ if not (tensor.size(-1) == tensor.size(-2) == sparsity_block_size):
66
+ raise ValueError("Blocks not conforming to sparsity block size")
67
+ if not tensor.size(0) == torch.sum(sparsity_layout.reshape(-1)):
68
+ raise ValueError("Mismatch between sparsity layout and blocks")
69
+
70
+
71
+ def _validate_sparsity_layout_values(sparsity_layout: Tensor):
72
+ if not torch.all(torch.logical_or(sparsity_layout == 0, sparsity_layout == 1)):
73
+ raise ValueError("Sparsity layout values must be either 0 or 1")
74
+
75
+ def validate_sparsity_block_size(sparsity_block_size: int, *tensors):
76
+ if _skip_validation():
77
+ return
78
+
79
+ if not (sparsity_block_size & (sparsity_block_size - 1)) == 0:
80
+ raise ValueError("Sparsity block size must be a power of 2")
81
+
82
+ for tensor in tensors:
83
+ if not (tensor.size(-1) % sparsity_block_size == 0 and tensor.size(-2) % sparsity_block_size == 0):
84
+ raise ValueError("Tensor sizes must be divisible by sparsity block size")
85
+
86
+ def validate_triton_block_size(triton_block_size: int, sparsity_block_size: int):
87
+ if _skip_validation():
88
+ return
89
+
90
+ if triton_block_size is None:
91
+ return
92
+
93
+ if triton_block_size > sparsity_block_size:
94
+ raise ValueError("Triton block size cannot be larger than sparsity block size")
95
+
96
+ def _skip_validation():
97
+ return False
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.1
2
+ Name: blksprs
3
+ Version: 1.1
4
+ Summary: A lightweight library for operations on blocksparse matrices in PyTorch.
5
+ Author-email: Felix Schön <schoen@kr.tuwien.ac.at>
6
+ Project-URL: Homepage, https://github.com/FelixSchoen/blksprs
7
+ Project-URL: Bugtracker, https://github.com/FelixSchoen/blksprs/issues
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: torch
11
+ Provides-Extra: deploy
12
+ Requires-Dist: build; extra == "deploy"
13
+ Requires-Dist: twine; extra == "deploy"
14
+ Requires-Dist: pdoc3; extra == "deploy"
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest; extra == "test"
17
+ Requires-Dist: pytest-xdist; extra == "test"
18
+ Requires-Dist: pytest-cov; extra == "test"
19
+ Requires-Dist: coverage; extra == "test"
20
+ Requires-Dist: matplotlib; extra == "test"
21
+
22
+ # blksprs
23
+
24
+ ## Overview
25
+
26
+ A lightweight and efficient library for operations on block-sparse matrices in PyTorch using Triton.
27
+
28
+ Currently supported operations (includes gradient calculation):
29
+
30
+ - Sparse matrix multiplication (_supports any combination of sparse and dense matrices due to support
31
+ for `sparse = sparse @ sparse` matmul_)
32
+ - Softmax
33
+ - Transposition
34
+ - Gather
35
+ - Scatter (_supports either no reduction or summation, gradients are only available for summation_)
36
+ - Conversion from and to sparse form
37
+
38
+ As with this library sparse matrices are represented using a tuple of `(matrix, sparsity_layout, sparsity_block_size)`,
39
+ any element-wise operations can be applied in regular torch-like fashion.
40
+ These include, e.g.,
41
+
42
+ - Element-wise addition and subtraction
43
+ - Element-wise multiplication and division
44
+ - Element-wise exponentiation
45
+ - ...
46
+
47
+ Note that in order to correctly apply element-wise operations between two sparse tensors their sparsity layouts have to
48
+ match.
49
+
50
+ Furthermore, the library provides a set of utility functions for the creation of sparsity layouts based on existing
51
+ dense tensors.
52
+
53
+ ## Installation
54
+
55
+ Note that due to the dependency on [Triton](https://github.com/triton-lang/triton) this library is only compatible with
56
+ the Linux platform.
57
+
58
+ We recommend installing blksprs from [PyPI](https://pypi.org/project/blksprs/) using pip:
59
+
60
+ ```pip install blksprs```
61
+
62
+ ## Changelog
63
+
64
+ See [`CHANGELOG.md`](https://github.com/FelixSchoen/blksprs/blob/main/CHANGELOG.md) for a detailed changelog.
65
+
66
+ ## Usage
67
+
68
+ We provide an example below to demonstrate the usage of the library.
69
+ For more detailed examples, please refer to
70
+ the [test cases](https://github.com/FelixSchoen/blksprs/blob/main/test/cases/test_blocksparse.py) which cover all
71
+ implemented operations and functions.
72
+ The example below can also be found in
73
+ the [test cases](https://github.com/FelixSchoen/blksprs/blob/main/test/cases/test_readme.py).
74
+
75
+ ```python
76
+ import torch
77
+
78
+ from blksprs.layouting.sparsity_layout import build_sparsity_layout
79
+ from blksprs.ops.conversion import to_sparse, to_dense
80
+ from blksprs.ops.matmul import matmul
81
+ from blksprs.ops.row_wise_sum import row_wise_sum
82
+ from blksprs.ops.softmax import softmax
83
+ from blksprs.ops.transpose import transpose
84
+ from blksprs.utils.tools import do_shape_blocksparse, undo_shape_blocksparse
85
+
86
+
87
+ def test_readme():
88
+ # Set up parameters (batch size, number of heads, dimensions for matrices (m, k) and (n, k))
89
+ b, h, m, n, k = 2, 4, 64, 64, 16
90
+
91
+ # Percentage of blocks that will be sparse in the output for demonstration purposes
92
+ sparsity_percentage = 25
93
+
94
+ # Must be a power of two, greater than or equal to 16 for matmul, and divide m, n, and k
95
+ sparsity_block_size = 16
96
+
97
+ # Must be a power of two and smaller than or equal to sparsity_block_size
98
+ # If it is set to ``none`` a value will be chosen automatically
99
+ triton_block_size = None
100
+
101
+ # Initialise random (dense) tensors
102
+ x = torch.randn(size=(b, h, m, k), device="cuda")
103
+ y = torch.randn(size=(b, h, n, k), device="cuda").transpose(-1, -2).contiguous()
104
+
105
+ # Convert tensors to three-dimensional (dense) tensors since Triton can only handle tensors of exactly three dimensions
106
+ x_dense, x_shape_original = do_shape_blocksparse(x)
107
+ y_dense, y_shape_original = do_shape_blocksparse(y)
108
+
109
+ # Create sparsity layouts from existing tensors
110
+ sparsity_layout_x = build_sparsity_layout(x_dense, sparsity_block_size, triton_block_size=triton_block_size)
111
+ sparsity_layout_y = build_sparsity_layout(y_dense, sparsity_block_size, triton_block_size=triton_block_size)
112
+
113
+ # Create random sparsity layout for output tensor
114
+ sparsity_layout_o = _get_random_sparsity_layout(b * h, m, n, sparsity_block_size, sparsity_percentage)
115
+
116
+ # Convert tensors to sparse tensors for matrix multiplication
117
+ x_sparse = to_sparse(x_dense, sparsity_layout_x, sparsity_block_size, triton_block_size=triton_block_size)
118
+ y_sparse = to_sparse(y_dense, sparsity_layout_y, sparsity_block_size, triton_block_size=triton_block_size)
119
+
120
+ # Perform matrix multiplication
121
+ o_sparse = matmul(x_sparse, sparsity_layout_x, y_sparse, sparsity_layout_y, sparsity_layout_o, sparsity_block_size,
122
+ triton_block_size=triton_block_size)
123
+ o_dense = to_dense(o_sparse, sparsity_layout_o, sparsity_block_size, triton_block_size=triton_block_size)
124
+
125
+ # Sanity check
126
+ o_torch = torch.matmul(x_dense, y_dense)
127
+
128
+ # Perform round trip to set sparse blocks to 0
129
+ o_torch_round_trip = to_dense(
130
+ to_sparse(o_torch, sparsity_layout_o, sparsity_block_size, triton_block_size=triton_block_size),
131
+ sparsity_layout_o, sparsity_block_size, fill_value=0, triton_block_size=triton_block_size)
132
+
133
+ # Assert that the output is correct
134
+ assert torch.allclose(o_dense, o_torch_round_trip, atol=2e-2) # Note that small numerical differences are expected
135
+
136
+ # Assert that the output has the correct sparsity layout
137
+ actual_sparsity_layout_o = build_sparsity_layout(o_dense, sparsity_block_size, triton_block_size=triton_block_size)
138
+ assert torch.allclose(actual_sparsity_layout_o, sparsity_layout_o)
139
+
140
+ # Convert output tensor back to original shape
141
+ o = undo_shape_blocksparse(o_dense, x_shape_original)
142
+
143
+ # Other available functions
144
+ transpose(o_sparse, sparsity_layout_o, sparsity_block_size, triton_block_size=triton_block_size)
145
+ softmax(o_sparse, sparsity_layout_o, sparsity_block_size, triton_block_size=triton_block_size)
146
+ row_wise_sum(o_sparse, sparsity_layout_o, sparsity_block_size, triton_block_size=triton_block_size)
147
+
148
+
149
+ def _get_random_sparsity_layout(b, m, n, sparsity_block_size, sparsity_percentage):
150
+ """Helper function, creates a random sparsity layout for a given shape with a given percentage of blocks marked as sparse.
151
+
152
+ """
153
+ m_s = m // sparsity_block_size
154
+ n_s = n // sparsity_block_size
155
+
156
+ sparsity_layout = torch.ones(size=(b, m_s, n_s), device="cuda", dtype=torch.int)
157
+
158
+ num_zero_elements = int(m_s * n_s * (sparsity_percentage / 100))
159
+ for b_i in range(b):
160
+ indices = torch.randperm(m_s * n_s)[:num_zero_elements]
161
+ sparsity_layout[b_i, indices // n_s, indices % n_s] = 0
162
+
163
+ return sparsity_layout
164
+ ```
@@ -0,0 +1,17 @@
1
+ blksprs/layouting/distribution_layout.py,sha256=GQ-ZRXbeImiLcbaqnL2FuUZ6DoFwmB0naT_YrOpD84Q,4940
2
+ blksprs/layouting/sparsity_layout.py,sha256=Z9Ac88kQZVaPp27ymlLwyGN14ZfMyljXp6oM_gSsFMQ,2902
3
+ blksprs/misc/broadcast_addition.py,sha256=vf1Hdqz9Uyqykto3DCjmdyepMzpMXL238SpANQqRAwI,5297
4
+ blksprs/ops/conversion.py,sha256=COhHE5KvwhrtdUTLZX1wmxFe0kDNMY97iIhnkMmztBA,11362
5
+ blksprs/ops/distribution.py,sha256=_fQb6fWpLxocAh86D74ATahChi0EK0eBb4eUOUEBVps,16769
6
+ blksprs/ops/exp.py,sha256=qs8fVtCzxl4CKT4GepaqurjEL62jyi8VjMY12JFrFAU,3674
7
+ blksprs/ops/matmul.py,sha256=x3lrYg4g8fIf5PeMtZY_SEpi11kP9RFcRoemCIxcSDE,11086
8
+ blksprs/ops/row_wise_sum.py,sha256=ojuSejV37cLtRNS3lBfknA5KY3TEg8EHxOqVT6JZzoM,11387
9
+ blksprs/ops/softmax.py,sha256=ZyeAVqmG_VzJ72FArGrpUSFfoSM4GPxyubrmNKERVIA,11654
10
+ blksprs/ops/transpose.py,sha256=DVEXoxo2MoTNL3NZrjxsukMDrzk2vnEXL1uRnKFWkn0,6722
11
+ blksprs/utils/benchmarking.py,sha256=4pLVlnPW_2EM-NT3n4SClaRznVYEljztLbJcccz8kZE,1360
12
+ blksprs/utils/tools.py,sha256=P2UALvccRjJJ7w05YGuaxB3qmNObgct4idfM0jlE2wg,465
13
+ blksprs/utils/validation.py,sha256=gJYZO5C48YUrXV3Fy_Z_lCaOpiFj951FT-Od7sKfprg,3007
14
+ blksprs-1.1.dist-info/METADATA,sha256=NIdEtqxj4SBUOP1eMlBz2RoOppwlQx9sJnRmDicWvp4,6982
15
+ blksprs-1.1.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
16
+ blksprs-1.1.dist-info/top_level.txt,sha256=qyp0IHeY3H2GQA97i4hk_To5rRBS2YcE1HRPSLy04fk,8
17
+ blksprs-1.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (74.0.0)
2
+ Generator: setuptools (75.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5