(
text_encoders,
tokenizers,
prompt: str,
max_sequence_length,
device=None,
num_images_per_prompt: int = 1,
)
| 925 | |
| 926 | |
| 927 | def encode_prompt( |
| 928 | text_encoders, |
| 929 | tokenizers, |
| 930 | prompt: str, |
| 931 | max_sequence_length, |
| 932 | device=None, |
| 933 | num_images_per_prompt: int = 1, |
| 934 | ): |
| 935 | prompt = [prompt] if isinstance(prompt, str) else prompt |
| 936 | |
| 937 | clip_tokenizers = tokenizers[:2] |
| 938 | clip_text_encoders = text_encoders[:2] |
| 939 | |
| 940 | clip_prompt_embeds_list = [] |
| 941 | clip_pooled_prompt_embeds_list = [] |
| 942 | for tokenizer, text_encoder in zip(clip_tokenizers, clip_text_encoders): |
| 943 | prompt_embeds, pooled_prompt_embeds = _encode_prompt_with_clip( |
| 944 | text_encoder=text_encoder, |
| 945 | tokenizer=tokenizer, |
| 946 | prompt=prompt, |
| 947 | device=device if device is not None else text_encoder.device, |
| 948 | num_images_per_prompt=num_images_per_prompt, |
| 949 | ) |
| 950 | clip_prompt_embeds_list.append(prompt_embeds) |
| 951 | clip_pooled_prompt_embeds_list.append(pooled_prompt_embeds) |
| 952 | |
| 953 | clip_prompt_embeds = torch.cat(clip_prompt_embeds_list, dim=-1) |
| 954 | pooled_prompt_embeds = torch.cat(clip_pooled_prompt_embeds_list, dim=-1) |
| 955 | |
| 956 | t5_prompt_embed = _encode_prompt_with_t5( |
| 957 | text_encoders[-1], |
| 958 | tokenizers[-1], |
| 959 | max_sequence_length, |
| 960 | prompt=prompt, |
| 961 | num_images_per_prompt=num_images_per_prompt, |
| 962 | device=device if device is not None else text_encoders[-1].device, |
| 963 | ) |
| 964 | |
| 965 | clip_prompt_embeds = torch.nn.functional.pad( |
| 966 | clip_prompt_embeds, (0, t5_prompt_embed.shape[-1] - clip_prompt_embeds.shape[-1]) |
| 967 | ) |
| 968 | prompt_embeds = torch.cat([clip_prompt_embeds, t5_prompt_embed], dim=-2) |
| 969 | |
| 970 | return prompt_embeds, pooled_prompt_embeds |
| 971 | |
| 972 | |
| 973 | def main(args): |
no test coverage detected