Skip to content

Commit 2864270

Browse files
committed
Based on the existing fake_torch.py, this imports .ckpt files without unpickling them, instead using Fickling to decompile them.
1 parent 31728e2 commit 2864270

File tree

2 files changed

+287
-0
lines changed

2 files changed

+287
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
from no_pickle_fake_torch import extract_weights_from_checkpoint
2+
import json
3+
import numpy as np
4+
from constants import SD_SHAPES, _ALPHAS_CUMPROD
5+
import sys
6+
7+
# python convert_model.py "/Users/divamgupta/Downloads/hollie-mengert.ckpt" "/Users/divamgupta/Downloads/hollie-mengert.tdict"
8+
9+
# pyinstaller convert_model.py --onefile --noconfirm --clean # build using intel machine so that its cross platform lol
10+
11+
checkpoint_filename = sys.argv[1]
12+
out_filename = sys.argv[2]
13+
14+
#TODO add MD5s
15+
16+
_HEADER_BYTES = [42, 10 , 8, 42] + [0]*20
17+
18+
19+
s = 24
20+
21+
torch_weights = extract_weights_from_checkpoint(open(checkpoint_filename, "rb"))
22+
keys_info = {}
23+
out_file = open( out_filename , "wb")
24+
25+
out_file.write(bytes(_HEADER_BYTES))
26+
27+
28+
torch_weights['state_dict']['temb_coefficients_fp32'] = np.array([1.0, 0.94406086, 0.8912509, 0.84139514, 0.7943282, 0.7498942, 0.70794576, 0.6683439, 0.63095737, 0.5956621, 0.56234133, 0.53088444, 0.50118726, 0.47315124, 0.44668362, 0.42169648, 0.39810717, 0.3758374, 0.35481337, 0.33496544, 0.31622776, 0.29853827, 0.2818383, 0.2660725, 0.25118864, 0.23713735, 0.2238721, 0.21134889, 0.19952625, 0.18836491, 0.17782794, 0.16788039, 0.15848932, 0.14962357, 0.14125374, 0.13335215, 0.12589253, 0.11885023, 0.11220184, 0.10592538, 0.099999994, 0.094406076, 0.08912509, 0.0841395, 0.07943282, 0.074989416, 0.07079458, 0.06683439, 0.06309574, 0.05956621, 0.056234125, 0.05308844, 0.05011872, 0.047315124, 0.044668354, 0.04216965, 0.039810725, 0.037583742, 0.035481337, 0.033496536, 0.031622775, 0.029853828, 0.028183822, 0.026607247, 0.025118865, 0.02371374, 0.022387212, 0.021134889, 0.01995262, 0.018836489, 0.017782794, 0.01678804, 0.015848929, 0.014962353, 0.014125377, 0.013335214, 0.012589253, 0.01188502, 0.011220186, 0.010592538, 0.01, 0.009440607, 0.0089125065, 0.008413952, 0.007943282, 0.007498941, 0.007079456, 0.00668344, 0.0063095735, 0.005956621, 0.0056234123, 0.0053088428, 0.005011873, 0.0047315126, 0.0044668354, 0.004216964, 0.003981072, 0.0037583741, 0.0035481334, 0.0033496537, 0.0031622767, 0.0029853827, 0.0028183828, 0.0026607246, 0.0025118857, 0.0023713738, 0.0022387211, 0.0021134887, 0.0019952618, 0.0018836485, 0.0017782794, 0.0016788039, 0.0015848937, 0.001496236, 0.0014125376, 0.0013335207, 0.0012589252, 0.001188502, 0.0011220181, 0.0010592537, 0.0009999999, 0.00094406115, 0.0008912511, 0.0008413952, 0.0007943278, 0.00074989407, 0.0007079456, 0.0006683437, 0.00063095737, 0.0005956621, 0.0005623415, 0.00053088454, 0.0005011872, 0.000473151, 0.00044668352, 0.00042169637, 0.00039810702, 0.0003758374, 0.00035481335, 0.00033496553, 0.00031622782, 0.00029853827, 0.00028183826, 0.00026607246, 0.00025118855, 0.00023713727, 0.00022387199, 0.00021134898, 0.00019952627, 0.00018836492, 0.00017782794, 0.00016788038, 0.00015848929, 0.00014962352, 0.0001412537, 0.00013335208, 0.00012589258, 0.00011885024, 0.00011220186, 0.00010592537]).astype('float32')
29+
torch_weights['state_dict']['causal_mask'] = np.triu(np.ones((1,1,77,77), dtype=np.float16) * -65500.0, k=1).astype(np.float32)
30+
torch_weights['state_dict']['aux_output_conv.weight'] = np.array([0.14013671875, 0.0711669921875, -0.03271484375, -0.11407470703125, 0.126220703125, 0.10101318359375, 0.034515380859375, -0.1383056640625, 0.126220703125, 0.07733154296875, 0.042633056640625, -0.177978515625]).astype(np.float32)
31+
torch_weights['state_dict']['aux_output_conv.bias'] = np.array([0.423828125, 0.471923828125, 0.473876953125]).astype(np.float32)
32+
torch_weights['state_dict']['alphas_cumprod'] = np.array(_ALPHAS_CUMPROD).astype(np.float32)
33+
extra_keys = ['temb_coefficients_fp32' , 'causal_mask' , 'aux_output_conv.weight' , 'aux_output_conv.bias', 'alphas_cumprod']
34+
35+
for k in torch_weights['state_dict']:
36+
if k not in SD_SHAPES and k not in extra_keys:
37+
continue
38+
if 'model_ema' in k:
39+
continue
40+
np_arr = torch_weights['state_dict'][k]
41+
key_bytes = np_arr.tobytes()
42+
shape = list(np_arr.shape)
43+
if k not in extra_keys:
44+
assert tuple(shape) == SD_SHAPES[k], ( "shape mismatch at" , k , shape , SD_SHAPES[k] )
45+
dtype = str(np_arr.dtype)
46+
if dtype == 'int64':
47+
np_arr = np_arr.astype('float32')
48+
dtype = 'float32'
49+
assert dtype in ['float16' , 'float32'] , (dtype, k)
50+
e = s + len(key_bytes)
51+
out_file.write(key_bytes)
52+
keys_info[k] = {"start": s , "end" : e , "shape": shape , "dtype" : dtype }
53+
s = e
54+
55+
for k in SD_SHAPES:
56+
if 'model_ema' in k or 'betas' in k or 'alphas' in k or 'posterior_' in k:
57+
continue
58+
assert k in keys_info , k
59+
60+
json_start = s
61+
info_json = bytes( json.dumps(keys_info) , 'ascii')
62+
json_end = s + len(info_json)
63+
64+
out_file.write(info_json)
65+
66+
out_file.seek(5)
67+
out_file.write(np.array(json_start).astype('long').tobytes())
68+
69+
out_file.seek(14)
70+
out_file.write(np.array(json_end).astype('long').tobytes())
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
import sys
2+
import ast
3+
import re
4+
import numpy as np
5+
import zipfile
6+
from math import prod
7+
from fickling.pickle import Pickled
8+
9+
if sys.version_info >= (3, 9):
10+
from ast import unparse
11+
else:
12+
from astunparse import unparse
13+
14+
15+
def extract_weights_from_checkpoint(fb0):
16+
torch_weights = {}
17+
torch_weights['state_dict'] = {}
18+
with zipfile.ZipFile(fb0, 'r') as myzip:
19+
folder_name = [a for a in myzip.namelist() if a.endswith("/data.pkl")]
20+
if len(folder_name)== 0:
21+
raise ValueError("Looks like the checkpoints file is in the wrong format")
22+
folder_name = folder_name[0].replace("/data.pkl" , "").replace("\\data.pkl" , "")
23+
with myzip.open(folder_name+'/data.pkl') as myfile:
24+
instructions = examine_pickle(myfile)
25+
for sd_key,load_instruction in instructions.items():
26+
with myzip.open(folder_name + f'/data/{load_instruction.obj_key}') as myfile:
27+
if (load_instruction.load_from_file_buffer(myfile)):
28+
torch_weights['state_dict'][sd_key] = load_instruction.get_data()
29+
30+
return torch_weights
31+
32+
def examine_pickle(fb0):
33+
34+
decompiled = unparse(Pickled.load(fb0).ast).splitlines()
35+
## LINES WE CARE ABOUT:
36+
## 1: this defines a data file and what kind of data is in it
37+
## _var1 = _rebuild_tensor_v2(UNPICKLER.persistent_load(('storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
38+
##
39+
## 2: this massive line assigns the previous data to dictionary entries
40+
## _var2262 = {'model.diffusion_model.input_blocks.0.0.weight': _var1, [..... continue for ever]}
41+
##
42+
## 3: this massive line also assigns values to keys, but does so differently
43+
## _var2262.update({ 'cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.bias': _var2001, [ .... and on and on ]})
44+
##
45+
## that's it
46+
# make some REs to match the above.
47+
re_rebuild = re.compile('^_var\d+ = _rebuild_tensor_v2\(UNPICKLER\.persistent_load\(\(.*\)$')
48+
re_assign = re.compile('^_var\d+ = \{.*\}$')
49+
re_update = re.compile('^_var\d+\.update\(\{.*\}\)$')
50+
51+
load_instructions = {}
52+
assign_instructions = AssignInstructions()
53+
54+
for line in decompiled:
55+
## see if line matches pattern of var =
56+
line = line.strip()
57+
if re_rebuild.match(line):
58+
variable_name, load_instruction = line.split(' = ', 1)
59+
load_instructions[variable_name] = LoadInstruction(line)
60+
elif re_assign.match(line):
61+
assign_instructions.parse_assign_line(line)
62+
elif re_update.match(line):
63+
assign_instructions.parse_update_line(line)
64+
#else:
65+
# print('kicking rocks')
66+
67+
print(f"Found {len(load_instructions)} load instructions")
68+
69+
assign_instructions.integrate(load_instructions)
70+
71+
return assign_instructions.integrated_instructions
72+
73+
74+
#output = {}
75+
#output['state_dict'] = {}
76+
77+
class AssignInstructions:
78+
def __init__(self):
79+
self.instructions = {}
80+
self.integrated_instructions = {}
81+
82+
def parse_assign_line(self, line):
83+
# input looks like this:
84+
# _var2262 = {'model.diffusion_model.input_blocks.0.0.weight': _var1, 'model.diffusion_model.input_blocks.0.0.bias': _var3,\
85+
# ...\
86+
# 'cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.weight': _var1999}
87+
garbage, huge_mess = line.split(' = {')
88+
assignments = huge_mess.split(', ')
89+
del huge_mess
90+
assignments[-1] = assignments[-1].strip('}')
91+
for a in assignments:
92+
self._add_assignment(a)
93+
print(f"Added/merged {len(assignments)} assignments. Total of {len(self.instructions)} assignment instructions")
94+
95+
def _add_assignment(self, assignment):
96+
sd_key, fickling_var = assignment.split(': ')
97+
sd_key = sd_key.strip("'")
98+
self.instructions[sd_key] = fickling_var
99+
100+
def integrate(self, load_instructions):
101+
for sd_key, fickling_var in self.instructions.items():
102+
if fickling_var in load_instructions:
103+
self.integrated_instructions[sd_key] = load_instructions[fickling_var]
104+
print(f"Have {len(self.integrated_instructions)} integrated load/assignment instructions")
105+
106+
def parse_update_line(self, line):
107+
# input looks like:
108+
# _var2262.update({'cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.bias': _var2001,\
109+
# 'cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.k_proj.weight': _var2003,\
110+
# ...\
111+
#'cond_stage_model.transformer.text_model.final_layer_norm.bias': _var2261})
112+
garbage, huge_mess = line.split('({')
113+
updates = huge_mess.split(', ')
114+
del huge_mess
115+
updates[-1] = updates[-1].strip('})')
116+
for u in updates:
117+
self._add_assignment(u)
118+
print(f"Added/merged {len(updates)} updates. Total of {len(self.instructions)} assignment instructions")
119+
120+
class LoadInstruction:
121+
def __init__(self, instruction_string):
122+
self.ident = False
123+
self.storage_type = False
124+
self.obj_key = False
125+
self.location = False
126+
self.obj_size = False
127+
self.stride = False #args[3] -- unused, I think
128+
self.data = False;
129+
self.parse_instruction(instruction_string)
130+
131+
def parse_instruction(self, instruction_string):
132+
## this is the API def for _rebuild_tensor_v2:
133+
## _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
134+
#
135+
## sample instruction from decompiled pickle:
136+
# _rebuild_tensor_v2(UNPICKLER.persistent_load(('storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
137+
#
138+
# the following comments will show the output of each string manipulation as if it started with the above.
139+
140+
garbage, storage_etc = instruction_string.split('((', 1)
141+
# storage_etc = 'storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
142+
143+
storage, etc = storage_etc.split('))', 1)
144+
# storage = 'storage', HalfStorage, '0', 'cpu', 11520
145+
# etc = 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
146+
147+
## call below maps to: ('storage', HalfStorage, '0', 'cpu', 11520)
148+
# ident, storage_type, obj_key, location, obj_size = args[0][0:5]
149+
self.ident, self.storage_type, self.obj_key, self.location, self.obj_size = storage.split(', ', 4)
150+
151+
self.ident = self.ident.strip("'")
152+
self.obj_key = self.obj_key.strip("'")
153+
self.location = self.location.strip("'")
154+
self.obj_size = int(self.obj_size)
155+
self.storage_type = self._torch_to_numpy(self.storage_type)
156+
157+
assert (self.ident == 'storage')
158+
159+
garbage, etc = etc.split(', (', 1)
160+
# etc = 320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
161+
162+
size, stride, garbage = etc.split('), ', 2)
163+
# size = 320, 4, 3, 3
164+
# stride = (36, 9, 3, 1
165+
stride = stride.strip('(,')
166+
size = size.strip(',')
167+
168+
169+
if (size == ''):
170+
self.size_tuple = ()
171+
else:
172+
self.size_tuple = tuple(map(int, size.split(', ')))
173+
174+
if (stride == ''):
175+
self.stride = ()
176+
else:
177+
self.stride = tuple(map(int, stride.split(', ')))
178+
179+
prod_size = prod(self.size_tuple)
180+
assert prod(self.size_tuple) == self.obj_size # does the size in the storage call match the size tuple
181+
182+
# zero out the data
183+
self.data = np.zeros(self.size_tuple, dtype=self.storage_type)
184+
185+
@staticmethod
186+
def _torch_to_numpy(storage_type):
187+
if storage_type == 'FloatStorage':
188+
return np.float32
189+
if storage_type == 'HalfStorage':
190+
return np.float16
191+
if storage_type == 'LongStorage':
192+
return np.int64
193+
if storage_type == 'IntStorage':
194+
return np.int32
195+
raise Exception("Storage type not defined!")
196+
197+
198+
def load_from_file_buffer(self, fb):
199+
if self.data.dtype == "object":
200+
print(f"issue assigning object on {self.obj_key}")
201+
return False
202+
else:
203+
#key_prelookup[obj_key] = (storage_type, obj_size, ret, args[2], args[3])
204+
#maps to: where v is the right side of the above assignment
205+
#np.copyto(v[2], np.frombuffer(myfile.read(), v[2].dtype).reshape(v[3]))
206+
#print(f"np.copyto(self.data, np.frombuffer(fb.read(), {self.data.dtype}).reshape({self.size_tuple}))")
207+
np.copyto(self.data, np.frombuffer(fb.read(), self.data.dtype).reshape(self.size_tuple))
208+
return True
209+
210+
def get_data(self):
211+
return self.data
212+
213+
214+
215+
#examine_pickle(open('classicanimation.archive/data.pkl', "rb"))
216+
217+

0 commit comments

Comments
 (0)