charsin commited on
Commit
3d2ff6a
·
verified ·
1 Parent(s): 2edd45c

Upload test_fun.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test_fun.py +150 -0
test_fun.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ warnings.filterwarnings("ignore", category=FutureWarning)
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import time
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from decord import VideoReader
13
+ from transformers import AutoModel, AutoVideoProcessor
14
+
15
+ import src.datasets.utils.video.transforms as video_transforms
16
+ import src.datasets.utils.video.volume_transforms as volume_transforms
17
+ from src.models.attentive_pooler import AttentiveClassifier
18
+ from src.models.vision_transformer import vit_giant_xformers_rope, vit_base
19
+
20
+ IMAGENET_DEFAULT_MEAN = (0.485, 0.456, 0.406)
21
+ IMAGENET_DEFAULT_STD = (0.229, 0.224, 0.225)
22
+
23
+
24
+ def load_pretrained_vjepa_pt_weights(model, pretrained_weights):
25
+ # Load weights of the VJEPA2 encoder
26
+ # The PyTorch state_dict is already preprocessed to have the right key names
27
+ pretrained_dict = torch.load(pretrained_weights, weights_only=True, map_location="cpu")["encoder"]
28
+ pretrained_dict = {k.replace("module.", ""): v for k, v in pretrained_dict.items()}
29
+ pretrained_dict = {k.replace("backbone.", ""): v for k, v in pretrained_dict.items()}
30
+ msg = model.load_state_dict(pretrained_dict, strict=False)
31
+ print("Pretrained weights found at {} and loaded with msg: {}".format(pretrained_weights, msg))
32
+
33
+
34
+ def build_pt_video_transform(img_size):
35
+ short_side_size = int(256.0 / 224 * img_size)
36
+ # Eval transform has no random cropping nor flip
37
+ eval_transform = video_transforms.Compose(
38
+ [
39
+ video_transforms.Resize(short_side_size, interpolation="bilinear"),
40
+ video_transforms.CenterCrop(size=(img_size, img_size)),
41
+ volume_transforms.ClipToTensor(),
42
+ video_transforms.Normalize(mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD),
43
+ ]
44
+ )
45
+ return eval_transform
46
+
47
+
48
+ def get_video(sample_video_path, num_frames=80):
49
+ vr = VideoReader(sample_video_path)
50
+ total_frames = len(vr)
51
+ # Choose evenly spaced frames, limited by available frames
52
+ if total_frames < num_frames:
53
+ frame_idx = np.arange(0, total_frames, 2)
54
+ else:
55
+ frame_idx = np.linspace(0, total_frames - 1, num_frames, dtype=int)
56
+ video = vr.get_batch(frame_idx).asnumpy()
57
+ return video
58
+
59
+
60
+ def forward_vjepa_video(model_pt, pt_transform, sample_video_path):
61
+ # Run a sample inference with VJEPA
62
+ with torch.inference_mode():
63
+ # Read and pre-process the image
64
+ video = get_video(sample_video_path) # T x H x W x C
65
+ video = torch.from_numpy(video).permute(0, 3, 1, 2) # T x C x H x W
66
+ print(video.shape)
67
+ x_pt = pt_transform(video)[0].cuda().unsqueeze(0)
68
+ print(x_pt.shape)
69
+ # Extract the patch-wise features from the last layer
70
+ out_patch_features_pt = model_pt(x_pt)
71
+
72
+ return out_patch_features_pt
73
+
74
+
75
+
76
+ def run_single_sample_inference():
77
+ # sample_video_path = "/mnt/data2/tzx/workspace/auto/pipeline/drivelaw/data/escape_data/danger_8hz/FR/FR_ARCF004_20221029151346.mp4"
78
+ sample_video_path = "/workspace/vjepa/videos/-WH-lxmGJVY_000005_000015.mp4"
79
+
80
+ encoder, predictor = torch.hub.load('/workspace/vjepa', 'vjepa2_1_vit_giant_384', source='local')
81
+ encoder.cuda().eval()
82
+
83
+ hf_transform = torch.hub.load('/workspace/vjepa', 'vjepa2_preprocessor', source='local')
84
+ print('Successfully loaded VJEPA2 model and preprocessor from local PyTorch Hub.')
85
+ # Inference on video
86
+ out_patch_features_pt = forward_vjepa_video(
87
+ encoder, hf_transform, sample_video_path
88
+ )
89
+
90
+ print(
91
+ f"""
92
+ Inference results on video:
93
+ PyTorch output shape: {out_patch_features_pt.shape}
94
+ """
95
+ )
96
+
97
+
98
+ def load_and_transform(video_path, pt_transform, num_frames=80):
99
+ # 读取并统一采样为 num_frames(或尽量接近)
100
+ vr = VideoReader(video_path)
101
+ total_frames = len(vr)
102
+ if total_frames < num_frames:
103
+ frame_idx = np.arange(0, total_frames, max(1, total_frames // num_frames))
104
+ else:
105
+ frame_idx = np.linspace(0, total_frames - 1, num_frames, dtype=int)
106
+ video = vr.get_batch(frame_idx).asnumpy() # T x H x W x C
107
+ video = torch.from_numpy(video).permute(0, 3, 1, 2) # T x C x H x W
108
+ # pt_transform 返回 list(可能多视角),取第一个视图(或根据需要修改)
109
+ tensor = pt_transform(video)[0] # C x T x H x W
110
+ return tensor
111
+
112
+ def forward_vjepa_multiview(encoder, pt_transform, video_paths, num_frames=80):
113
+ """
114
+ video_paths: list of paths, e.g. [FR, LF, RF]
115
+ 返回 encoder 输出(每个视角一个条目)
116
+ """
117
+ with torch.inference_mode():
118
+ views = []
119
+ for p in video_paths:
120
+ t = load_and_transform(p, pt_transform, num_frames=num_frames)
121
+ views.append(t)
122
+ # 堆叠为 batch: (V, C, T, H, W)
123
+ views = torch.stack(views, dim=0).cuda()
124
+ encoder = encoder.cuda()
125
+ encoder.eval()
126
+ out = encoder(views) # encoder 接受 B x C x T x H x W
127
+ return out
128
+
129
+ def run_multi_sample_inference():
130
+ FR_video_path = "/mnt/data2/tzx/workspace/auto/pipeline/drivelaw/data/escape_data/danger_8hz/FR/FR_ARCF004_20221029151346.mp4"
131
+ LF_video_path = "/mnt/data2/tzx/workspace/auto/pipeline/drivelaw/data/escape_data/danger_8hz/LF/LF_ARCF004_20221029151346.mp4"
132
+ RF_video_path = "/mnt/data2/tzx/workspace/auto/pipeline/drivelaw/data/escape_data/danger_8hz/RF/RF_ARCF004_20221029151346.mp4"
133
+
134
+ # 从本地 hub 加载(返回 encoder, predictor)
135
+ encoder, predictor = torch.hub.load('/workspace/vjepa', 'vjepa2_1_vit_base_384', source='local')
136
+ print('Successfully loaded encoder and predictor from local hub.')
137
+
138
+ # 预处理:用 hub 提供的 preprocessor 获取 crop size,然后构建 PT transform
139
+ hf_transform = torch.hub.load('/workspace/vjepa', 'vjepa2_preprocessor', source='local')
140
+
141
+ # 三视角一起推理
142
+ video_paths = [LF_video_path, FR_video_path, RF_video_path]
143
+ out = forward_vjepa_multiview(encoder, hf_transform, video_paths, num_frames=80)
144
+
145
+ print(f"Encoder output for {len(video_paths)} views: {out.shape}")
146
+
147
+
148
+ if __name__ == "__main__":
149
+ # Run with: `python -m notebooks.vjepa2_demo`
150
+ run_single_sample_inference()