1010from flag_gems .utils import broadcastable_to , libentry , libtuner
1111from flag_gems .utils import triton_lang_extension as tle
1212
13+ _ordered_datatypes = [torch .float16 , torch .bfloat16 , torch .float32 , torch .float64 ]
14+
15+
16+ def get_higher_dtype (a , b ):
17+ if a is b :
18+ return a
19+ assert a in _ordered_datatypes
20+ assert b in _ordered_datatypes
21+ for d in _ordered_datatypes :
22+ if a is d :
23+ return b
24+ if b is d :
25+ return a
26+
27+
1328logger = logging .getLogger (__name__ )
1429
1530
@@ -76,6 +91,9 @@ def addmm_kernel(
7691 if IS_FP64 :
7792 a = a .to (tl .float32 )
7893 b = b .to (tl .float32 )
94+ if a .dtype != b .dtype :
95+ a = a .to (tl .float32 )
96+ b = b .to (tl .float32 )
7997 accumulator += tl .dot (a , b , allow_tf32 = False )
8098 a_ptrs += BLOCK_SIZE_K * stride_ak
8199 b_ptrs += BLOCK_SIZE_K * stride_bk
@@ -88,7 +106,7 @@ def addmm_kernel(
88106 bias = tl .load (i_ptrs , mask = c_mask , other = 0.0 )
89107
90108 accumulator = accumulator * alpha + bias * beta
91- c = accumulator .to (bias .dtype )
109+ c = accumulator .to (c_ptr .dtype . element_ty )
92110 tl .store (c_ptrs , c , mask = c_mask )
93111
94112
@@ -112,7 +130,8 @@ def addmm(bias, mat1, mat2, *, beta=1, alpha=1):
112130 )
113131 mat1 = mat1 .contiguous ()
114132 # mat2 = mat2.contiguous()
115- out = torch .empty ((M , N ), device = mat1 .device , dtype = mat1 .dtype )
133+ c_dtype = get_higher_dtype (mat1 .dtype , mat2 .dtype )
134+ out = torch .empty ((M , N ), device = mat1 .device , dtype = c_dtype )
116135 bias = bias .broadcast_to (out .shape )
117136
118137 grid = lambda META : (
@@ -151,7 +170,8 @@ def addmm_out(bias, mat1, mat2, *, beta=1, alpha=1, out=None):
151170 M , K = mat1 .shape
152171 _ , N = mat2 .shape
153172 if out is None :
154- out = torch .empty ((M , N ), device = mat1 .device , dtype = mat1 .dtype )
173+ c_dtype = get_higher_dtype (mat1 .dtype , mat2 .dtype )
174+ out = torch .empty ((M , N ), device = mat1 .device , dtype = c_dtype )
155175 else :
156176 assert out .shape == (M , N ), "Incompatible output shape"
157177 logger .debug (
0 commit comments