-
Notifications
You must be signed in to change notification settings - Fork 3k
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 Text2Image into Taskflow #2988
Merged
guoshengCS
merged 8 commits into
PaddlePaddle:develop
from
JunnYu:add_text2img_taskflow
Aug 10, 2022
Merged
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f6d3a90
add text2image taskflow
JunnYu 1af97f1
update readme
JunnYu 00e8f63
update readme
JunnYu 64625a5
Merge branch 'develop' into add_text2img_taskflow
guoshengCS 088c6d6
Merge branch 'develop' into add_text2img_taskflow
guoshengCS 4b811ad
update text2image taskflow
JunnYu 9543781
Merge branch 'develop' into add_text2img_taskflow
JunnYu b0927e3
Merge branch 'develop' into add_text2img_taskflow
guoshengCS 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 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 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 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,161 @@ | ||
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License" | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import paddle | ||
from PIL import Image | ||
from ..transformers import AutoModelForImageGeneration, AutoTokenizer | ||
from .task import Task | ||
|
||
usage = r""" | ||
from paddlenlp import Taskflow | ||
|
||
text2imagegen = Taskflow("text2image_generation") | ||
images = text2imagegen("风阁水帘今在眼,且来先看早梅红") | ||
images[0].save("figure.png") | ||
|
||
""" | ||
|
||
tokenizer_kwargs = { | ||
"dallebart": { | ||
"max_length": 64, | ||
"return_token_typd_ids": False, | ||
"return_attention_mask": True | ||
}, | ||
"gpt": { | ||
"max_length": 32, | ||
"return_token_typd_ids": False, | ||
"return_attention_mask": False | ||
}, | ||
} | ||
|
||
|
||
class Text2ImageGenerationTask(Task): | ||
""" | ||
The text2image generation model to generate the image. | ||
Args: | ||
task(string): The name of task. | ||
model(string): The model name in the task. | ||
kwargs (dict, optional): Additional keyword arguments passed along to the specific task. | ||
""" | ||
|
||
def __init__(self, task, model="pai-painter-painting-base-zh", **kwargs): | ||
super().__init__(task=task, model=model, **kwargs) | ||
self._batch_size = kwargs.get("batch_size", 1) | ||
self._temperature = kwargs.get("temperature", 1.) | ||
self._top_k = kwargs.get("top_k", 32) | ||
self._top_p = kwargs.get("top_p", 1.) | ||
self._condition_scale = kwargs.get("condition_scale", 10.) | ||
self._num_return_images = kwargs.get("num_return_images", 4) | ||
self._use_faster = kwargs.get("use_faster", False) | ||
self._use_fp16_decoding = kwargs.get("use_fp16_decoding", False) | ||
self._construct_tokenizer(model) | ||
self._construct_model(model) | ||
|
||
def _construct_model(self, model): | ||
""" | ||
Construct the inference model for the predictor. | ||
""" | ||
self._model = AutoModelForImageGeneration.from_pretrained(model) | ||
self._model.eval() | ||
|
||
def _construct_tokenizer(self, model): | ||
""" | ||
Construct the tokenizer for the predictor. | ||
""" | ||
self._tokenizer = AutoTokenizer.from_pretrained(model) | ||
|
||
def _batchify(self, data, batch_size): | ||
""" | ||
Generate input batches. | ||
""" | ||
|
||
def _parse_batch(batch_examples): | ||
tokenizerd_inputs = self._tokenizer( | ||
batch_examples, | ||
return_tensors="pd", | ||
padding="max_length", | ||
truncation=True, | ||
**tokenizer_kwargs[self._model.base_model_prefix]) | ||
if self._model.base_model_prefix == "dallebart": | ||
tokenizerd_inputs["condition_scale"] = self._condition_scale | ||
return tokenizerd_inputs | ||
|
||
# Seperates data into some batches. | ||
one_batch = [] | ||
for example in data: | ||
one_batch.append(example) | ||
if len(one_batch) == batch_size: | ||
yield _parse_batch(one_batch) | ||
one_batch = [] | ||
if one_batch: | ||
yield _parse_batch(one_batch) | ||
|
||
def _preprocess(self, inputs): | ||
""" | ||
Transform the raw text to the model inputs, two steps involved: | ||
1) Transform the raw text to token ids. | ||
2) Generate the other model inputs from the raw text and token ids. | ||
""" | ||
inputs = self._check_input_text(inputs) | ||
batches = self._batchify(inputs, self._batch_size) | ||
outputs = {'batches': batches, 'text': inputs} | ||
return outputs | ||
|
||
def _run_model(self, inputs): | ||
""" | ||
Run the task model from the outputs of the `_preprocess` function. | ||
""" | ||
all_images = [] | ||
|
||
for batch_inputs in inputs["batches"]: | ||
images = self._model.generate( | ||
**batch_inputs, | ||
temperature=self._temperature, | ||
top_k=self._top_k, | ||
top_p=self._top_p, | ||
num_return_sequences=self._num_return_images, | ||
use_faster=self._use_faster, | ||
use_fp16_decoding=self._use_fp16_decoding).cpu().numpy() | ||
if self._model.base_model_prefix == "dallebart": | ||
images = (images.clip(0, 1) * 255).astype("uint8") | ||
elif self._model.base_model_prefix == "gpt": | ||
images = ((images + 1.0) * 127.5).clip(0, 255).astype("uint8") | ||
for image in images: | ||
all_images.append(image) | ||
inputs['images'] = all_images | ||
return inputs | ||
|
||
def _postprocess(self, inputs): | ||
""" | ||
The model output is images, this function will convert the model output to PIL Image. | ||
""" | ||
batch_out = [] | ||
generated_images = inputs['images'] | ||
for generated_image in generated_images: | ||
generated_image = generated_image.transpose([1, 0, 2, 3]).reshape( | ||
generated_image.shape[-3], | ||
self._num_return_images * generated_image.shape[-2], | ||
generated_image.shape[-1]) | ||
batch_out.append(Image.fromarray(generated_image)) | ||
|
||
return batch_out | ||
|
||
def _construct_input_spec(self): | ||
""" | ||
Construct the input spec for the convert dygraph model to static model. | ||
""" | ||
self._input_spec = [ | ||
paddle.static.InputSpec(shape=[None, None], | ||
dtype="int64", | ||
name='input_ids'), | ||
] |
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.
这些后处理如果是和模型绑定的话后面也可以看看将这些方法放在transformers模型代码中提供出来,这里进行统一调用,方便更多模型扩展
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.
done, 现已添加到model的generate内部。