2323
2424from .plan import ContractionPlan , _parse_subscripts , plan_contraction
2525
26+ # Mapping of user-friendly dtype strings to torch.dtype
27+ _DTYPE_MAP : dict [str , torch .dtype ] = {
28+ "bf16" : torch .bfloat16 ,
29+ "bfloat16" : torch .bfloat16 ,
30+ "fp16" : torch .float16 ,
31+ "float16" : torch .float16 ,
32+ "f32" : torch .float32 ,
33+ "float32" : torch .float32 ,
34+ "f64" : torch .float64 ,
35+ "float64" : torch .float64 ,
36+ }
37+
38+
39+ def _resolve_dtype (dtype : str | torch .dtype | None ) -> torch .dtype | None :
40+ """Resolve a dtype argument to a ``torch.dtype`` or ``None``."""
41+ if dtype is None :
42+ return None
43+ if isinstance (dtype , torch .dtype ):
44+ return dtype
45+ try :
46+ return _DTYPE_MAP [dtype .lower ()]
47+ except KeyError :
48+ raise ValueError (f"unknown dtype { dtype !r} ; valid strings: { sorted (_DTYPE_MAP )} " ) from None
49+
2650
2751def einsum (
2852 subscripts : str ,
2953 * operands : torch .Tensor ,
3054 alpha : float = 1.0 ,
3155 beta : float = 0.0 ,
3256 out : torch .Tensor | None = None ,
57+ dtype : str | torch .dtype | None = None ,
3358) -> torch .Tensor :
3459 """Einstein summation with contraction planning.
3560
@@ -43,20 +68,28 @@ def einsum(
4368 out: Optional accumulation tensor. When provided the return value is
4469 ``alpha * contract(operands) + beta * out``. Must have the same
4570 shape as the contraction result.
71+ dtype: Optional compute dtype. When set, all operands are cast to this
72+ dtype before contracting and the result is returned in that dtype.
73+ Accepts ``torch.dtype`` instances or strings: ``"bf16"``,
74+ ``"bfloat16"``, ``"fp16"``, ``"float16"``, ``"f32"``, ``"float32"``.
75+ Matches Neuron SDK autocast recommendations for Trainium.
4676
4777 Examples:
4878 # Matrix multiply
4979 einsum("ij,jk->ik", A, B)
5080
81+ # Force bf16 compute (e.g. to hit NKI bf16 matmul kernel)
82+ einsum("ij,jk->ik", A, B, dtype="bf16")
83+
5184 # Scaled GEMM: 2*A@B + 0.5*C (cuTENSOR-style alpha/beta)
5285 einsum("ij,jk->ik", A, B, alpha=2.0, beta=0.5, out=C)
5386
54- # Batched matrix multiply
55- einsum("bij,bjk->bik", A, B)
56-
5787 # DF-MP2 energy contraction
5888 einsum("iap,jbp->ijab", B, B)
5989 """
90+ target = _resolve_dtype (dtype )
91+ if target is not None :
92+ operands = tuple (op .to (target ) for op in operands )
6093 plan = plan_contraction (subscripts , * operands )
6194 result = _execute_contraction (subscripts , operands , plan )
6295 if alpha != 1.0 :
0 commit comments