-
Notifications
You must be signed in to change notification settings - Fork 2
create new llava_captioning filter #48
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from 8 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
3081f00
create new llava_captioning filter
74a34f7
update llava34b filter
442b4d3
fixed
95ef493
fixed
279b252
finally
a42fd6f
update image_filters_example
6a5e270
llava34b
66ea31f
documentation
8f24527
done
79cdc3a
debug
9ada3d2
tututu
2a0735c
fix
855eebc
fix
6f2c15f
image transformations were replaced
a5a3871
Merge branch 'dev' into dev_alisa
boomb0om File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import re | ||
| from typing import Any | ||
|
|
||
| import torch | ||
| from transformers import LlavaNextForConditionalGeneration, LlavaNextProcessor | ||
|
|
||
| from DPF.filters.images.img_filter import ImageFilter | ||
| from DPF.types import ModalityToDataMapping | ||
| from DPF.utils import read_image_rgb_from_bytes | ||
|
|
||
|
|
||
| class Llava34b_Filter(ImageFilter): | ||
| """ | ||
| The filter implements a description of the images supplied to the input using a model llava-v1.6-34b-hf. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| model_path: str = 'llava-hf/llava-v1.6-34b-hf', | ||
| workers: int = 16, | ||
| batch_size: int = 8, | ||
| device: str = "cuda:0", | ||
| pbar: bool = True, | ||
| crop_size_x: int = 336, | ||
| crop_size_y: int = 336, | ||
| _pbar_position: int = 0 | ||
| ): | ||
| super().__init__(pbar, _pbar_position) | ||
| self.batch_size = batch_size | ||
| self.num_workers = workers | ||
| self.device = device | ||
| self.crop_size_x = crop_size_x | ||
| self.crop_size_y = crop_size_y | ||
| self.prompt = "<|im_start|>system\nAnswer the questions.<|im_end|><|im_start|>user\n<image>\nDescribe this image and its style in a very detailed manner<|im_end|><|im_start|>assistant\n" | ||
| self.processor = LlavaNextProcessor.from_pretrained(model_path) | ||
| self.model = LlavaNextForConditionalGeneration.from_pretrained( | ||
| model_path, | ||
| torch_dtype=torch.float16, | ||
| low_cpu_mem_usage=True, | ||
| attn_implementation="flash_attention_2", | ||
| device_map=self.device | ||
| ) | ||
|
|
||
| @property | ||
| def result_columns(self) -> list[str]: | ||
| return ["llava34b_caption"] | ||
|
|
||
| @property | ||
| def dataloader_kwargs(self) -> dict[str, Any]: | ||
| return { | ||
| "num_workers": self.num_workers, | ||
| "batch_size": self.batch_size, | ||
| "drop_last": False, | ||
| } | ||
|
|
||
| def preprocess_data( | ||
| self, | ||
| modality2data: ModalityToDataMapping, | ||
| metadata: dict[str, Any] | ||
| ) -> Any: | ||
| key = metadata[self.key_column] | ||
| pil_img = read_image_rgb_from_bytes( | ||
| modality2data['image']).convert('RGB') | ||
| width, height = pil_img.size | ||
| left = int((width - self.crop_size_x)/2) | ||
| top = int((height - self.crop_size_y)/2) | ||
| right = int((width + self.crop_size_x)/2) | ||
| bottom = int((height + self.crop_size_y)/2) | ||
| cropped_image = pil_img.crop((left, top, right, bottom)) | ||
| cropped_image = cropped_image.resize( | ||
| (self.crop_size_x, self.crop_size_y)) | ||
| return key, cropped_image | ||
|
|
||
| def process_batch(self, batch: list[Any]) -> dict[str, list[Any]]: | ||
| df_batch_labels = self._get_dict_from_schema() | ||
| keys, images = list(zip(*batch)) | ||
| prompts = [self.prompt for _ in range(self.batch_size)] | ||
| inputs = self.processor(prompts, list( | ||
| images), return_tensors="pt").to(self.device) | ||
| with torch.inference_mode(): | ||
| output_ids = self.model.generate( | ||
| **inputs, max_new_tokens=512, use_cache=True) | ||
|
|
||
| all_outputs = [] | ||
| for i in range(output_ids.shape[0]): | ||
| output = self.processor.decode( | ||
| output_ids[i], skip_special_tokens=True, clean_up_tokenization_spaces=True) | ||
| output = re.sub(r'.*?assistant', '', output, flags=re.DOTALL) | ||
| output = re.sub(r'\n', '', output) | ||
| all_outputs.append(output) | ||
|
|
||
| df_batch_labels[self.schema[1]].extend(all_outputs) | ||
| df_batch_labels[self.key_column].extend(keys) | ||
|
|
||
| return df_batch_labels | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| { | ||
|
||
| "cells": [ | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "ffc1208c", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "from transformers import LlavaNextConfig, LlavaNextProcessor, LlavaNextForConditionalGeneration\n", | ||
| "from DPF import S3Connector, DatasetReader, ShardsDatasetConfig\n", | ||
| "import torch\n", | ||
| "from PIL import Image\n", | ||
| "import requests\n", | ||
| "import csv\n", | ||
| "import requests\n", | ||
| "import os\n", | ||
| "from typing import Any\n", | ||
| "from py3langid.langid import MODEL_FILE, LanguageIdentifier\n", | ||
| "from DPF.filters.images.img_filter import ImageFilter\n", | ||
| "from DPF.types import ModalityToDataMapping\n", | ||
| "\n", | ||
| "class Llava34b_Filter(ImageFilter):\n", | ||
| " \"\"\"\n", | ||
| " The filter implements a description of the images supplied to the input.\n", | ||
| " \"\"\"\n", | ||
| " def __init__(\n", | ||
| " self,\n", | ||
| " model_path: str = 'llava-hf/llava-v1.6-34b-hf',\n", | ||
| " workers: int = 16,\n", | ||
| " batch_size: int = 16,\n", | ||
| " device: str = \"cuda:0\",\n", | ||
| " pbar: bool = True,\n", | ||
| " _pbar_position: int = 0\n", | ||
| " ):\n", | ||
| " super().__init__(pbar, _pbar_position)\n", | ||
| " self.batch_size = batch_size\n", | ||
| " self.num_workers = workers\n", | ||
| " self.device = device\n", | ||
| " self.prompt = \"<|im_start|>system\\nAnswer the questions.<|im_end|><|im_start|>user\\n<image>\\nDescribe this image and its style in a very detailed manner<|im_end|><|im_start|>assistant\\n\"\n", | ||
| " \n", | ||
| " self.processor = LlavaNextProcessor.from_pretrained(\"llava-hf/llava-v1.6-34b-hf\")\n", | ||
| " \n", | ||
| " self.model = LlavaNextForConditionalGeneration.from_pretrained(\n", | ||
| " \"llava-hf/llava-v1.6-34b-hf\",\n", | ||
| " torch_dtype=torch.float16,\n", | ||
| " low_cpu_mem_usage=True,\n", | ||
| " use_flash_attention_2=True,\n", | ||
| " device_map=self.device)\n", | ||
| "\n", | ||
| " @property\n", | ||
| " def result_columns(self) -> list[str]:\n", | ||
| " return [\"llava34b_caption\"]\n", | ||
| "\n", | ||
| " @property\n", | ||
| " def dataloader_kwargs(self) -> dict[str, Any]:\n", | ||
| " return {\n", | ||
| " \"num_workers\": self.num_workers,\n", | ||
| " \"batch_size\": self.batch_size,\n", | ||
| " \"drop_last\": False,\n", | ||
| " }\n", | ||
| "\n", | ||
| " def preprocess_data(\n", | ||
| " self,\n", | ||
| " modality2data: ModalityToDataMapping,\n", | ||
| " metadata: dict[str, Any]\n", | ||
| " ) -> Any:\n", | ||
| " key = metadata[self.key_column]\n", | ||
| " pil_img = read_image_rgb_from_bytes(modality2data['image']).convert('RGB')\n", | ||
| " img_tensor = self.image_processor.preprocess(pil_img, return_tensors='pt')['pixel_values'].half()\n", | ||
| " return key, img_tensor\n", | ||
| "\n", | ||
| " def process_batch(self, batch: list[Any]) -> dict[str, list[Any]]:\n", | ||
| " df_batch_labels = self._get_dict_from_schema()\n", | ||
| "\n", | ||
| " keys, image_tensors = list(zip(*batch))\n", | ||
| " image_tensors = default_collate(image_tensors).to(self.device) # type: ignore\n", | ||
| "\n", | ||
| " input_ids_batch = self.input_ids.repeat_interleave(image_tensors.shape[0], 0).to(self.device) # type: ignore\n", | ||
| " with torch.inference_mode():\n", | ||
| " output_ids = self.model.generate(\n", | ||
| " input_ids_batch, images=image_tensors, do_sample=True, temperature=0.2, top_p=0.7,\n", | ||
| " max_new_tokens=512, use_cache=True, stopping_criteria=[self.stopping_criteria]\n", | ||
| " )\n", | ||
| "\n", | ||
| " all_outputs = []\n", | ||
| " for i in range(output_ids.shape[0]):\n", | ||
| " output = self.tokenizer.decode(output_ids[i, self.input_ids.shape[1]:]).strip().split('</s>')[0]\n", | ||
| " all_outputs.append(output)" | ||
| ] | ||
| } | ||
| ], | ||
| "metadata": { | ||
| "kernelspec": { | ||
| "display_name": "Python [conda env:.mlspace-env3.11]", | ||
| "language": "python", | ||
| "name": "conda-env-.mlspace-env3.11-py" | ||
| }, | ||
| "language_info": { | ||
| "codemirror_mode": { | ||
| "name": "ipython", | ||
| "version": 3 | ||
| }, | ||
| "file_extension": ".py", | ||
| "mimetype": "text/x-python", | ||
| "name": "python", | ||
| "nbconvert_exporter": "python", | ||
| "pygments_lexer": "ipython3", | ||
| "version": "3.11.8" | ||
| } | ||
| }, | ||
| "nbformat": 4, | ||
| "nbformat_minor": 5 | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут только один промпт и он захардкожен в код( Нужно сделать, чтобы его можно было менять. Посмотри как реализовано в ллаве 1.5