Skip to content

Commit d346d46

Browse files
Kim-Ju-wonharheem
andauthored
🌐 [i18n-KO] Translated tvp.md to Korean (#39578)
* docs: ko: tvp.md * feat: nmt draft * fix: manual edits * fix: manual edits * fix: manual edits * fix: manual edits * fix: manual edits Co-authored-by: Harheem Kim <[email protected]> --------- Co-authored-by: Harheem Kim <[email protected]>
1 parent 2f59c15 commit d346d46

File tree

2 files changed

+190
-1
lines changed

2 files changed

+190
-1
lines changed

docs/source/ko/_toctree.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1155,4 +1155,4 @@
11551155
- local: in_translation
11561156
title: (번역중)Environment Variables
11571157
title: Reference
1158-
title: API
1158+
title: API

docs/source/ko/model_doc/tvp.md

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
<!--Copyright 2023 The Intel Team Authors and HuggingFace Inc. team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
# TVP [[tvp]]
14+
15+
<div class="flex flex-wrap space-x-1">
16+
<img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white">
17+
</div>
18+
19+
## 개요 [[overview]]
20+
21+
Text-Visual Prompting(TVP) 프레임워크는 Yimeng Zhang, Xin Chen, Jinghan Jia, Sijia Liu, Ke Ding이 발표한 논문 [Text-Visual Prompting for Efficient 2D Temporal Video Grounding](https://huggingface.co/papers/2303.04995)에서 제안되었습니다.
22+
23+
논문의 초록은 다음과 같습니다:
24+
25+
*본 논문에서는 길고, 편집되지 않은 비디오에서 문장으로 설명된 순간의 시작/종료 시점을 예측하는 것을 목표로 하는 Temporal Video Grounding(TVG) 문제를 다룹니다. 세밀한 3D 시각적 특징 덕분에 TVG 기술은 최근 몇 년 동안 놀라운 발전을 이뤘습니다. 하지만 3D 합성곱 신경망(CNN)의 높은 복잡성으로 인해 밀도 높은 3D 시각적 특징을 추출하는 데 시간이 오래 걸리고 그만큼 많은 메모리와 연산 자원을 필요로 합니다. 효율적인 TVG를 위해, 본 논문에서는 TVG 모델의 시각적 입력과 텍스트 특징 모두에 최적화된 교란 패턴('프롬프트'라고 부름)을 통합하는 새로운 Text-Visual Prompting(TVP) 프레임워크를 제안합니다. 3D CNN과 뚜렷이 대비되게 TVP가 2D TVG 모델에서 비전 인코더와 언어 인코더를 효과적으로 공동 학습할 수 있게 하고, 낮은 복잡도의 희소한 2D 시각적 특징만을 사용하여 크로스 모달 특징 융합의 성능을 향상시킵니다. 더 나아가, TVG의 효율적인 학습을 위해 Temporal-Distance IoU(TDIoU) 손실 함수를 제안합니다. 두 개의 벤치마크 데이터 세트인 Charades-STA와 ActivityNet Captions 데이터셋에 대한 실험을 통해, 제안된 TVP가 2D TVG의 성능을 크게 향상시키고(예: Charades-STA에서 9.79% 향상, ActivityNet Captions에서 30.77% 향상) 3D 시각적 특징을 사용하는 TVG에 비해 5배의 추론 가속을 달성함을 실험적으로 입증합니다.*
26+
27+
이 연구는 Temporal Video Grounding(TVG)을 다룹니다. TVG는 문장으로 설명된 특정 이벤트의 시작 및 종료 시점을 긴 비디오에서 정확히 찾아내는 과정입니다. TVG 성능을 향상시키기 위해 Text-Visual Prompting(TVP)이 제안되었습니다. TVP는 '프롬프트'라고 알려진 특별히 설계된 패턴을 TVG 모델의 시각적(이미지 기반) 및 텍스트(단어 기반) 입력 구성 요소 모두에 통합하는 것을 방식입니다. 이 프롬프트는 추가적인 시공간적 컨텍스트를 제공함으로써 모델이 비디오 내 이벤트 시점의 예측 정확도를 높입니다. 이 접근 방식은 3D 시각적 입력 대신 2D 입력을 사용합니다. 3D 입력은 보다 풍부한 시공간적 세부 정보를 제공하지만 처리하는 데 시간이 더 많이 걸립니다. 따라서 프롬프팅 메소드와 함께 2D 입력을 사용하여 이와 유사한 수준의 컨텍스트와 정확도를 더 효율적으로 제공하는 것을 목표로 합니다.
28+
29+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/tvp_architecture.png"
30+
alt="drawing" width="600"/>
31+
32+
<small> TVP 아키텍처. <a href="https://huggingface.co/papers/2303.04995">원본 논문에서 발췌.</a> </small>
33+
34+
이 모델은 [Jiqing Feng](https://huggingface.co/Jiqing)님이 기여했습니다. 원본 코드는 [이 곳](https://github.com/intel/TVP)에서 찾을 수 있습니다.
35+
36+
## 사용 팁 및 예시 [[usage-tips-and-examples]]
37+
38+
프롬프트는 최적화된 교란 패턴으로 입력 비디오 프레임이나 텍스트 특징에 추가되는 패턴입니다. 범용 세트란 모든 입력에 대해 동일한 프롬프트 세트를 사용하는 것을 말합니다. 즉, 입력 내용과 관계없이 모든 비디오 프레임과 텍스트 특징에 이 프롬프트들을 일관적으로 추가합니다.
39+
40+
TVP는 시각 인코더와 크로스 모달 인코더로 구성됩니다. 범용 시각 프롬프트와 텍스트 프롬프트 세트가 각각 샘플링된 비디오 프레임과 텍스트 특징에 통합됩니다. 특히, 서로 다른 시각 프롬프트 세트가 편집되지 않은 한 비디오에서 균일하게 샘플링된 프레임에 순서대로 적용됩니다.
41+
42+
이 모델의 목표는 학습 가능한 프롬프트를 시각적 입력과 텍스트 특징 모두에 통합하여 Temporal Video Grounding(TVG) 문제를 해결하는 것입니다.
43+
44+
원칙적으로, 제안된 아키텍처에는 어떤 시각 인코더나 크로스 모달 인코더라도 적용할 수 있습니다.
45+
46+
[TvpProcessor][BertTokenizer][TvpImageProcessor]를 단일 인스턴스로 래핑하여 텍스트를 인코딩하고 이미지를 각각 준비합니다.
47+
48+
다음 예시는 [TvpProcessor][TvpForVideoGrounding]을 사용하여 TVG를 실행하는 방법을 보여줍니다.
49+
50+
```python
51+
import av
52+
import cv2
53+
import numpy as np
54+
import torch
55+
from huggingface_hub import hf_hub_download
56+
from transformers import AutoProcessor, TvpForVideoGrounding
57+
58+
59+
def pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps):
60+
'''
61+
원본 fps의 비디오를 지정한 fps(target_fps)로 변환하고 PyAV 디코더로 비디오를 디코딩합니다.
62+
Args:
63+
container (container): pyav 컨테이너 객체입니다.
64+
sampling_rate (int): 프레임 샘플링 속도입니다.(샘플링된 두개의 프레임 사이의 간격을 말합니다)
65+
num_frames (int): 샘플링할 프레임 수입니다.
66+
clip_idx (int): clip_idx가 -1이면 시간 축에서 무작위 샘플링을 수행합니다.
67+
clip_idx가 -1보다 크면 비디오를 num_clips 개로 균등 분할한 후
68+
clip_idx번째 비디오 클립을 선택합니다.
69+
num_clips (int): 주어진 비디오에서 균일하게 샘플링할 전체 클립 수입니다.
70+
target_fps (int): 입력 비디오의 fps가 다를 수 있으므로, 샘플링 전에
71+
지정한 fps로 변환합니다
72+
Returns:
73+
frames (tensor): 비디오에서 디코딩된 프레임입니다. 비디오 스트림을 찾을 수 없는 경우
74+
None을 반환합니다.
75+
fps (float): 비디오의 초당 프레임 수입니다.
76+
'''
77+
video = container.streams.video[0]
78+
fps = float(video.average_rate)
79+
clip_size = sampling_rate * num_frames / target_fps * fps
80+
delta = max(num_frames - clip_size, 0)
81+
start_idx = delta * clip_idx / num_clips
82+
end_idx = start_idx + clip_size - 1
83+
timebase = video.duration / num_frames
84+
video_start_pts = int(start_idx * timebase)
85+
video_end_pts = int(end_idx * timebase)
86+
seek_offset = max(video_start_pts - 1024, 0)
87+
container.seek(seek_offset, any_frame=False, backward=True, stream=video)
88+
frames = {}
89+
for frame in container.decode(video=0):
90+
if frame.pts < video_start_pts:
91+
continue
92+
frames[frame.pts] = frame
93+
if frame.pts > video_end_pts:
94+
break
95+
frames = [frames[pts] for pts in sorted(frames)]
96+
return frames, fps
97+
98+
99+
def decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps):
100+
'''
101+
비디오를 디코딩하고 시간 축 샘플링을 수행합니다.
102+
Args:
103+
container (container): pyav 컨테이너 객체입니다.
104+
sampling_rate (int): 프레임 샘플링 속도입니다.(샘플링된 두개의 프레임 사이의 간격을 말합니다)
105+
num_frames (int): 샘플링할 프레임 수입니다.
106+
clip_idx (int): clip_idx가 -1이면 시간 축에서 무작위 샘플링을 수행합니다.
107+
clip_idx가 -1보다 크면 비디오를 num_clips 개로 균등 분할한 후
108+
clip_idx번째 비디오 클립을 선택합니다.
109+
num_clips (int): 주어진 비디오에서 균일하게 샘플링할 전체 클립 수입니다.
110+
target_fps (int): 입력 비디오의 fps가 다를 수 있으므로, 샘플링 전에
111+
지정한 fps로 변환합니다
112+
Returns:
113+
frames (tensor): 비디오에서 디코딩된 프레임입니다.
114+
'''
115+
assert clip_idx >= -2, "Not a valid clip_idx {}".format(clip_idx)
116+
frames, fps = pyav_decode(container, sampling_rate, num_frames, clip_idx, num_clips, target_fps)
117+
clip_size = sampling_rate * num_frames / target_fps * fps
118+
index = np.linspace(0, clip_size - 1, num_frames)
119+
index = np.clip(index, 0, len(frames) - 1).astype(np.int64)
120+
frames = np.array([frames[idx].to_rgb().to_ndarray() for idx in index])
121+
frames = frames.transpose(0, 3, 1, 2)
122+
return frames
123+
124+
125+
file = hf_hub_download(repo_id="Intel/tvp_demo", filename="AK2KG.mp4", repo_type="dataset")
126+
model = TvpForVideoGrounding.from_pretrained("Intel/tvp-base")
127+
128+
decoder_kwargs = dict(
129+
container=av.open(file, metadata_errors="ignore"),
130+
sampling_rate=1,
131+
num_frames=model.config.num_frames,
132+
clip_idx=0,
133+
num_clips=1,
134+
target_fps=3,
135+
)
136+
raw_sampled_frms = decode(**decoder_kwargs)
137+
138+
text = "a person is sitting on a bed."
139+
processor = AutoProcessor.from_pretrained("Intel/tvp-base")
140+
model_inputs = processor(
141+
text=[text], videos=list(raw_sampled_frms), return_tensors="pt", max_text_length=100#, size=size
142+
)
143+
144+
model_inputs["pixel_values"] = model_inputs["pixel_values"].to(model.dtype)
145+
output = model(**model_inputs)
146+
147+
def get_video_duration(filename):
148+
cap = cv2.VideoCapture(filename)
149+
if cap.isOpened():
150+
rate = cap.get(5)
151+
frame_num = cap.get(7)
152+
duration = frame_num/rate
153+
return duration
154+
return -1
155+
156+
duration = get_video_duration(file)
157+
start, end = processor.post_process_video_grounding(output.logits, duration)
158+
159+
print(f"The time slot of the video corresponding to the text \"{text}\" is from {start}s to {end}s")
160+
```
161+
162+
팁:
163+
- 이 TVP 구현은 텍스트 임베딩을 생성하기 위해 [BertTokenizer]를 사용하고, 시각적 임베딩을 계산하기 위해 Resnet-50 모델을 사용합니다.
164+
- 사전 학습된 [tvp-base](https://huggingface.co/Intel/tvp-base)의 체크포인트가 공개되어 있습니다.
165+
- 시간적 비디오 그라운딩 작업에 대한 TVP의 성능은 [표 2](https://huggingface.co/papers/2303.04995)를 참고하세요.
166+
167+
## TvpConfig [[transformers.TvpConfig]]
168+
169+
[[autodoc]] TvpConfig
170+
171+
## TvpImageProcessor [[transformers.TvpImageProcessor]]
172+
173+
[[autodoc]] TvpImageProcessor
174+
- preprocess
175+
176+
## TvpProcessor [[transformers.TvpProcessor]]
177+
178+
[[autodoc]] TvpProcessor
179+
- __call__
180+
181+
## TvpModel [[transformers.TvpModel]]
182+
183+
[[autodoc]] TvpModel
184+
- forward
185+
186+
## TvpForVideoGrounding [[transformers.TvpForVideoGrounding]]
187+
188+
[[autodoc]] TvpForVideoGrounding
189+
- forward

0 commit comments

Comments
 (0)