Generate a random array by generating random bits and casting to the target dtype. Supported dtypes: - "int8", "uint8", "float16", "float32", "bfloat16", "float8_e4m3fn", "float8_e5m2"
(dtype: str, shape: tuple)
| 1203 | |
| 1204 | |
| 1205 | def generate_random_array(dtype: str, shape: tuple) -> np.ndarray: |
| 1206 | """ |
| 1207 | Generate a random array by generating random bits and casting to the target dtype. |
| 1208 | |
| 1209 | Supported dtypes: |
| 1210 | - "int8", "uint8", "float16", "float32", "bfloat16", "float8_e4m3fn", "float8_e5m2" |
| 1211 | """ |
| 1212 | try: |
| 1213 | np_dtype = np_dtype_from_str(dtype) |
| 1214 | |
| 1215 | except TypeError: |
| 1216 | raise ValueError("Provided dtype is not a valid numpy dtype.") |
| 1217 | |
| 1218 | # Determine the bit length for this dtype. |
| 1219 | bit_length = np_dtype.itemsize * 8 |
| 1220 | |
| 1221 | # Choose an appropriate unsigned container type. |
| 1222 | if bit_length <= 8: |
| 1223 | container = np.uint8 |
| 1224 | elif bit_length <= 16: |
| 1225 | container = np.uint16 |
| 1226 | elif bit_length <= 32: |
| 1227 | container = np.uint32 |
| 1228 | elif bit_length <= 64: |
| 1229 | container = np.uint64 |
| 1230 | else: |
| 1231 | raise ValueError(f"Unsupported dtype bit length: {bit_length}") |
| 1232 | |
| 1233 | # Generate random integers in the full range of the bit length. |
| 1234 | random_ints = np.random.randint(0, 2**bit_length, size=shape, dtype=container) |
| 1235 | # Reinterpret the bit pattern as the desired dtype. |
| 1236 | res = random_ints.view(np_dtype) |
| 1237 | with np.errstate(invalid="ignore"): |
| 1238 | invalid_indices = np.where(~np.isfinite(res)) |
| 1239 | for idx in zip(*invalid_indices): |
| 1240 | while True: |
| 1241 | with np.errstate(invalid="ignore"): |
| 1242 | if np.isfinite(res[idx]): |
| 1243 | break |
| 1244 | # Generate a new random value for this specific position |
| 1245 | new_random_int = np.random.randint(0, 2**bit_length, size=1, dtype=container) |
| 1246 | res[idx] = new_random_int.view(np_dtype)[0] |
| 1247 | return res |
nothing calls this directly
no test coverage detected
searching dependent graphs…