1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
|
#!/usr/bin/env python3
"""
V-JEPA 模型从 Hugging Face 下载、转换和保存脚本(改进版)
支持多种转换模式以满足不同需求
"""
import os
import torch
import requests
from pathlib import Path
from huggingface_hub import hf_hub_download, snapshot_download
from transformers import AutoModel, AutoConfig
import json
from collections import OrderedDict
def setup_directories():
"""创建必要的目录"""
dirs = ['models', 'converted_models', 'checkpoints']
for d in dirs:
Path(d).mkdir(exist_ok=True)
return dirs
def download_vjepa_from_hf(model_name="facebook/vjepa2-vitl-fpc64-256", local_dir="./models"):
"""
从 Hugging Face 下载 V-JEPA 模型
"""
print(f"开始从 Hugging Face 下载 {model_name}...")
try:
# 方法1: 下载整个仓库
local_path = snapshot_download(
repo_id=model_name,
local_dir=local_dir,
local_dir_use_symlinks=False
)
print(f"模型已下载到: {local_path}")
return local_path
except Exception as e:
print(f"下载失败: {e}")
def remove_module_prefix(state_dict):
"""
移除键名中的 'module.' 前缀
"""
new_state_dict = OrderedDict()
for key, value in state_dict.items():
if key.startswith('module.'):
new_key = key[7:] # 移除 'module.'
else:
new_key = key
new_state_dict[new_key] = value
return new_state_dict
def extract_encoder_only(checkpoint):
"""
只提取encoder部分
"""
if 'encoder' in checkpoint:
encoder_state = checkpoint['encoder']
return remove_module_prefix(encoder_state)
else:
# 如果直接是state_dict格式
return remove_module_prefix(checkpoint)
def extract_full_model(checkpoint):
"""
提取完整模型(encoder + predictor)
"""
full_state = OrderedDict()
if 'encoder' in checkpoint:
# 添加encoder
encoder_state = remove_module_prefix(checkpoint['encoder'])
for key, value in encoder_state.items():
full_state[f"encoder.{key}"] = value
# 添加predictor
if 'predictor' in checkpoint:
predictor_state = remove_module_prefix(checkpoint['predictor'])
for key, value in predictor_state.items():
full_state[f"predictor.{key}"] = value
else:
# 如果直接是state_dict格式
full_state = remove_module_prefix(checkpoint)
return full_state
def extract_backbone_only(checkpoint):
"""
只提取backbone部分(不包含预测头)
"""
backbone_state = OrderedDict()
if 'encoder' in checkpoint:
encoder_state = remove_module_prefix(checkpoint['encoder'])
for key, value in encoder_state.items():
if key.startswith('backbone.') and not key.startswith('backbone.predictor'):
new_key = key[9:] # 移除 'backbone.'
backbone_state[new_key] = value
else:
# 如果直接是state_dict格式
state_dict = remove_module_prefix(checkpoint)
for key, value in state_dict.items():
if not key.startswith('predictor') and not key.startswith('head'):
backbone_state[key] = value
return backbone_state
def convert_to_standard_vit(checkpoint):
"""
转换为标准ViT格式
"""
standard_state = OrderedDict()
if 'encoder' in checkpoint:
encoder_state = remove_module_prefix(checkpoint['encoder'])
else:
encoder_state = remove_module_prefix(checkpoint)
# 映射键名到标准ViT格式
key_mapping = {
'backbone.patch_embed.proj.weight': 'patch_embed.projection.weight',
'backbone.patch_embed.proj.bias': 'patch_embed.projection.bias',
'backbone.pos_embed': 'embeddings.position_embeddings',
'backbone.cls_token': 'embeddings.cls_token',
}
for old_key, value in encoder_state.items():
# 处理特殊映射
if old_key in key_mapping:
new_key = key_mapping[old_key]
elif old_key.startswith('backbone.blocks.'):
# 转换注意力和MLP层
new_key = old_key.replace('backbone.blocks.', 'encoder.layer.')
new_key = new_key.replace('.attn.', '.attention.attention.')
new_key = new_key.replace('.mlp.', '.intermediate.')
elif old_key.startswith('backbone.norm.'):
new_key = old_key.replace('backbone.norm.', 'layernorm.')
else:
new_key = old_key
standard_state[new_key] = value
return standard_state
def convert_to_official_format(checkpoint):
"""
转换为官方checkpoint格式,保持完整结构
"""
official_checkpoint = {}
# 如果已经是官方格式,直接返回
if 'encoder' in checkpoint and 'predictor' in checkpoint:
print("检测到已是官方checkpoint格式")
return checkpoint
# 如果是单一state_dict,需要重构为官方格式
if isinstance(checkpoint, dict) and 'encoder' not in checkpoint:
print("转换单一state_dict为官方格式")
# 初始化结构
encoder_state = OrderedDict()
predictor_state = OrderedDict()
for key, value in checkpoint.items():
if 'predictor' in key or 'mask_token' in key:
# 确保有module.backbone前缀
if not key.startswith('module.backbone.'):
new_key = f'module.backbone.{key}'
else:
new_key = key
predictor_state[new_key] = value
else:
# 其他都归类为encoder
if not key.startswith('module.backbone.'):
new_key = f'module.backbone.{key}'
else:
new_key = key
encoder_state[new_key] = value
# 构建官方格式
official_checkpoint['encoder'] = encoder_state
official_checkpoint['predictor'] = predictor_state
official_checkpoint['target_encoder'] = encoder_state.copy() # target_encoder通常是encoder的副本
# 添加训练相关的默认值
official_checkpoint['epoch'] = 0
official_checkpoint['loss'] = 0.0
official_checkpoint['batch_size'] = 1
official_checkpoint['world_size'] = 1
official_checkpoint['lr'] = 0.0001
# 添加空的优化器和scaler状态
official_checkpoint['opt'] = {'state': {}, 'param_groups': []}
official_checkpoint['scaler'] = {
'scale': 1.0,
'growth_factor': 2.0,
'backoff_factor': 0.5,
'growth_interval': 2000,
'_growth_tracker': 0
}
return official_checkpoint
def convert_model_format(input_path, output_path, conversion_mode="official_format"):
"""
转换模型格式
conversion_mode 选项:
- "official_format": 转换为官方checkpoint格式(推荐)
- "encoder_only": 只提取encoder
- "full_model": 提取encoder+predictor
- "backbone_only": 只提取backbone(无预测头)
- "standard_vit": 转换为标准ViT格式
- "raw": 保持原始格式,只去除module前缀
"""
print(f"开始转换模型格式,模式: {conversion_mode}")
try:
# 检查输入路径
if os.path.isdir(input_path):
# 如果是目录,寻找模型文件
possible_files = [
"pytorch_model.bin",
"model.safetensors",
"vitl.pt",
"checkpoint.pth"
]
model_file = None
for f in possible_files:
full_path = os.path.join(input_path, f)
if os.path.exists(full_path):
model_file = full_path
break
if not model_file:
raise FileNotFoundError("在目录中未找到模型文件")
else:
model_file = input_path
print(f"加载模型文件: {model_file}")
# 加载模型
if model_file.endswith('.safetensors'):
from safetensors.torch import load_file
checkpoint = load_file(model_file)
else:
checkpoint = torch.load(model_file, map_location='cpu')
print(f"原始检查点包含 {len(checkpoint)} 个顶层键")
if isinstance(checkpoint, dict):
print(f"顶层键: {list(checkpoint.keys())}")
# 根据转换模式处理
if conversion_mode == "official_format":
# 转换为官方格式
final_checkpoint = convert_to_official_format(checkpoint)
elif conversion_mode == "encoder_only":
final_checkpoint = extract_encoder_only(checkpoint)
elif conversion_mode == "full_model":
final_checkpoint = extract_full_model(checkpoint)
elif conversion_mode == "backbone_only":
final_checkpoint = extract_backbone_only(checkpoint)
elif conversion_mode == "standard_vit":
final_checkpoint = convert_to_standard_vit(checkpoint)
elif conversion_mode == "raw":
if 'encoder' in checkpoint:
final_checkpoint = remove_module_prefix(checkpoint['encoder'])
else:
final_checkpoint = remove_module_prefix(checkpoint)
else:
raise ValueError(f"不支持的转换模式: {conversion_mode}")
# 创建输出目录
Path(output_path).mkdir(exist_ok=True)
# 保存转换后的模型
if conversion_mode == "official_format":
output_file = os.path.join(output_path, 'vjepa_official.pt')
else:
output_file = os.path.join(output_path, f'vjepa_{conversion_mode}.pt')
torch.save(final_checkpoint, output_file)
print(f"模型已保存到: {output_file}")
# 保存模型信息
if conversion_mode == "official_format":
# 对于官方格式,显示详细结构信息
info = {
'original_file': model_file,
'converted_file': output_file,
'conversion_mode': conversion_mode,
'checkpoint_structure': {
'top_level_keys': list(final_checkpoint.keys()),
'encoder_tensors': len(final_checkpoint['encoder']) if 'encoder' in final_checkpoint else 0,
'predictor_tensors': len(final_checkpoint['predictor']) if 'predictor' in final_checkpoint else 0,
'target_encoder_tensors': len(final_checkpoint['target_encoder']) if 'target_encoder' in final_checkpoint else 0
},
'encoder_keys_sample': list(final_checkpoint['encoder'].keys())[:5] if 'encoder' in final_checkpoint else [],
'predictor_keys_sample': list(final_checkpoint['predictor'].keys())[:5] if 'predictor' in final_checkpoint else []
}
else:
# 其他格式的标准信息
if isinstance(final_checkpoint, dict):
num_params = sum(p.numel() for p in final_checkpoint.values() if torch.is_tensor(p))
num_tensors = len([v for v in final_checkpoint.values() if torch.is_tensor(v)])
sample_keys = [k for k, v in final_checkpoint.items() if torch.is_tensor(v)][:10]
else:
num_params = 0
num_tensors = 0
sample_keys = []
info = {
'original_file': model_file,
'converted_file': output_file,
'conversion_mode': conversion_mode,
'num_parameters': num_params,
'num_tensors': num_tensors,
'model_keys_sample': sample_keys
}
info_file = os.path.join(output_path, f'model_info_{conversion_mode}.json')
with open(info_file, 'w', encoding='utf-8') as f:
json.dump(info, f, indent=2, ensure_ascii=False)
print(f"模型信息已保存到: {info_file}")
# 显示转换结果摘要
if conversion_mode == "official_format":
print(f"\n✅ 转换为官方格式成功!")
print(f" 顶层键: {list(final_checkpoint.keys())}")
if 'encoder' in final_checkpoint:
print(f" encoder: {len(final_checkpoint['encoder'])} 个张量")
if 'predictor' in final_checkpoint:
print(f" predictor: {len(final_checkpoint['predictor'])} 个张量")
else:
print(f"转换后包含 {len(final_checkpoint)} 个张量" if isinstance(final_checkpoint, dict) else "转换完成")
return output_file
except Exception as e:
print(f"转换失败: {e}")
import traceback
traceback.print_exc()
return None
def verify_model(model_path):
"""
验证转换后的模型
"""
print(f"\n验证模型: {model_path}")
try:
# 加载模型并检查
checkpoint = torch.load(model_path, map_location='cpu')
# 检查是否为官方checkpoint格式
if isinstance(checkpoint, dict) and 'encoder' in checkpoint:
print("✓ 检测到官方checkpoint格式")
print(f" 顶层键: {list(checkpoint.keys())}")
if 'encoder' in checkpoint:
encoder_keys = len(checkpoint['encoder'])
print(f" encoder: {encoder_keys} 个张量")
# 显示encoder的示例键名
sample_keys = list(checkpoint['encoder'].keys())[:3]
for key in sample_keys:
tensor = checkpoint['encoder'][key]
print(f" {key}: {tensor.shape}")
if 'predictor' in checkpoint:
predictor_keys = len(checkpoint['predictor'])
print(f" predictor: {predictor_keys} 个张量")
if 'target_encoder' in checkpoint:
target_encoder_keys = len(checkpoint['target_encoder'])
print(f" target_encoder: {target_encoder_keys} 个张量")
# 计算总参数量
total_params = 0
for key in ['encoder', 'predictor', 'target_encoder']:
if key in checkpoint:
total_params += sum(p.numel() for p in checkpoint[key].values())
print(f" 总参数量: {total_params:,}")
else:
# 单一state_dict格式
print("✓ 检测到单一state_dict格式")
if isinstance(checkpoint, dict):
state_dict = checkpoint
print(f"模型包含 {len(state_dict)} 个参数张量")
print(f"总参数量: {sum(p.numel() for p in state_dict.values()):,}")
# 显示一些关键信息
print("\n模型结构概览:")
for i, (name, tensor) in enumerate(state_dict.items()):
if i < 10: # 显示前10个
print(f" {name}: {tensor.shape}")
elif i == 10:
print(f" ... 还有 {len(state_dict) - 10} 个张量")
break
# 检查常见的层
key_patterns = ['patch_embed', 'pos_embed', 'blocks', 'norm', 'head']
print("\n层类型分析:")
for pattern in key_patterns:
matching_keys = [k for k in state_dict.keys() if pattern in k.lower()]
if matching_keys:
print(f" {pattern}: {len(matching_keys)} 个相关键")
return True
except Exception as e:
print(f"验证失败: {e}")
return False
def download_via_transformers(model_name="facebook/vjepa2-vitl-fpc64-256", output_dir="./models"):
"""
通过 transformers 库下载 V-JEPA 2 模型
"""
print(f"通过 transformers 下载 {model_name}...")
try:
from transformers import AutoModel, AutoConfig
import torch
# 下载配置和模型
config = AutoConfig.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)
# 保存模型
Path(output_dir).mkdir(exist_ok=True)
output_path = os.path.join(output_dir, "vjepa2_model.pt")
torch.save(model.state_dict(), output_path)
# 保存配置
config_path = os.path.join(output_dir, "config.json")
config.save_pretrained(output_dir)
print(f"模型已保存到: {output_path}")
print(f"配置已保存到: {config_path}")
return output_path
except Exception as e:
print(f"transformers 下载失败: {e}")
return None
def download_via_torch_hub(model_name='vjepa2_vit_large', output_dir="./models"):
"""
通过 torch.hub 下载 V-JEPA 2 模型
"""
print(f"通过 torch.hub 下载 {model_name}...")
try:
import torch
# 下载模型
model = torch.hub.load('facebookresearch/vjepa2', model_name, pretrained=True)
# 保存模型状态字典
Path(output_dir).mkdir(exist_ok=True)
output_path = os.path.join(output_dir, f"{model_name}.pt")
torch.save(model.state_dict(), output_path)
print(f"模型已保存到: {output_path}")
return output_path
except Exception as e:
print(f"torch.hub 下载失败: {e}")
return None
def main():
"""
主函数
"""
print("V-JEPA 2 模型下载转换工具(改进版)")
print("=" * 60)
# 创建目录
setup_directories()
# 方法1: 尝试通过 transformers 下载
print("方法1: 通过 transformers 下载...")
model_path = download_via_transformers()
if not model_path:
# 方法2: 尝试从 Hugging Face Hub 下载
print("\n方法2: 从 Hugging Face Hub 下载...")
model_path = download_vjepa_from_hf()
if not model_path:
# 方法3: 尝试通过 torch.hub 下载
print("\n方法3: 通过 torch.hub 下载...")
model_path = download_via_torch_hub()
if model_path:
print(f"\n成功下载模型到: {model_path}")
# 首先转换为官方格式(主要目标)
print("\n--- 转换为官方checkpoint格式 ---")
converted_path = convert_model_format(model_path, "./converted_models", "official_format")
if converted_path:
if verify_model(converted_path):
print(f"🎉 官方格式转换成功: {converted_path}")
print("✅ 模型已转换为和官方vitg-384.pt相同的格式!")
else:
print("❌ 官方格式验证失败")
else:
print("❌ 官方格式转换失败")
else:
print("\n❌ 所有下载方法都失败")
print("\n备选方案:")
print("1. 手动下载模型文件")
print("2. 使用 convert_local_model() 函数转换本地文件")
def convert_local_model(local_file_path, conversion_mode="official_format"):
"""
转换本地模型文件(支持多种转换模式)
"""
if not os.path.exists(local_file_path):
print(f"文件不存在: {local_file_path}")
return None
setup_directories()
return convert_model_format(local_file_path, "./converted_models", conversion_mode)
def batch_convert_local_model(local_file_path):
"""
批量转换本地模型文件为所有支持的格式
"""
conversion_modes = ["official_format", "encoder_only", "full_model", "backbone_only", "standard_vit", "raw"]
results = {}
for mode in conversion_modes:
print(f"\n--- 转换模式: {mode} ---")
result = convert_local_model(local_file_path, mode)
results[mode] = result
if result and verify_model(result):
print(f"✅ {mode} 模式转换成功")
else:
print(f"❌ {mode} 模式转换失败")
return results
if __name__ == "__main__":
# 可以直接运行主程序
# main()
# 或者转换本地文件(取消注释并修改路径)
# convert_local_model("path/to/your/model.pt", "official_format")
# 或者批量转换所有格式
# batch_convert_local_model("path/to/your/model.pt")
# 显示使用说明
print("🎯 V-JEPA模型下载转换工具")
print("="*50)
print("主要功能: 下载并转换为官方checkpoint格式")
print("\n📖 使用说明:")
print("1. main() - 下载并转换为官方格式")
print("2. convert_local_model(file_path) - 转换本地文件为官方格式")
print("3. convert_local_model(file_path, mode) - 转换为指定格式")
print("4. batch_convert_local_model(file_path) - 批量转换所有格式")
print("\n🔧 转换模式:")
print("- official_format: 转换为官方checkpoint格式 (🎯推荐)")
print("- encoder_only: 只提取encoder部分")
print("- full_model: 提取encoder+predictor")
print("- backbone_only: 只提取backbone(无预测头)")
print("- standard_vit: 转换为标准ViT格式")
print("- raw: 保持原始格式,只去除module前缀")
print("\n💡 快速开始:")
print('# 下载并转换为官方格式')
print('main()')
print('\n# 转换本地文件')
print('convert_local_model("your_model.pt")')
# 自动运行主程序
main()
|