Spaces:
Paused
Paused
File size: 8,128 Bytes
598d165 |
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 |
import torch
from transformers import TextStreamer
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "Evaluation"))
from llava.constants import IMAGE_TOKEN_INDEX
from llava.conversation import conv_templates, SeparatorStyle
from llava.mm_utils import get_model_name_from_path, KeywordsStoppingCriteria, tokenizer_image_token
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
import shutil
# <a href="https://github.com/SNUMPR/vlm-rlaif.git" style="margin-right: 20px; text-decoration: none; display: flex; align-items: center;">
# <img src="https://z1.ax1x.com/2023/11/07/pil4sqH.png" alt="VLM-RLAIF" style="max-width: 120px; height: auto;">
# </a>
cur_dir = os.path.dirname(os.path.abspath(__file__))
title_markdown = ("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center;">
<img src="/dataset/dcahn/yura/vlm-rlaif/asset/Model.png" alt="VLM-RLAIF" style="max-width: 120px; height: auto;">
<img src="file:/dataset/dcahn/yura/vlm-rlaif/asset/Model.png" alt="VLM-RLAIF" style="max-width: 120px; height: auto;">
<div>
<h1 >VLM-RLAIF: Tuning Large Multimodal Models for Videos using Reinforcement Learning from AI Feedback (ACL 2024 Oral) </h1>
<h5 style="margin: 0;">If you like our project, please give us a star โจ on Github for the latest update.</h5>
</div>
</div>
<div align="center">
<div style="display:flex; gap: 0.25rem;" align="center">
<a href='https://github.com/SNUMPR/vlm-rlaif'><img src='https://img.shields.io/badge/Github-Code-blue'></a>
<a href="https://arxiv.org/abs/2402.03746"><img src="https://img.shields.io/badge/Paper-arxiv-green"></a>
</div>
</div>
""")
# <a href='https://github.com/PKU-YuanGroup/Video-LLaVA/stargazers'><img src='https://img.shields.io/github/stars/PKU-YuanGroup/Video-LLaVA.svg?style=social'></a> # arXiv ๋ฒํผ ์์ ์ถ๊ฐ?
block_css = """
#buttons button {
min-width: min(120px,100%);
}
"""
tos_markdown = ("""
### Terms of use
By using this service, users are required to agree to the following terms:
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
""")
learn_more_markdown = ("""
### License
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
""")
class Chat:
def __init__(self, model_path, conv_mode, model_base=None, load_8bit=False, load_4bit=False, device='cuda', cache_dir=None):
# model_base = '/dataset/yura/vlm-rlaif/pretrained/final_models/Video_LLaVA_SFT'
# model_base='/dataset/yura/vlm-rlaif/pretrained/llava-v1.5-7b-lora_w_lora_16_sftv2_short1632_and_then_long_rank32_alpha32_lr1e4_allmodels/SFT_merged'
# model_path = '/dataset/yura/vlm-rlaif/pretrained/LLaVA_Video-RL-Fact-RLHF-7b_SFTv2_RM_13b_v1_40k-v1.5-336-lora-padding/checkpoint-180/adapter_model/lora_policy'
disable_torch_init()
model_name = get_model_name_from_path(model_path)
# self.tokenizer, self.model, image_processor, context_len = load_pretrained_model(model_path, model_base, model_name,
# load_8bit, load_4bit,
# device=device, cache_dir=cache_dir)
is_rlhf_checkpoint = 'rlhf' in model_path.lower()
print("MODEL_PATH", model_path)
print("RLHF Checkpoint: ", is_rlhf_checkpoint)
if not model_base or model_base == "none": model_base = None
if is_rlhf_checkpoint:
model_name = model_path
print("Config?", os.path.exists(os.path.join(model_path, "config.json")))
if not os.path.exists(os.path.join(model_path, "config.json")):
print("Copying")
shutil.copy(os.path.join(model_base, "config.json"), os.path.join(model_path, "config.json")) # Copy SFT model's config -> to RLHF folder
print("Listed", os.listdir(model_path))
print("Copying done")
# return(model_name)
# return
# self.tokenizer, self.model, image_processor, context_len = load_pretrained_model(model_path, model_base, model_name, load_8bit, load_4bit, device=device)
self.tokenizer, self.model, image_processor, context_len = load_pretrained_model(model_path, model_base, model_name, False, False, device=device)
self.image_processor = image_processor
# self.image_processor = processor['image']
# self.video_processor = processor['video']
self.conv_mode = conv_mode
self.conv = conv_templates[conv_mode].copy()
self.device = self.model.device
print(self.model)
def get_prompt(self, qs, state):
state.append_message(state.roles[0], qs)
state.append_message(state.roles[1], None)
return state
def _get_latest_prompt(self, state):
new_state = state.copy()
new_state.messages = state.messages[-2:]
return new_state
@torch.inference_mode()
# def generate(self, images_tensor: list, prompt: str, first_run: bool, state):
def generate(self, images_tensor: torch.Tensor, prompt: str, first_run: bool, state):
tokenizer, model, image_processor = self.tokenizer, self.model, self.image_processor
state = self.get_prompt(prompt, state)
# prompt = state.get_prompt()
latest_state = self._get_latest_prompt(state)
prompt = latest_state.get_prompt()
# print('\n\n\n')
# print(prompt)
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(self.device)
temperature = 0.2
max_new_tokens = 1024
stop_str = self.conv.sep if self.conv.sep_style != SeparatorStyle.TWO else self.conv.sep2
keywords = [stop_str]
stopping_criteria = KeywordsStoppingCriteria(keywords, tokenizer, input_ids)
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
print(prompt, input_ids.shape, images_tensor.shape)
# print(images_tensor)
with torch.inference_mode():
output_ids = model.generate(
input_ids,
images=images_tensor,
do_sample=True,
temperature=temperature,
max_new_tokens=max_new_tokens,
streamer=streamer,
use_cache=True,
stopping_criteria=[stopping_criteria])
input_token_len = input_ids.shape[1]
n_diff_input_output = (input_ids != output_ids[:, :input_token_len]).sum().item()
if n_diff_input_output > 0:
print(f'[Warning] {n_diff_input_output} output_ids are not the same as the input_ids')
outputs = tokenizer.batch_decode(output_ids[:, input_token_len:], skip_special_tokens=True)[0]
outputs = outputs.strip()
outputs = outputs.replace("QA_GT_caption_based_noisy", "")
if outputs.endswith(stop_str):
outputs = outputs[:-len(stop_str)]
outputs = outputs.strip()
print('response', outputs)
return outputs, state
|