fp8_cast_bf16.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import json
  3. from argparse import ArgumentParser
  4. from glob import glob
  5. from tqdm import tqdm
  6. import torch
  7. from safetensors.torch import load_file, save_file
  8. from kernel import weight_dequant
  9. def main(fp8_path, bf16_path):
  10. torch.set_default_dtype(torch.bfloat16)
  11. os.makedirs(bf16_path, exist_ok=True)
  12. model_index_file = os.path.join(fp8_path, "model.safetensors.index.json")
  13. with open(model_index_file, "r") as f:
  14. model_index = json.load(f)
  15. weight_map = model_index["weight_map"]
  16. fp8_weight_names = []
  17. safetensor_files = list(glob(os.path.join(fp8_path, "*.safetensors")))
  18. for safetensor_file in tqdm(safetensor_files):
  19. file_name = os.path.basename(safetensor_file)
  20. state_dict = load_file(safetensor_file, device="cuda")
  21. new_state_dict = {}
  22. for weight_name, weight in state_dict.items():
  23. if weight_name.endswith("_scale_inv"):
  24. continue
  25. elif weight.element_size() == 1:
  26. scale_inv_name = f"{weight_name}_scale_inv"
  27. assert scale_inv_name in state_dict
  28. fp8_weight_names.append(weight_name)
  29. scale_inv = state_dict[scale_inv_name]
  30. new_state_dict[weight_name] = weight_dequant(weight, scale_inv)
  31. else:
  32. new_state_dict[weight_name] = weight
  33. new_safetensor_file = os.path.join(bf16_path, file_name)
  34. save_file(new_state_dict, new_safetensor_file)
  35. new_model_index_file = os.path.join(bf16_path, "model.safetensors.index.json")
  36. for weight_name in fp8_weight_names:
  37. scale_inv_name = f"{weight_name}_scale_inv"
  38. assert scale_inv_name in weight_map
  39. weight_map.pop(scale_inv_name)
  40. with open(new_model_index_file, "w") as f:
  41. json.dump({"metadata": {}, "weight_map": weight_map}, f, indent=2)
  42. if __name__ == "__main__":
  43. parser = ArgumentParser()
  44. parser.add_argument("--input-fp8-hf-path", type=str, required=True)
  45. parser.add_argument("--output-bf16-hf-path", type=str, required=True)
  46. args = parser.parse_args()
  47. main(args.input_fp8_hf_path, args.output_bf16_hf_path)