trntensor 0.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.
- trntensor/__init__.py +21 -0
- trntensor/decompose.py +180 -0
- trntensor/einsum.py +110 -0
- trntensor/nki/__init__.py +3 -0
- trntensor/nki/dispatch.py +36 -0
- trntensor/plan.py +134 -0
- trntensor-0.1.1.dist-info/METADATA +106 -0
- trntensor-0.1.1.dist-info/RECORD +11 -0
- trntensor-0.1.1.dist-info/WHEEL +5 -0
- trntensor-0.1.1.dist-info/licenses/LICENSE +201 -0
- trntensor-0.1.1.dist-info/top_level.txt +1 -0
trntensor/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""
|
|
2
|
+
trntensor — Tensor contractions for AWS Trainium via NKI.
|
|
3
|
+
|
|
4
|
+
Einstein summation, contraction planning, and tensor decompositions
|
|
5
|
+
for scientific computing. Part of the trnsci scientific computing suite.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.1"
|
|
9
|
+
|
|
10
|
+
from .einsum import einsum, multi_einsum
|
|
11
|
+
from .plan import ContractionPlan, plan_contraction, estimate_flops
|
|
12
|
+
from .decompose import (cp_decompose, cp_reconstruct,
|
|
13
|
+
tucker_decompose, tucker_reconstruct)
|
|
14
|
+
from .nki import HAS_NKI, set_backend, get_backend
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"einsum", "multi_einsum",
|
|
18
|
+
"ContractionPlan", "plan_contraction", "estimate_flops",
|
|
19
|
+
"cp_decompose", "cp_reconstruct", "tucker_decompose", "tucker_reconstruct",
|
|
20
|
+
"HAS_NKI", "set_backend", "get_backend",
|
|
21
|
+
]
|
trntensor/decompose.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tensor decompositions for Trainium.
|
|
3
|
+
|
|
4
|
+
CP (CANDECOMP/PARAFAC) and Tucker decompositions for compressing
|
|
5
|
+
high-order tensors. Used in quantum chemistry for:
|
|
6
|
+
- Tensor hypercontraction (THC) of two-electron integrals
|
|
7
|
+
- Reduced-rank approximation of the DF coefficient tensor B_ia^P
|
|
8
|
+
- Low-rank factorization of response tensors
|
|
9
|
+
|
|
10
|
+
All inner operations are matmuls → map to Tensor Engine via trnblas.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import torch
|
|
16
|
+
from typing import Tuple, Optional
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def cp_decompose(
|
|
20
|
+
tensor: torch.Tensor,
|
|
21
|
+
rank: int,
|
|
22
|
+
max_iter: int = 100,
|
|
23
|
+
tol: float = 1e-6,
|
|
24
|
+
) -> Tuple[list[torch.Tensor], torch.Tensor]:
|
|
25
|
+
"""CP decomposition via alternating least squares (ALS).
|
|
26
|
+
|
|
27
|
+
Approximates tensor T ≈ Σ_r λ_r * a_r ⊗ b_r ⊗ c_r ⊗ ...
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
tensor: Input tensor of arbitrary order
|
|
31
|
+
rank: Number of components
|
|
32
|
+
max_iter: Maximum ALS iterations
|
|
33
|
+
tol: Convergence tolerance (relative reconstruction error)
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
factors: List of factor matrices, one per mode [(I_0, R), (I_1, R), ...]
|
|
37
|
+
weights: Component weights (R,)
|
|
38
|
+
"""
|
|
39
|
+
ndim = tensor.dim()
|
|
40
|
+
shape = tensor.shape
|
|
41
|
+
|
|
42
|
+
# Initialize factors randomly
|
|
43
|
+
factors = [torch.randn(s, rank) for s in shape]
|
|
44
|
+
|
|
45
|
+
# Normalize
|
|
46
|
+
for k in range(ndim):
|
|
47
|
+
norms = torch.linalg.norm(factors[k], dim=0, keepdim=True)
|
|
48
|
+
factors[k] = factors[k] / (norms + 1e-10)
|
|
49
|
+
|
|
50
|
+
weights = torch.ones(rank)
|
|
51
|
+
|
|
52
|
+
for iteration in range(max_iter):
|
|
53
|
+
for mode in range(ndim):
|
|
54
|
+
# Compute the Khatri-Rao product of all factors except current mode
|
|
55
|
+
V = _khatri_rao_except(factors, mode)
|
|
56
|
+
|
|
57
|
+
# Unfold tensor along current mode
|
|
58
|
+
T_mode = _unfold(tensor, mode)
|
|
59
|
+
|
|
60
|
+
# Solve least squares: factors[mode] = T_mode @ V @ (V^T V)^{-1}
|
|
61
|
+
VtV = V.T @ V
|
|
62
|
+
rhs = T_mode @ V
|
|
63
|
+
try:
|
|
64
|
+
factors[mode] = torch.linalg.solve(VtV, rhs.T).T
|
|
65
|
+
except RuntimeError:
|
|
66
|
+
factors[mode] = rhs @ torch.linalg.pinv(VtV)
|
|
67
|
+
|
|
68
|
+
# Extract norms as weights
|
|
69
|
+
norms = torch.linalg.norm(factors[mode], dim=0)
|
|
70
|
+
weights = norms
|
|
71
|
+
factors[mode] = factors[mode] / (norms.unsqueeze(0) + 1e-10)
|
|
72
|
+
|
|
73
|
+
# Check convergence
|
|
74
|
+
reconstructed = cp_reconstruct(factors, weights)
|
|
75
|
+
error = torch.linalg.norm(tensor - reconstructed) / torch.linalg.norm(tensor)
|
|
76
|
+
if error.item() < tol:
|
|
77
|
+
break
|
|
78
|
+
|
|
79
|
+
return factors, weights
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def cp_reconstruct(factors: list[torch.Tensor], weights: torch.Tensor) -> torch.Tensor:
|
|
83
|
+
"""Reconstruct tensor from CP factors: T = Σ_r w_r * a_r ⊗ b_r ⊗ ..."""
|
|
84
|
+
rank = weights.shape[0]
|
|
85
|
+
ndim = len(factors)
|
|
86
|
+
shape = tuple(f.shape[0] for f in factors)
|
|
87
|
+
|
|
88
|
+
result = torch.zeros(shape)
|
|
89
|
+
for r in range(rank):
|
|
90
|
+
component = weights[r]
|
|
91
|
+
outer = factors[0][:, r]
|
|
92
|
+
for k in range(1, ndim):
|
|
93
|
+
outer = torch.outer(outer.reshape(-1), factors[k][:, r]).reshape(
|
|
94
|
+
*[factors[i].shape[0] for i in range(k + 1)]
|
|
95
|
+
)
|
|
96
|
+
result = result + component * outer
|
|
97
|
+
|
|
98
|
+
return result
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def tucker_decompose(
|
|
102
|
+
tensor: torch.Tensor,
|
|
103
|
+
ranks: tuple[int, ...],
|
|
104
|
+
) -> Tuple[torch.Tensor, list[torch.Tensor]]:
|
|
105
|
+
"""Tucker decomposition via higher-order SVD (HOSVD).
|
|
106
|
+
|
|
107
|
+
T ≈ G ×_1 U_1 ×_2 U_2 ×_3 U_3 ...
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
tensor: Input tensor
|
|
111
|
+
ranks: Tuple of ranks for each mode
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
core: Core tensor of shape ranks
|
|
115
|
+
factors: List of factor matrices [(I_k, R_k) for each mode]
|
|
116
|
+
"""
|
|
117
|
+
ndim = tensor.dim()
|
|
118
|
+
assert len(ranks) == ndim
|
|
119
|
+
|
|
120
|
+
factors = []
|
|
121
|
+
for mode in range(ndim):
|
|
122
|
+
T_mode = _unfold(tensor, mode)
|
|
123
|
+
U, S, Vh = torch.linalg.svd(T_mode, full_matrices=False)
|
|
124
|
+
factors.append(U[:, :ranks[mode]])
|
|
125
|
+
|
|
126
|
+
# Core tensor: G = T ×_1 U_1^T ×_2 U_2^T ×_3 U_3^T ...
|
|
127
|
+
core = tensor.clone()
|
|
128
|
+
for mode in range(ndim):
|
|
129
|
+
core = _mode_product(core, factors[mode].T, mode)
|
|
130
|
+
|
|
131
|
+
return core, factors
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def tucker_reconstruct(core: torch.Tensor, factors: list[torch.Tensor]) -> torch.Tensor:
|
|
135
|
+
"""Reconstruct tensor from Tucker decomposition."""
|
|
136
|
+
result = core.clone()
|
|
137
|
+
for mode in range(len(factors)):
|
|
138
|
+
result = _mode_product(result, factors[mode], mode)
|
|
139
|
+
return result
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --- Tensor algebra helpers ---
|
|
143
|
+
|
|
144
|
+
def _unfold(tensor: torch.Tensor, mode: int) -> torch.Tensor:
|
|
145
|
+
"""Mode-n unfolding (matricization) of a tensor."""
|
|
146
|
+
return tensor.moveaxis(mode, 0).reshape(tensor.shape[mode], -1)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _mode_product(tensor: torch.Tensor, matrix: torch.Tensor, mode: int) -> torch.Tensor:
|
|
150
|
+
"""Mode-n product: T ×_n M.
|
|
151
|
+
|
|
152
|
+
Multiplies matrix M along mode n of tensor T.
|
|
153
|
+
"""
|
|
154
|
+
T_unfolded = _unfold(tensor, mode)
|
|
155
|
+
result_unfolded = matrix @ T_unfolded
|
|
156
|
+
new_shape = list(tensor.shape)
|
|
157
|
+
new_shape[mode] = matrix.shape[0]
|
|
158
|
+
# Refold
|
|
159
|
+
result = result_unfolded.reshape(new_shape[mode], *[new_shape[i] for i in range(len(new_shape)) if i != mode])
|
|
160
|
+
# Move mode axis back
|
|
161
|
+
result = result.moveaxis(0, mode)
|
|
162
|
+
return result
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _khatri_rao_except(factors: list[torch.Tensor], skip: int) -> torch.Tensor:
|
|
166
|
+
"""Khatri-Rao product of all factor matrices except index `skip`.
|
|
167
|
+
|
|
168
|
+
Column-wise Kronecker product.
|
|
169
|
+
"""
|
|
170
|
+
indices = [i for i in range(len(factors)) if i != skip]
|
|
171
|
+
result = factors[indices[0]]
|
|
172
|
+
for i in indices[1:]:
|
|
173
|
+
# Khatri-Rao: column-wise Kronecker
|
|
174
|
+
R = result.shape[1]
|
|
175
|
+
new_rows = result.shape[0] * factors[i].shape[0]
|
|
176
|
+
kr = torch.zeros(new_rows, R)
|
|
177
|
+
for r in range(R):
|
|
178
|
+
kr[:, r] = torch.kron(result[:, r], factors[i][:, r])
|
|
179
|
+
result = kr
|
|
180
|
+
return result
|
trntensor/einsum.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Tensor contractions via einsum for Trainium.
|
|
3
|
+
|
|
4
|
+
The core operation: generalized tensor contraction expressed in Einstein
|
|
5
|
+
summation notation. Decomposes arbitrary contractions into sequences of
|
|
6
|
+
matmuls that map to the Tensor Engine.
|
|
7
|
+
|
|
8
|
+
For DF-MP2, the natural expression is:
|
|
9
|
+
T_ijab = einsum("iap,jbp->ijab", B, B)
|
|
10
|
+
|
|
11
|
+
rather than the GEMM decomposition:
|
|
12
|
+
for i in range(nocc):
|
|
13
|
+
for j in range(nocc):
|
|
14
|
+
T = B[i] @ B[j].T
|
|
15
|
+
|
|
16
|
+
The einsum path can fuse the loops and avoid materializing intermediates,
|
|
17
|
+
which is where cuTENSOR beats cuBLAS for tensor workloads.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import torch
|
|
23
|
+
from typing import Optional
|
|
24
|
+
|
|
25
|
+
from .plan import ContractionPlan, plan_contraction
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def einsum(subscripts: str, *operands: torch.Tensor) -> torch.Tensor:
|
|
29
|
+
"""Einstein summation with contraction planning.
|
|
30
|
+
|
|
31
|
+
Supports the same subscript notation as torch.einsum and numpy.einsum.
|
|
32
|
+
|
|
33
|
+
Examples:
|
|
34
|
+
# Matrix multiply
|
|
35
|
+
einsum("ij,jk->ik", A, B)
|
|
36
|
+
|
|
37
|
+
# Batched matrix multiply
|
|
38
|
+
einsum("bij,bjk->bik", A, B)
|
|
39
|
+
|
|
40
|
+
# Trace
|
|
41
|
+
einsum("ii->", A)
|
|
42
|
+
|
|
43
|
+
# Outer product
|
|
44
|
+
einsum("i,j->ij", x, y)
|
|
45
|
+
|
|
46
|
+
# DF-MP2 energy contraction
|
|
47
|
+
einsum("iap,jbp->ijab", B, B)
|
|
48
|
+
|
|
49
|
+
# Tensor contraction (4-index transform)
|
|
50
|
+
einsum("mi,mnP->inP", C, integrals)
|
|
51
|
+
"""
|
|
52
|
+
plan = plan_contraction(subscripts, *operands)
|
|
53
|
+
return _execute_contraction(subscripts, operands, plan)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _execute_contraction(
|
|
57
|
+
subscripts: str, operands: tuple, plan: ContractionPlan
|
|
58
|
+
) -> torch.Tensor:
|
|
59
|
+
"""Execute contraction according to plan.
|
|
60
|
+
|
|
61
|
+
For now, delegates to torch.einsum. The plan infrastructure
|
|
62
|
+
enables NKI-optimized paths for specific contraction patterns.
|
|
63
|
+
"""
|
|
64
|
+
if plan.strategy == "torch":
|
|
65
|
+
return torch.einsum(subscripts, *operands)
|
|
66
|
+
elif plan.strategy == "bmm":
|
|
67
|
+
return _execute_bmm(subscripts, operands, plan)
|
|
68
|
+
elif plan.strategy == "matmul":
|
|
69
|
+
return _execute_matmul(subscripts, operands, plan)
|
|
70
|
+
else:
|
|
71
|
+
return torch.einsum(subscripts, *operands)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _execute_matmul(subscripts: str, operands: tuple, plan: ContractionPlan) -> torch.Tensor:
|
|
75
|
+
"""Execute as a single matmul (2D contraction)."""
|
|
76
|
+
A, B = operands
|
|
77
|
+
if plan.transA and plan.transB:
|
|
78
|
+
return torch.matmul(A.T, B.T)
|
|
79
|
+
elif plan.transA:
|
|
80
|
+
return torch.matmul(A.T, B)
|
|
81
|
+
elif plan.transB:
|
|
82
|
+
return torch.matmul(A, B.T)
|
|
83
|
+
else:
|
|
84
|
+
return torch.matmul(A, B)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _execute_bmm(subscripts: str, operands: tuple, plan: ContractionPlan) -> torch.Tensor:
|
|
88
|
+
"""Execute as batched matmul."""
|
|
89
|
+
A, B = operands
|
|
90
|
+
return torch.bmm(A, B)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def multi_einsum(*contractions: tuple) -> list[torch.Tensor]:
|
|
94
|
+
"""Execute multiple contractions, fusing where possible.
|
|
95
|
+
|
|
96
|
+
Each contraction is (subscripts, *operands).
|
|
97
|
+
Returns list of results.
|
|
98
|
+
|
|
99
|
+
Useful for DF-MP2 where many independent contractions share operands:
|
|
100
|
+
results = multi_einsum(
|
|
101
|
+
("iap,jbp->ijab", B, B),
|
|
102
|
+
("ibp,jap->ijab", B, B), # Exchange term
|
|
103
|
+
)
|
|
104
|
+
"""
|
|
105
|
+
results = []
|
|
106
|
+
for contraction in contractions:
|
|
107
|
+
subscripts = contraction[0]
|
|
108
|
+
operands = contraction[1:]
|
|
109
|
+
results.append(einsum(subscripts, *operands))
|
|
110
|
+
return results
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NKI dispatch for tensor contractions.
|
|
3
|
+
|
|
4
|
+
The primary NKI target is fused multi-index contractions that avoid
|
|
5
|
+
materializing intermediates. For example, the DF-MP2 energy contraction
|
|
6
|
+
E = Σ_{ijab} B_ia^P B_jb^P / Δ_{ijab}
|
|
7
|
+
can be tiled across (i,j) pairs with B slices loaded once to SBUF.
|
|
8
|
+
|
|
9
|
+
On the Tensor Engine, each (a,b) block is a matmul: B[i] @ B[j]^T.
|
|
10
|
+
Fusing the denominator division into the PSUM accumulation avoids
|
|
11
|
+
a separate element-wise pass over the output.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
import neuronxcc.nki as nki
|
|
18
|
+
import neuronxcc.nki.language as nl
|
|
19
|
+
HAS_NKI = True
|
|
20
|
+
except ImportError:
|
|
21
|
+
HAS_NKI = False
|
|
22
|
+
|
|
23
|
+
_backend = "auto"
|
|
24
|
+
|
|
25
|
+
def set_backend(backend: str):
|
|
26
|
+
global _backend
|
|
27
|
+
assert backend in ("auto", "pytorch", "nki")
|
|
28
|
+
_backend = backend
|
|
29
|
+
|
|
30
|
+
def get_backend() -> str:
|
|
31
|
+
return _backend
|
|
32
|
+
|
|
33
|
+
def _use_nki() -> bool:
|
|
34
|
+
if _backend == "nki": return True
|
|
35
|
+
if _backend == "pytorch": return False
|
|
36
|
+
return HAS_NKI
|
trntensor/plan.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Contraction planner for tensor operations.
|
|
3
|
+
|
|
4
|
+
Analyzes einsum subscripts to select the best execution strategy:
|
|
5
|
+
- Direct matmul for 2-operand contractions over a single index
|
|
6
|
+
- Batched matmul (bmm) for batched contractions
|
|
7
|
+
- torch.einsum fallback for complex patterns
|
|
8
|
+
- (Future) NKI-optimized paths for specific patterns
|
|
9
|
+
|
|
10
|
+
Also plans multi-contraction fusion for DF-MP2-style workloads
|
|
11
|
+
where many contractions share operands.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import torch
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ContractionPlan:
|
|
24
|
+
"""Execution plan for a tensor contraction."""
|
|
25
|
+
subscripts: str
|
|
26
|
+
strategy: str # "matmul", "bmm", "torch", "nki"
|
|
27
|
+
transA: bool = False
|
|
28
|
+
transB: bool = False
|
|
29
|
+
contraction_indices: list[str] = field(default_factory=list)
|
|
30
|
+
batch_indices: list[str] = field(default_factory=list)
|
|
31
|
+
output_indices: list[str] = field(default_factory=list)
|
|
32
|
+
estimated_flops: int = 0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def plan_contraction(subscripts: str, *operands: torch.Tensor) -> ContractionPlan:
|
|
36
|
+
"""Analyze contraction and select execution strategy."""
|
|
37
|
+
input_str, output_str = _parse_subscripts(subscripts)
|
|
38
|
+
input_indices = input_str.split(",")
|
|
39
|
+
|
|
40
|
+
if len(operands) == 2:
|
|
41
|
+
return _plan_binary(subscripts, input_indices, output_str, operands)
|
|
42
|
+
else:
|
|
43
|
+
return ContractionPlan(subscripts=subscripts, strategy="torch")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse_subscripts(subscripts: str) -> tuple[str, str]:
|
|
47
|
+
"""Parse 'ij,jk->ik' into ('ij,jk', 'ik')."""
|
|
48
|
+
if "->" in subscripts:
|
|
49
|
+
input_str, output_str = subscripts.split("->")
|
|
50
|
+
else:
|
|
51
|
+
input_str = subscripts
|
|
52
|
+
# Implicit output: all indices that appear exactly once
|
|
53
|
+
all_indices = re.findall(r'[a-zA-Z]', input_str.replace(",", ""))
|
|
54
|
+
from collections import Counter
|
|
55
|
+
counts = Counter(all_indices)
|
|
56
|
+
output_str = "".join(sorted(c for c, n in counts.items() if n == 1))
|
|
57
|
+
return input_str, output_str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _plan_binary(
|
|
61
|
+
subscripts: str,
|
|
62
|
+
input_indices: list[str],
|
|
63
|
+
output_str: str,
|
|
64
|
+
operands: tuple,
|
|
65
|
+
) -> ContractionPlan:
|
|
66
|
+
"""Plan a 2-operand contraction."""
|
|
67
|
+
idx_a = list(input_indices[0])
|
|
68
|
+
idx_b = list(input_indices[1])
|
|
69
|
+
idx_out = list(output_str)
|
|
70
|
+
|
|
71
|
+
set_a = set(idx_a)
|
|
72
|
+
set_b = set(idx_b)
|
|
73
|
+
set_out = set(idx_out)
|
|
74
|
+
|
|
75
|
+
# Contracted indices: appear in inputs but not output
|
|
76
|
+
contracted = (set_a & set_b) - set_out
|
|
77
|
+
# Batch indices: appear in both inputs and output
|
|
78
|
+
batch = set_a & set_b & set_out
|
|
79
|
+
# Free indices: appear in one input and output
|
|
80
|
+
free_a = (set_a - set_b) & set_out
|
|
81
|
+
free_b = (set_b - set_a) & set_out
|
|
82
|
+
|
|
83
|
+
A, B = operands
|
|
84
|
+
|
|
85
|
+
# Simple matmul: ij,jk->ik or ji,jk->ik etc.
|
|
86
|
+
if len(contracted) == 1 and len(batch) == 0 and A.dim() == 2 and B.dim() == 2:
|
|
87
|
+
c_idx = list(contracted)[0]
|
|
88
|
+
transA = idx_a.index(c_idx) == 0 # Contracted index is first → need transpose
|
|
89
|
+
transB = idx_b.index(c_idx) == 1 # Contracted index is second → need transpose
|
|
90
|
+
return ContractionPlan(
|
|
91
|
+
subscripts=subscripts,
|
|
92
|
+
strategy="matmul",
|
|
93
|
+
transA=transA,
|
|
94
|
+
transB=transB,
|
|
95
|
+
contraction_indices=list(contracted),
|
|
96
|
+
output_indices=idx_out,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# Batched matmul: bij,bjk->bik
|
|
100
|
+
if len(contracted) == 1 and len(batch) == 1 and A.dim() == 3 and B.dim() == 3:
|
|
101
|
+
return ContractionPlan(
|
|
102
|
+
subscripts=subscripts,
|
|
103
|
+
strategy="bmm",
|
|
104
|
+
contraction_indices=list(contracted),
|
|
105
|
+
batch_indices=list(batch),
|
|
106
|
+
output_indices=idx_out,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# Fallback to torch.einsum
|
|
110
|
+
return ContractionPlan(
|
|
111
|
+
subscripts=subscripts,
|
|
112
|
+
strategy="torch",
|
|
113
|
+
contraction_indices=list(contracted),
|
|
114
|
+
batch_indices=list(batch),
|
|
115
|
+
output_indices=idx_out,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def estimate_flops(subscripts: str, *operands: torch.Tensor) -> int:
|
|
120
|
+
"""Estimate FLOPs for a contraction (multiply-add pairs)."""
|
|
121
|
+
input_str, output_str = _parse_subscripts(subscripts)
|
|
122
|
+
all_indices = set(re.findall(r'[a-zA-Z]', input_str))
|
|
123
|
+
|
|
124
|
+
# Product of all dimension sizes
|
|
125
|
+
index_sizes = {}
|
|
126
|
+
for op_str, op in zip(input_str.split(","), operands):
|
|
127
|
+
for idx, size in zip(op_str, op.shape):
|
|
128
|
+
index_sizes[idx] = size
|
|
129
|
+
|
|
130
|
+
flops = 1
|
|
131
|
+
for idx in all_indices:
|
|
132
|
+
flops *= index_sizes.get(idx, 1)
|
|
133
|
+
|
|
134
|
+
return flops
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: trntensor
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Tensor contractions for AWS Trainium via NKI
|
|
5
|
+
Author-email: Scott Friedman <3011922+scttfrdmn@users.noreply.github.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/trnsci/trntensor
|
|
8
|
+
Project-URL: Documentation, https://trnsci.github.io/trntensor/
|
|
9
|
+
Project-URL: Repository, https://github.com/trnsci/trntensor
|
|
10
|
+
Project-URL: Issues, https://github.com/trnsci/trntensor/issues
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: torch>=2.1
|
|
19
|
+
Requires-Dist: numpy>=1.24
|
|
20
|
+
Provides-Extra: neuron
|
|
21
|
+
Requires-Dist: neuronxcc>=2.24; extra == "neuron"
|
|
22
|
+
Requires-Dist: torch-neuronx>=2.9; extra == "neuron"
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
25
|
+
Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
|
|
26
|
+
Requires-Dist: scipy>=1.11; extra == "dev"
|
|
27
|
+
Requires-Dist: mkdocs>=1.5; extra == "dev"
|
|
28
|
+
Requires-Dist: mkdocs-material>=9.0; extra == "dev"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# trntensor
|
|
32
|
+
|
|
33
|
+
[](https://github.com/scttfrdmn/trntensor/actions/workflows/ci.yml)
|
|
34
|
+
[](https://pypi.org/project/trntensor/)
|
|
35
|
+
[](https://pypi.org/project/trntensor/)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
[](https://trnsci.github.io/trntensor/)
|
|
38
|
+
|
|
39
|
+
Tensor contractions for AWS Trainium via NKI.
|
|
40
|
+
|
|
41
|
+
Einstein summation with contraction planning, CP and Tucker decompositions. Expresses scientific tensor workloads naturally instead of decomposing to GEMM. Part of the trnsci scientific computing suite ([github.com/trnsci](https://github.com/trnsci)).
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install trntensor
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
import torch
|
|
53
|
+
import trntensor
|
|
54
|
+
|
|
55
|
+
# Einsum — drop-in for torch.einsum with contraction planning
|
|
56
|
+
C = trntensor.einsum("ij,jk->ik", A, B) # matmul
|
|
57
|
+
T = trntensor.einsum("ap,bp->ab", B_i, B_j) # DF-MP2 contraction
|
|
58
|
+
X = trntensor.einsum("mi,mnP->inP", C_occ, eri) # AO→MO transform
|
|
59
|
+
|
|
60
|
+
# Contraction planning
|
|
61
|
+
plan = trntensor.plan_contraction("ij,jk->ik", A, B)
|
|
62
|
+
flops = trntensor.estimate_flops("ij,jk->ik", A, B)
|
|
63
|
+
|
|
64
|
+
# CP decomposition (tensor hypercontraction)
|
|
65
|
+
factors, weights = trntensor.cp_decompose(tensor, rank=10)
|
|
66
|
+
reconstructed = trntensor.cp_reconstruct(factors, weights)
|
|
67
|
+
|
|
68
|
+
# Tucker decomposition (HOSVD)
|
|
69
|
+
core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Operations
|
|
73
|
+
|
|
74
|
+
| Category | Operation | Description |
|
|
75
|
+
|----------|-----------|-------------|
|
|
76
|
+
| Contraction | `einsum` | General tensor contraction |
|
|
77
|
+
| Contraction | `multi_einsum` | Multiple contractions (fusion-ready) |
|
|
78
|
+
| Planning | `plan_contraction` | Analyze and select strategy |
|
|
79
|
+
| Planning | `estimate_flops` | FLOPs for a contraction |
|
|
80
|
+
| Decomposition | `cp_decompose` | CP/PARAFAC via ALS |
|
|
81
|
+
| Decomposition | `tucker_decompose` | Tucker via HOSVD |
|
|
82
|
+
|
|
83
|
+
## Status
|
|
84
|
+
|
|
85
|
+
- [x] Einsum with matmul/bmm/torch dispatch
|
|
86
|
+
- [x] Contraction planner
|
|
87
|
+
- [x] CP decomposition (ALS)
|
|
88
|
+
- [x] Tucker decomposition (HOSVD)
|
|
89
|
+
- [x] DF-MP2 einsum example
|
|
90
|
+
- [ ] NKI fused contraction kernels
|
|
91
|
+
- [ ] Multi-contraction fusion
|
|
92
|
+
- [ ] Optimal contraction ordering (like opt_einsum)
|
|
93
|
+
|
|
94
|
+
## Related Projects
|
|
95
|
+
|
|
96
|
+
| Project | What |
|
|
97
|
+
|---------|------|
|
|
98
|
+
| [trnfft](https://github.com/scttfrdmn/trnfft) | FFT + complex ops |
|
|
99
|
+
| [trnblas](https://github.com/scttfrdmn/trnblas) | BLAS operations |
|
|
100
|
+
| [trnsolver](https://github.com/scttfrdmn/trnsolver) | Linear solvers |
|
|
101
|
+
| [trnrand](https://github.com/scttfrdmn/trnrand) | Random number generation |
|
|
102
|
+
| [trnsparse](https://github.com/scttfrdmn/trnsparse) | Sparse operations |
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
Apache 2.0 — Copyright 2026 Scott Friedman
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
trntensor/__init__.py,sha256=ZaFn5826XfEPsGoKHfbGjDBQbSRelLeImoadzQDqMow,741
|
|
2
|
+
trntensor/decompose.py,sha256=ApjxWdWMz0R5FoyGzIxv7rTkIzZDjHaXFh792Y0UGx8,5703
|
|
3
|
+
trntensor/einsum.py,sha256=3T6C8cDsuAvxllSlN-RixjPoZ__bIzuEQOlXFIJJjsk,3267
|
|
4
|
+
trntensor/plan.py,sha256=fMcmlKGA18_sp94ioYveaREVd6PjlnbenqwnTIVtqZk,4404
|
|
5
|
+
trntensor/nki/__init__.py,sha256=UJP53QV5GXr2L1x9A3LdrjanZn3-OKlZb_n-v6nwBS0,152
|
|
6
|
+
trntensor/nki/dispatch.py,sha256=7NhBFJBAeCW59DM-R5GA-Gee_o-nQQJCwst2_m_bCdI,966
|
|
7
|
+
trntensor-0.1.1.dist-info/licenses/LICENSE,sha256=hTt_varGm4HTIVm8GQ1pGR7jah4vW5IrddFIu94FPAE,11175
|
|
8
|
+
trntensor-0.1.1.dist-info/METADATA,sha256=nutK0gc66uiAMB1MWN5Kwv-kGByiJgcJkf57-ZkXVnM,4009
|
|
9
|
+
trntensor-0.1.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
+
trntensor-0.1.1.dist-info/top_level.txt,sha256=vm6Xeocl3X1Vw2abMEK5vGR7i1P-FPPilMvqoXeTP3E,10
|
|
11
|
+
trntensor-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2026 Scott Friedman
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
12
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
26
|
+
exercising permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
38
|
+
Object form, made available under the License, as indicated by a
|
|
39
|
+
copyright notice that is included in or attached to the work
|
|
40
|
+
(an example is provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original version of the Work and any modifications or additions
|
|
52
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
53
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
54
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
55
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
56
|
+
means any form of electronic, verbal, or written communication sent
|
|
57
|
+
to the Licensor or its representatives, including but not limited to
|
|
58
|
+
communication on electronic mailing lists, source code control systems,
|
|
59
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
60
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
61
|
+
excluding communication that is conspicuously marked or otherwise
|
|
62
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
65
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
66
|
+
subsequently incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, then any Derivative Works that You distribute must
|
|
110
|
+
include a readable copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
122
|
+
that such additional attribution notices cannot be construed
|
|
123
|
+
as modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions stated in this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for describing the origin of the Work and
|
|
143
|
+
reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may accept support,
|
|
169
|
+
obligations, or other liability only on behalf of Yourself and on
|
|
170
|
+
Your sole responsibility, not on behalf of any other Contributor,
|
|
171
|
+
and only if You agree to indemnify, defend, and hold each Contributor
|
|
172
|
+
harmless for any liability incurred by, or claims asserted against,
|
|
173
|
+
such Contributor by reason of your accepting any such warranty or
|
|
174
|
+
additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Scott Friedman
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
trntensor
|