-
Notifications
You must be signed in to change notification settings - Fork 27.8k
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
Add GOT-OCR 2.0 to Transformers #34721
Conversation
93b1d19
to
af8035d
Compare
f8e1ac9
to
4007fb2
Compare
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
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.
Seems very clean, congrats! The modular file is a bit verbose still, I left some comments for possible leads to reduce it. Let's make sure slow tests run, otherwise LGTM, and left a couple comments :)
write_tokenizer( | ||
tokenizer_path="qwen.tiktoken", | ||
save_dir=args.output_dir, | ||
instruct=args.instruct, |
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.
Does this model have an instruct
version needed?
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.
Oh I forgot to remove that, thanks. I'd say the model is indeed instruct, but users are not really expected to have conversation with it, and the possible prompt are explicitly defined in the processor so I'm not sure in which categories this model falls and if we should add support for a chat template here.
I'd say it might make sense to add a chat template when and if we end up adding support for fine-tuning, but to me it doesn't make much sense in this state, I might be wrong though.
What do you think @molbap @Ucas-HaoranWei ?
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.
From afar, maybe @Ucas-HaoranWei has a different opinion, I'd just remove the instruct - as you say users are not expected to converse with it. If it's instruct-tuned in a later version, it might make sense, but it's an OCR model as it stands, it sounds confusing to label it as instruct.
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.
Yes, I agree that there should not be a chat template, as they are fixed prompts in this state. @molbap @yonigozlan. If the later versions can be fine-tuned, then the template can be maintained to ensure that users use their new prompts.
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.
Sounds good thank you!
resized_image = image.resize((target_width, target_height)) | ||
|
||
# split the image into patches | ||
processed_images = [] |
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.
these are processed_patches
, rather, yes?
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.
Yes indeed, but the reason I did not rename it that is because we add to it a "thumbnail" image which is the whole image resized
format = output_kwargs["text_kwargs"].pop("format", False) | ||
num_image_tokens = output_kwargs["images_kwargs"].pop("num_image_tokens", 256) | ||
box = output_kwargs["images_kwargs"].pop("box", [None]) | ||
color = output_kwargs["images_kwargs"].pop("color", None) | ||
multi_page = output_kwargs["images_kwargs"].pop("multi_page", False) | ||
crop_to_patches = output_kwargs["images_kwargs"].pop("crop_to_patches", False) |
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.
here we could use the default values that are preset above
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.
Do you mean something like GotOcr2ProcessorKwargs._defaults["images_kwargs"].get("crop_to_patches")
?
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.
yes, for instance! what I mean is the default values in the pop
method should not be specified in two places, because if they change, it's more likely to cause errors/mismatches
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.
That makes sense. I might be missing something, but if we have default kwargs (for multi_page, crop_to_patches, min_patches, max_patches etc.), it seems to me that there shouldn't be any issues with using "pop" without default? if the kwarg is not specified by the user, pop will return the default, and it will return the user-specified value otherwise?
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.
@molbap just pinging you on this last question
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.
Ah, you're right - I guess it's just weird to me to see the default values written in two distinct places, does not seem necessary 🤔
class GotOcr2VisionAdapter(nn.Module): | ||
def __init__(self, language_hidden_size: int, vision_output_channels: int): | ||
super().__init__() | ||
self.conv_up1 = nn.Conv2d( |
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.
I assume up
stands for upsampler like in swin2sr, but a more explicit name would be better
Hey @ArthurZucker
|
7e88dbe
to
df94db3
Compare
HI all -- eager to try this model in transformers in the new year |
pls |
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.
Great work! Thanks for adding different examples to the documentation, this will help others explore the fantastic capabilities of this model! Added some comments regarding image processing and modeling below:
Thanks @qubvel for the review! I have made the requested changes. |
Does GOT OCR support returning the bounding boxes of detected text? Or else I have to go back to PaddleOCR which doesn't work on ZLUDA. |
No GOT OCR doesn't support returning the bounding boxes of detected text. |
6989c07
to
3ae43ec
Compare
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.
Very nice leverage of modular, a few outstanding issues left IMO
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.
super nice !
def _check_call_arguments(self, images, box, color, multi_page, crop_to_patches): | ||
if images is None: | ||
raise ValueError("Images are required to be passed to the processor.") | ||
|
||
if not isinstance(box, (list, tuple)): | ||
raise ValueError("Box must be a list or tuple of lists in the form [x1, y1, x2, y2].") | ||
|
||
if multi_page or crop_to_patches: | ||
if multi_page and crop_to_patches: | ||
raise ValueError("Cannot set both `multi_page` and `crop_to_patches` to `True`.") | ||
if box[0] is not None or color is not None: | ||
raise ValueError("Cannot pass `box` or `color` with multi-page inference.") | ||
|
||
if box[0] is not None and color is not None: | ||
raise ValueError("Both `box` and `color` cannot be set at the same time.") | ||
|
||
def _make_list_of_inputs(self, images, text, box, color, multi_page): | ||
if not isinstance(images, (list, tuple)): | ||
if multi_page: | ||
logger.warning("Multi-page inference is enabled but only one image is passed.") | ||
images = [images] | ||
elif isinstance(images[0], (list, tuple)) and not multi_page: | ||
raise ValueError("Nested images are only supported with `multi_page` set to `True`.") | ||
elif not isinstance(images[0], (list, tuple)) and multi_page: | ||
images = [images] | ||
|
||
if text is not None: | ||
if not isinstance(text, (list, tuple)): | ||
text = [text] | ||
if len(text) != len(images): | ||
raise ValueError("The number of `text` must match the number of images.") | ||
|
||
if not isinstance(box[0], (list, tuple)): | ||
# Use the same box for all images | ||
box = [box for _ in range(len(images))] | ||
if not isinstance(color, (list, tuple)): | ||
color = [color for _ in range(len(images))] | ||
if len(box) != len(images): | ||
raise ValueError("The number of `box` must match the number of images.") | ||
if len(color) != len(images): | ||
raise ValueError("The number of `color` must match the number of images.") | ||
|
||
return images, text, box, color |
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.
really not fan of this, it does not scale, and we do a lot of work for the user when we should be enforcing a single format IMO! See #34726 and why we don't want this
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.
it's good to raise errors, but we need to put more thoughts into how to make our checks readable and find a fine line between enforcing a single input format but at the same time make it easy to use the model.
What are people going to use the model for and how -> most intuitive type of input etc
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.
Yes I see, I've removed all the checks except the ones necessary to batch the inputs
def _check_call_arguments(self, images, box, color, multi_page, crop_to_patches): | ||
if images is None: | ||
raise ValueError("Images are required to be passed to the processor.") | ||
|
||
if not isinstance(box, (list, tuple)): | ||
raise ValueError("Box must be a list or tuple of lists in the form [x1, y1, x2, y2].") | ||
|
||
if multi_page or crop_to_patches: | ||
if multi_page and crop_to_patches: | ||
raise ValueError("Cannot set both `multi_page` and `crop_to_patches` to `True`.") | ||
if box[0] is not None or color is not None: | ||
raise ValueError("Cannot pass `box` or `color` with multi-page inference.") | ||
|
||
if box[0] is not None and color is not None: | ||
raise ValueError("Both `box` and `color` cannot be set at the same time.") | ||
|
||
def _make_list_of_inputs(self, images, text, box, color, multi_page): | ||
if not isinstance(images, (list, tuple)): | ||
if multi_page: | ||
logger.warning("Multi-page inference is enabled but only one image is passed.") | ||
images = [images] | ||
elif isinstance(images[0], (list, tuple)) and not multi_page: | ||
raise ValueError("Nested images are only supported with `multi_page` set to `True`.") | ||
elif not isinstance(images[0], (list, tuple)) and multi_page: | ||
images = [images] | ||
|
||
if text is not None: | ||
if not isinstance(text, (list, tuple)): | ||
text = [text] | ||
if len(text) != len(images): | ||
raise ValueError("The number of `text` must match the number of images.") | ||
|
||
if not isinstance(box[0], (list, tuple)): | ||
# Use the same box for all images | ||
box = [box for _ in range(len(images))] | ||
if not isinstance(color, (list, tuple)): | ||
color = [color for _ in range(len(images))] | ||
if len(box) != len(images): | ||
raise ValueError("The number of `box` must match the number of images.") | ||
if len(color) != len(images): | ||
raise ValueError("The number of `color` must match the number of images.") | ||
|
||
return images, text, box, color |
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.
it's good to raise errors, but we need to put more thoughts into how to make our checks readable and find a fine line between enforcing a single input format but at the same time make it easy to use the model.
What are people going to use the model for and how -> most intuitive type of input etc
prompt = ( | ||
self.message_start_token | ||
+ self.system_query | ||
+ self.message_end_token | ||
+ self.message_start_token | ||
+ "user\n" | ||
+ self.img_start_token | ||
+ self.img_pad_token * num_image_tokens * num_images | ||
+ self.img_end_token | ||
+ "\n" | ||
+ query | ||
+ self.message_end_token | ||
+ self.message_start_token | ||
+ "assistant\n" | ||
) | ||
text.append(prompt) |
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.
is this not <=> to a chat template basically?
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.
This is discussed here: #34721 (comment)
Indeed the model was trained as an instruct model with a chat template, but users are not really expected to converse with it, hence why there's this parametrized query instead of a full chat support.
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.
MUCH much better 😉
|
||
if pixel_values is not None: | ||
image_features = self.get_image_features(pixel_values=pixel_values) | ||
n_image_tokens = (input_ids == self.config.image_token_index).sum().item() |
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.
.item() is not really ideal here
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.
Yes, we might want to remove it from llava as well?
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.
yes!
) -> Union[Tuple, CausalLMOutputWithPast]: | ||
cache_position: Optional[torch.LongTensor] = None, | ||
logits_to_keep: Union[int, torch.Tensor] = 0, | ||
) -> Union[Tuple, LlavaCausalLMOutputWithPast]: |
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.
forward looks like it does not need to be overwritten no>
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.
I overwrote it only because I don't need vision_feature_layer
and vision_feature_select_strategy
…mers into add-got-ocr2
* init modular got_ocr2 * Get correct got_ocr architecture * add processing * run modular with processing * add working inference * apply modular * Refactor and fix style * Refactor, cleanup, fix style * fix init order * Fix docs * add base modeling tests * fix style and consistency * rename doc file * fix repo consistency * fix inference with box * add image processing and support for crop_to_multi_page * Fix batch inference * add tests * fixup * fix slow test * fix docstrings * Add model doc * update to new init * fix input autocast pixel_values dtype * update doc * move doc to multimodal * Reformat crop_image_to_patches and add docstrings * Fix example in forward docstring * Address Pablo review * [run slow] got_ocr2 * remove defaults defined twice * apply modular * add torch_device to integration tests * update modular * follow-up Pavel review * add device variable in doc * fix doc multi-page * Force eager attention for vision encoder to avoid attn implementation conflict * revert qwen2vl doc changes * use Qwen2ForCausalLM instead of Qwen2Model * make fixup * refactor gotocr2 to llava style * uniformize function names and reduce checks * final nits * fix pixel_values dtype error * change checkpoint names * fix modular
* init modular got_ocr2 * Get correct got_ocr architecture * add processing * run modular with processing * add working inference * apply modular * Refactor and fix style * Refactor, cleanup, fix style * fix init order * Fix docs * add base modeling tests * fix style and consistency * rename doc file * fix repo consistency * fix inference with box * add image processing and support for crop_to_multi_page * Fix batch inference * add tests * fixup * fix slow test * fix docstrings * Add model doc * update to new init * fix input autocast pixel_values dtype * update doc * move doc to multimodal * Reformat crop_image_to_patches and add docstrings * Fix example in forward docstring * Address Pablo review * [run slow] got_ocr2 * remove defaults defined twice * apply modular * add torch_device to integration tests * update modular * follow-up Pavel review * add device variable in doc * fix doc multi-page * Force eager attention for vision encoder to avoid attn implementation conflict * revert qwen2vl doc changes * use Qwen2ForCausalLM instead of Qwen2Model * make fixup * refactor gotocr2 to llava style * uniformize function names and reduce checks * final nits * fix pixel_values dtype error * change checkpoint names * fix modular
What does this PR do?
Add GOT-OCR 2.0 to Transformers.
Left TODOs:
Who can review?
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.