File size: 2,381 Bytes
5396c20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

import io,re,sys
p1='/root/ds4/ds4_cuda.cu'
s=open(p1).read()
old="""static __device__ __forceinline__ float solar_e2m1_decode(uint8_t code) {

    __nv_fp4_e2m1 value;

    value.__x = code & 0x0fu;

    return (float)value;

}"""
new="""static __device__ __forceinline__ float solar_e2m1_decode(uint8_t code) {

    const float mag = dsv4_e2m1fn_value_dev(code & 0x7u);

    return (code & 0x8u) ? -mag : mag;

}"""
assert old in s, 'A not found'
s=s.replace(old,new,1); open(p1,'w').write(s); print('A patched')

p2='/root/ds4/cuda/mmq/ds4_fattn.cu'
s=open(p2).read()
old2="""__device__ __forceinline__ float solar_fattn_e2m1(uint8_t code) {

    __nv_fp4_e2m1 value;

    value.__x = code & 0x0fu;

    return (float)value;

}"""
new2="""__device__ __forceinline__ float solar_fattn_e2m1(uint8_t code) {

    static const float tbl[8] = {0.0f,0.5f,1.0f,1.5f,2.0f,3.0f,4.0f,6.0f};

    const float mag = tbl[code & 0x7u];

    return (code & 0x8u) ? -mag : mag;

}



__device__ __forceinline__ __half2 solar_fattn_e2m1x2(uint8_t packed) {

    return __floats2half2_rn(solar_fattn_e2m1(packed & 0x0fu),

                             solar_fattn_e2m1((packed >> 4u) & 0x0fu));

}"""
assert old2 in s, 'B not found'
s=s.replace(old2,new2,1)
old3="""        const __half2_raw v01 = __nv_cvt_fp4x2_to_halfraw2(

            (__nv_fp4x2_storage_t)(vpack & 0xffu), __NV_E2M1);

        const __half2_raw v23 = __nv_cvt_fp4x2_to_halfraw2(

            (__nv_fp4x2_storage_t)(vpack >> 8u), __NV_E2M1);"""
new3="""        const __half2 v01 = solar_fattn_e2m1x2((uint8_t)(vpack & 0xffu));

        const __half2 v23 = solar_fattn_e2m1x2((uint8_t)(vpack >> 8u));"""
assert old3 in s, 'C not found'
s=s.replace(old3,new3,1)
s=s.replace("""        const float2 fv01 = __half22float2(__half2(v01));

        const float2 fv23 = __half22float2(__half2(v23));""","""        const float2 fv01 = __half22float2(v01);

        const float2 fv23 = __half22float2(v23);""",1)
open(p2,'w').write(s); print('B/C patched')

p3='/root/ds4/cuda/mmq/quantize.cu'
s=open(p3).read()
old4="#if CUDART_VERSION >= 12080\n        const float scaled_val = xi * inv_s;"
new4="#if CUDART_VERSION >= 12080 && defined(DS4_CUDA_NATIVE_FP4)\n        const float scaled_val = xi * inv_s;"
assert old4 in s, 'D not found'
s=s.replace(old4,new4,1); open(p3,'w').write(s); print('D patched')