fp8_cast_bf16.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. # Cache for loaded safetensor files
  17. loaded_files = {}
  18. fp8_weight_names = []
  19. # Helper function to get tensor from the correct file
  20. def get_tensor(tensor_name):
  21. file_name = weight_map[tensor_name]
  22. if file_name not in loaded_files:
  23. file_path = os.path.join(fp8_path, file_name)
  24. loaded_files[file_name] = load_file(file_path, device="cuda")
  25. return loaded_files[file_name][tensor_name]
  26. safetensor_files = list(glob(os.path.join(fp8_path, "*.safetensors")))
  27. safetensor_files.sort()
  28. for safetensor_file in tqdm(safetensor_files):
  29. file_name = os.path.basename(safetensor_file)
  30. current_state_dict = load_file(safetensor_file, device="cuda")
  31. loaded_files[file_name] = current_state_dict
  32. new_state_dict = {}
  33. for weight_name, weight in current_state_dict.items():
  34. if weight_name.endswith("_scale_inv"):
  35. continue
  36. elif weight.element_size() == 1: # FP8 weight
  37. scale_inv_name = f"{weight_name}_scale_inv"
  38. try:
  39. # Get scale_inv from the correct file
  40. scale_inv = get_tensor(scale_inv_name)
  41. fp8_weight_names.append(weight_name)
  42. new_state_dict[weight_name] = weight_dequant(weight, scale_inv)
  43. except KeyError:
  44. print(f"Warning: Missing scale_inv tensor for {weight_name}, skipping conversion")
  45. new_state_dict[weight_name] = weight
  46. else:
  47. new_state_dict[weight_name] = weight
  48. new_safetensor_file = os.path.join(bf16_path, file_name)
  49. save_file(new_state_dict, new_safetensor_file)
  50. # Memory management: keep only the 2 most recently used files
  51. if len(loaded_files) > 2:
  52. oldest_file = next(iter(loaded_files))
  53. del loaded_files[oldest_file]
  54. torch.cuda.empty_cache()
  55. # Update model index
  56. new_model_index_file = os.path.join(bf16_path, "model.safetensors.index.json")
  57. for weight_name in fp8_weight_names:
  58. scale_inv_name = f"{weight_name}_scale_inv"
  59. if scale_inv_name in weight_map:
  60. weight_map.pop(scale_inv_name)
  61. with open(new_model_index_file, "w") as f:
  62. json.dump({"metadata": {}, "weight_map": weight_map}, f, indent=2)
  63. if __name__ == "__main__":
  64. parser = ArgumentParser()
  65. parser.add_argument("--input-fp8-hf-path", type=str, required=True)
  66. parser.add_argument("--output-bf16-hf-path", type=str, required=True)
  67. args = parser.parse_args()
  68. main(args.input_fp8_hf_path, args.output_bf16_hf_path)