|
| 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