Kaeya commited on
Commit
9d71531
1 Parent(s): bd6f687

Upload safetensors_converter.py

Browse files
Files changed (1) hide show
  1. safetensors_converter.py +50 -0
safetensors_converter.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ import torch
5
+ from safetensors.torch import save_file
6
+
7
+
8
+ def convert(path: Path):
9
+ state_dict = torch.load(path, map_location="cpu")
10
+ if "state_dict" in state_dict:
11
+ state_dict = state_dict["state_dict"]
12
+
13
+ to_remove = []
14
+ for k, v in state_dict.items():
15
+ if not isinstance(v, torch.Tensor):
16
+ to_remove.append(k)
17
+ for k in to_remove:
18
+ del state_dict[k]
19
+
20
+ output_path = path.with_suffix(".safetensors").as_posix()
21
+ save_file(state_dict, output_path)
22
+
23
+
24
+ def main(path: str):
25
+ path_ = Path(path).resolve()
26
+
27
+ if not path_.exists():
28
+ raise ValueError(f"Invalid path: {path}")
29
+
30
+ if path_.is_file():
31
+ to_convert = [path_]
32
+ else:
33
+ to_convert = list(path_.glob("*.ckpt"))
34
+
35
+ for file in to_convert:
36
+ if file.with_suffix(".safetensors").exists():
37
+ continue
38
+ print(f"Converting... {file}")
39
+ convert(file)
40
+
41
+
42
+ def parse_args():
43
+ parser = argparse.ArgumentParser()
44
+ parser.add_argument("path", type=str, help="Path to checkpoint file or directory.")
45
+ return parser.parse_args()
46
+
47
+
48
+ if __name__ == "__main__":
49
+ args = parse_args()
50
+ main(args.path)