ChenHe727 commited on
Commit
9f3b6d6
·
verified ·
1 Parent(s): dece54c

Upload pruned_rebuild.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. pruned_rebuild.py +264 -0
pruned_rebuild.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ 从 safetensors + config.json 精确重建剪枝后的 UNet 结构。
4
+
5
+ 关键思路:
6
+ 不使用 align_tensor 填充零值(会污染已学习的权重)。
7
+ 而是先把标准 UNet 里的每个 Conv2d/Linear 替换为 safetensors
8
+ 中实际形状对应的新模块,再用 load_state_dict 加载。
9
+ """
10
+
11
+ import os
12
+ import sys
13
+ import json
14
+ import torch
15
+ import torch.nn as nn
16
+ from safetensors.torch import load_file
17
+
18
+ sys.path.insert(0, '/home/ubuntu')
19
+
20
+ os.environ.update({
21
+ 'HF_HOME': '/opt/dlami/nvme/hf_cache',
22
+ 'TRANSFORMERS_CACHE': '/opt/dlami/nvme/hf_cache',
23
+ 'TMPDIR': '/opt/dlami/nvme/tmp'
24
+ })
25
+
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # 核心:从 safetensors + config.json 重建剪枝模型
29
+ # ---------------------------------------------------------------------------
30
+
31
+ def _get_parent_and_attr(model: nn.Module, dotted_name: str):
32
+ """返回 (parent_module, attr_name),用于 setattr 替换子模块。"""
33
+ parts = dotted_name.split('.')
34
+ obj = model
35
+ for p in parts[:-1]:
36
+ obj = getattr(obj, p)
37
+ return obj, parts[-1]
38
+
39
+
40
+ def _find_num_groups(original_num_groups: int, new_num_channels: int) -> int:
41
+ """找到能整除 new_num_channels 的最大 num_groups(不超过 original_num_groups)。"""
42
+ ng = original_num_groups
43
+ while ng > 1:
44
+ if new_num_channels % ng == 0:
45
+ return ng
46
+ ng //= 2
47
+ return 1
48
+
49
+
50
+ def _replace_layers_to_match_shapes(unet: nn.Module, st: dict) -> int:
51
+ """
52
+ 遍历 unet 所有 Conv2d / Linear / GroupNorm,
53
+ 若 safetensors 中对应权重形状不同,则替换为正确尺寸的新模块。
54
+ 返回替换的层数量。
55
+ """
56
+ replaced = 0
57
+ for name, module in list(unet.named_modules()):
58
+ weight_key = name + '.weight'
59
+ if weight_key not in st:
60
+ continue
61
+
62
+ w = st[weight_key]
63
+ has_bias = (name + '.bias') in st
64
+
65
+ if isinstance(module, nn.Conv2d):
66
+ out_c, in_c = w.shape[0], w.shape[1]
67
+ if out_c != module.out_channels or in_c != module.in_channels:
68
+ new_mod = nn.Conv2d(
69
+ in_c, out_c,
70
+ kernel_size=module.kernel_size,
71
+ stride=module.stride,
72
+ padding=module.padding,
73
+ dilation=module.dilation,
74
+ groups=module.groups,
75
+ bias=has_bias,
76
+ )
77
+ parent, attr = _get_parent_and_attr(unet, name)
78
+ setattr(parent, attr, new_mod)
79
+ replaced += 1
80
+
81
+ elif isinstance(module, nn.Linear):
82
+ out_f, in_f = w.shape[0], w.shape[1]
83
+ if out_f != module.out_features or in_f != module.in_features:
84
+ new_mod = nn.Linear(in_f, out_f, bias=has_bias)
85
+ parent, attr = _get_parent_and_attr(unet, name)
86
+ setattr(parent, attr, new_mod)
87
+ replaced += 1
88
+
89
+ elif isinstance(module, nn.GroupNorm):
90
+ new_num_ch = w.shape[0]
91
+ if new_num_ch != module.num_channels:
92
+ ng = _find_num_groups(module.num_groups, new_num_ch)
93
+ new_mod = nn.GroupNorm(ng, new_num_ch, eps=module.eps, affine=module.affine)
94
+ parent, attr = _get_parent_and_attr(unet, name)
95
+ setattr(parent, attr, new_mod)
96
+ replaced += 1
97
+
98
+ elif isinstance(module, nn.LayerNorm):
99
+ # transformer_blocks.*.norm1/2/3 使用 LayerNorm,normalized_shape=[dim]
100
+ new_dim = w.shape[0]
101
+ if list(module.normalized_shape) != [new_dim]:
102
+ new_mod = nn.LayerNorm(new_dim, eps=module.eps, elementwise_affine=module.elementwise_affine)
103
+ parent, attr = _get_parent_and_attr(unet, name)
104
+ setattr(parent, attr, new_mod)
105
+ replaced += 1
106
+
107
+ return replaced
108
+
109
+
110
+ def _fix_internal_attrs(unet: nn.Module):
111
+ """
112
+ 更新 diffusers UNet 内部依赖于通道数的属性
113
+ (Upsample2D.channels、ResnetBlock2D.in_channels 等)。
114
+ """
115
+ for name, module in unet.named_modules():
116
+ if hasattr(module, 'channels') and hasattr(module, 'conv'):
117
+ if hasattr(module.conv, 'in_channels'):
118
+ module.channels = module.conv.in_channels
119
+ if hasattr(module, 'in_channels') and hasattr(module, 'conv1'):
120
+ if hasattr(module.conv1, 'in_channels'):
121
+ module.in_channels = module.conv1.in_channels
122
+ if hasattr(module, 'out_channels') and hasattr(module, 'conv2'):
123
+ if hasattr(module.conv2, 'out_channels'):
124
+ module.out_channels = module.conv2.out_channels
125
+ if hasattr(module, 'to_q') and hasattr(module, 'inner_dim'):
126
+ if hasattr(module.to_q, 'weight'):
127
+ new_inner_dim = module.to_q.weight.shape[0]
128
+ old_inner_dim = module.inner_dim
129
+ module.inner_dim = new_inner_dim
130
+ if hasattr(module, 'inner_kv_dim'):
131
+ module.inner_kv_dim = new_inner_dim
132
+ # Update heads: head_dim is invariant, recompute heads count
133
+ if hasattr(module, 'heads') and module.heads > 0 and old_inner_dim > 0:
134
+ head_dim = old_inner_dim // module.heads
135
+ if head_dim > 0 and new_inner_dim % head_dim == 0:
136
+ module.heads = new_inner_dim // head_dim
137
+ if hasattr(module, 'sliceable_head_dim'):
138
+ module.sliceable_head_dim = module.heads
139
+
140
+
141
+ def create_unet_from_safetensors(safetensors_path: str, config_path: str = None) -> nn.Module:
142
+ """
143
+ 从 safetensors + config.json 精确重建剪枝后的 UNet。
144
+
145
+ 流程:
146
+ 1. 加载 safetensors(获取实际张量形状)
147
+ 2. 从 config_path 中的 model_config 构建标准 UNet
148
+ 3. 将形状不匹配的 Conv2d/Linear 替换为正确尺寸
149
+ 4. load_state_dict
150
+ 5. 修复内部属性
151
+ """
152
+ from diffusers import UNet2DConditionModel
153
+
154
+ # 1. 加载 safetensors
155
+ print(f"加载 safetensors: {safetensors_path}")
156
+ st = load_file(safetensors_path)
157
+ total_params = sum(v.numel() for v in st.values())
158
+ print(f" safetensors 共 {len(st)} 个张量,{total_params/1e6:.1f}M 参数")
159
+
160
+ # 2. 读取 model_config
161
+ if config_path is None:
162
+ config_path = safetensors_path.replace('.safetensors', '.config.json')
163
+
164
+ model_config = None
165
+ if os.path.exists(config_path):
166
+ with open(config_path, 'r', encoding='utf-8') as f:
167
+ meta = json.load(f)
168
+ model_config = meta.get('model_config')
169
+ print(f" 读取配置: {config_path}")
170
+
171
+ # 回退到默认 SD 1.5 配置
172
+ if not model_config or not isinstance(model_config, dict):
173
+ print(" ⚠️ 未找到 model_config,使用 SD 1.5 默认配置")
174
+ model_config = {
175
+ "sample_size": 64,
176
+ "in_channels": 4,
177
+ "out_channels": 4,
178
+ "layers_per_block": 2,
179
+ "block_out_channels": [320, 640, 1280, 1280],
180
+ "down_block_types": [
181
+ "CrossAttnDownBlock2D", "CrossAttnDownBlock2D",
182
+ "CrossAttnDownBlock2D", "DownBlock2D"
183
+ ],
184
+ "up_block_types": [
185
+ "UpBlock2D", "CrossAttnUpBlock2D",
186
+ "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"
187
+ ],
188
+ "cross_attention_dim": 768,
189
+ "attention_head_dim": 8,
190
+ }
191
+
192
+ # 3. 构建标准 UNet
193
+ print(" 构建标准 UNet 架构...")
194
+ unet = UNet2DConditionModel(**model_config)
195
+
196
+ # 4. 将形状不匹配的层替换为正确尺寸
197
+ replaced = _replace_layers_to_match_shapes(unet, st)
198
+ print(f" 替换了 {replaced} 个形状不匹配的层")
199
+
200
+ # 5. 加载 safetensors 权重
201
+ missing, unexpected = unet.load_state_dict(st, strict=False)
202
+ if missing:
203
+ print(f" ⚠️ 缺失键: {len(missing)} 个(例如 {missing[:3]})")
204
+ if unexpected:
205
+ print(f" ⚠️ 多余键: {len(unexpected)} 个")
206
+
207
+ # 6. 修复内部属性
208
+ _fix_internal_attrs(unet)
209
+
210
+ param_count = sum(p.numel() for p in unet.parameters())
211
+ print(f" ✅ 重建完成,参数量: {param_count/1e6:.1f}M")
212
+ return unet
213
+
214
+
215
+ # ---------------------------------------------------------------------------
216
+ # 验证:前向推理测试
217
+ # ---------------------------------------------------------------------------
218
+
219
+ def verify_forward(unet: nn.Module, device: str = 'cpu') -> bool:
220
+ """对重建的模型跑一次前向推理,验证输出形状正确。"""
221
+ unet = unet.to(device).eval()
222
+ with torch.no_grad():
223
+ sample = torch.randn(1, 4, 64, 64, device=device)
224
+ timestep = torch.tensor([1], device=device)
225
+ enc_hs = torch.randn(1, 77, 768, device=device)
226
+ try:
227
+ out = unet(sample, timestep, encoder_hidden_states=enc_hs)
228
+ assert tuple(out.sample.shape) == (1, 4, 64, 64), \
229
+ f"输出形状异常: {out.sample.shape}"
230
+ print(f" 前向推理 OK,输出形状: {tuple(out.sample.shape)}")
231
+ return True
232
+ except Exception as e:
233
+ print(f" ❌ 前向推理失败: {e}")
234
+ import traceback
235
+ traceback.print_exc()
236
+ return False
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # 主入口
241
+ # ---------------------------------------------------------------------------
242
+
243
+ def main():
244
+ safetensors_path = os.environ.get(
245
+ 'PRUNED_SAFETENS_PATH',
246
+ '/opt/dlami/nvme/prune_outputs/taylor_sp_unet_v2.safetensors'
247
+ )
248
+ config_path = safetensors_path.replace('.safetensors', '.config.json')
249
+
250
+ print("=" * 60)
251
+ print("从 safetensors + config.json 重建剪枝 UNet")
252
+ print("=" * 60)
253
+
254
+ unet = create_unet_from_safetensors(safetensors_path, config_path)
255
+ ok = verify_forward(unet)
256
+
257
+ if ok:
258
+ print("\n✅ 模型重建成功,可直接用于推理/蒸馏!")
259
+ else:
260
+ print("\n❌ 模型重建后前向推理失败,请检查配置")
261
+
262
+
263
+ if __name__ == '__main__':
264
+ main()