(shape: tuple[int, int], block_size: tuple[int, int], dtype: str)
| 138 | |
| 139 | |
| 140 | def rowwise_quant_fp8_e4m3(shape: tuple[int, int], block_size: tuple[int, int], dtype: str): |
| 141 | x_full_np = (np.random.rand(*shape) * 2 - 1).astype(dtype) |
| 142 | x_scale_shape = ( |
| 143 | *shape[:-1], |
| 144 | (shape[-1] + block_size[1] - 1) // block_size[1], |
| 145 | ) |
| 146 | # For each (block_size[1]) block, compute the max abs value of `w_full_np` |
| 147 | x_max_abs_np = np.zeros(x_scale_shape, dtype="float32") |
| 148 | for i in range(x_scale_shape[-1]): |
| 149 | x_max_abs_np[..., i] = np.max( |
| 150 | np.abs(x_full_np[..., i * block_size[1] : min((i + 1) * block_size[1], shape[-1])]), |
| 151 | axis=-1, |
| 152 | )[0] |
| 153 | # Scale is the `x_max_abs_np` divided by the max value of quant_dtype in ml_dtypes |
| 154 | fp8_max = float(ml_dtypes.finfo("float8_e4m3fn").max) |
| 155 | x_scale_np = x_max_abs_np / fp8_max |
| 156 | # `x_np` is the `x_full_np` divided by the `x_scale_np` (with block awareness), |
| 157 | # clamped to (-fp8_max, fp8_max), and cast to `quant_dtype` |
| 158 | x_np = np.zeros_like(x_full_np, dtype="float8_e4m3fn") |
| 159 | for i in range(x_scale_shape[-1]): |
| 160 | x_np[..., i * block_size[1] : min((i + 1) * block_size[1], shape[-1])] = np.clip( |
| 161 | x_full_np[..., i * block_size[1] : min((i + 1) * block_size[1], shape[-1])] |
| 162 | / x_scale_np[..., i : i + 1], |
| 163 | -fp8_max, |
| 164 | fp8_max, |
| 165 | ) |
| 166 | |
| 167 | x_scale_np = np.random.rand(*x_scale_np.shape).astype("float32") / fp8_max |
| 168 | for i in range(x_scale_shape[-1]): |
| 169 | x_full_np[..., i * block_size[1] : min((i + 1) * block_size[1], shape[-1])] = ( |
| 170 | x_np[..., i * block_size[1] : min((i + 1) * block_size[1], shape[-1])].astype( |
| 171 | x_scale_np.dtype |
| 172 | ) |
| 173 | * x_scale_np[..., i : i + 1] |
| 174 | ) |
| 175 | return x_np, x_scale_np |
| 176 | |
| 177 | |
| 178 | def blockwise_quant_fp8_e4m3(shape: tuple[int, int], block_size: tuple[int, int], dtype: str): |
no test coverage detected
searching dependent graphs…