Buckets:
| # Inferência em lote | |
| A inferência em lote processa múltiplos prompts de uma vez para aumentar a taxa de transferência. Um lote mantém a GPU ocupada, enquanto um prompt único a deixa subutilizada. | |
| A desvantagem é a maior latência, pois você espera que o lote inteiro termine. Lotes grandes também exigem mais memória de GPU. | |
| ## Lote múltiplos prompts | |
| Passe uma lista de prompts para o pipeline para gerar uma imagem para cada prompt. | |
| ```py | |
| import torch | |
| import matplotlib.pyplot as plt | |
| from diffusers import DiffusionPipeline | |
| pipeline = DiffusionPipeline.from_pretrained( | |
| "stabilityai/stable-diffusion-xl-base-1.0", | |
| dtype=torch.float16, | |
| device_map="cuda" # or "mps", "xpu", "cpu" | |
| ) | |
| prompts = [ | |
| "Cinematic shot of a cozy coffee shop interior, warm pastel light streaming through a window where a cat rests. Shallow depth of field, glowing cups in soft focus, dreamy lofi-inspired mood, nostalgic tones, framed like a quiet film scene.", | |
| "Polaroid-style photograph of a cozy coffee shop interior, bathed in warm pastel light. A cat sits on the windowsill near steaming mugs. Soft, slightly faded tones and dreamy blur evoke nostalgia, a lofi mood, and the intimate, imperfect charm of instant film.", | |
| "Soft watercolor illustration of a cozy coffee shop interior, pastel washes of color filling the space. A cat rests peacefully on the windowsill as warm light glows through. Gentle brushstrokes create a dreamy, lofi-inspired atmosphere with whimsical textures and nostalgic calm.", | |
| "Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the nostalgic, lofi-inspired game aesthetic." | |
| ] | |
| images = pipeline( | |
| prompt=prompts, | |
| ).images | |
| fig, axes = plt.subplots(2, 2, figsize=(12, 12)) | |
| axes = axes.flatten() | |
| for i, image in enumerate(images): | |
| axes[i].imshow(image) | |
| axes[i].set_title(f"Image {i+1}") | |
| axes[i].axis('off') | |
| plt.tight_layout() | |
| plt.show() | |
| ``` | |
| ## Gere várias imagens por prompt | |
| Para gerar múltiplas variações de um único prompt, use o argumento `num_images_per_prompt`. | |
| ```py | |
| import torch | |
| import matplotlib.pyplot as plt | |
| from diffusers import DiffusionPipeline | |
| pipeline = DiffusionPipeline.from_pretrained( | |
| "stabilityai/stable-diffusion-xl-base-1.0", | |
| dtype=torch.float16, | |
| device_map="cuda" # or "mps", "xpu", "cpu" | |
| ) | |
| prompt=""" | |
| Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the | |
| space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the | |
| nostalgic, lofi-inspired game aesthetic. | |
| """ | |
| images = pipeline( | |
| prompt=prompt, | |
| num_images_per_prompt=4 | |
| ).images | |
| fig, axes = plt.subplots(2, 2, figsize=(12, 12)) | |
| axes = axes.flatten() | |
| for i, image in enumerate(images): | |
| axes[i].imshow(image) | |
| axes[i].set_title(f"Image {i+1}") | |
| axes[i].axis('off') | |
| plt.tight_layout() | |
| plt.show() | |
| ``` | |
| ## Gere várias imagens para vários prompts | |
| Combine as duas abordagens para gerar diferentes variações de diferentes prompts. Este exemplo reutiliza o `pipeline` e os `prompts` dos exemplos acima. | |
| ```py | |
| images = pipeline( | |
| prompt=prompts, | |
| num_images_per_prompt=2, | |
| ).images | |
| fig, axes = plt.subplots(2, 4, figsize=(12, 12)) | |
| axes = axes.flatten() | |
| for i, image in enumerate(images): | |
| axes[i].imshow(image) | |
| axes[i].set_title(f"Image {i+1}") | |
| axes[i].axis('off') | |
| plt.tight_layout() | |
| plt.show() | |
| ``` | |
| ## Gerar lotes reproduzíveis | |
| Para tornar um lote reproduzível, passe ao pipeline uma lista de objetos [Generator](https://pytorch.org/docs/stable/generated/torch.Generator.html), um para cada imagem, cada um com sua própria semente. | |
| > [!TIP] | |
| > Consulte a documentação de [Reproducibility](./reusing_seeds) para saber mais sobre algoritmos determinísticos e o objeto `Generator`. | |
| Crie um `Generator` por imagem com uma list comprehension. Multiplicar uma lista (`[generator] * 3`) resulta em três referências ao mesmo `Generator`, de modo que as imagens não recebem sementes independentes. | |
| ```py | |
| # don't do this | |
| generator = [torch.Generator(device="cuda").manual_seed(0)] * 3 # or "mps", "xpu", "cpu" | |
| ``` | |
| O número de geradores deve corresponder ao número de imagens no lote. Passe o `generator` para o pipeline. | |
| ```py | |
| import torch | |
| import matplotlib.pyplot as plt | |
| from diffusers import DiffusionPipeline | |
| pipeline = DiffusionPipeline.from_pretrained( | |
| "stabilityai/stable-diffusion-xl-base-1.0", | |
| dtype=torch.float16, | |
| device_map="cuda" | |
| ) | |
| prompts = [ | |
| "Cinematic shot of a cozy coffee shop interior, warm pastel light streaming through a window where a cat rests. Shallow depth of field, glowing cups in soft focus, dreamy lofi-inspired mood, nostalgic tones, framed like a quiet film scene.", | |
| "Polaroid-style photograph of a cozy coffee shop interior, bathed in warm pastel light. A cat sits on the windowsill near steaming mugs. Soft, slightly faded tones and dreamy blur evoke nostalgia, a lofi mood, and the intimate, imperfect charm of instant film.", | |
| "Soft watercolor illustration of a cozy coffee shop interior, pastel washes of color filling the space. A cat rests peacefully on the windowsill as warm light glows through. Gentle brushstrokes create a dreamy, lofi-inspired atmosphere with whimsical textures and nostalgic calm.", | |
| "Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the nostalgic, lofi-inspired game aesthetic." | |
| ] | |
| generator = [torch.Generator(device="cuda").manual_seed(i) for i in range(len(prompts))] # or "mps", "xpu", "cpu" | |
| images = pipeline( | |
| prompt=prompts, | |
| generator=generator | |
| ).images | |
| fig, axes = plt.subplots(2, 2, figsize=(12, 12)) | |
| axes = axes.flatten() | |
| for i, image in enumerate(images): | |
| axes[i].imshow(image) | |
| axes[i].set_title(f"Image {i+1}") | |
| axes[i].axis('off') | |
| plt.tight_layout() | |
| plt.show() | |
| ``` | |
| Cada imagem está vinculada a uma semente, então você pode escolher uma imagem que goste e regenerá-la com a mesma semente enquanto refina seu prompt. | |
| ## Atender solicitações simultâneas | |
| Um servidor também aumenta a taxa de transferência ao lidar com solicitações de muitos usuários ao mesmo tempo. Carregue o pipeline uma vez e compartilhe-o entre as solicitações para que os modelos permaneçam na memória da GPU apenas uma vez. Os agendadores não são seguros para threads, então forneça a cada solicitação seu próprio agendador com [from_pipe()](/docs/diffusers/main/pt/api/pipelines/overview#diffusers.DiffusionPipeline.from_pipe). Compartilhar um único agendador entre threads gera erros como `IndexError: index 21 is out of bounds for dimension 0 with size 21`. | |
| ```py | |
| scheduler = shared_pipeline.scheduler.from_config(shared_pipeline.scheduler.config) | |
| pipeline = StableDiffusion3Pipeline.from_pipe(shared_pipeline, scheduler=scheduler) | |
| ``` | |
| Para servidores completos construídos com [FastAPI](https://fastapi.tiangolo.com/), consulte o exemplo [server](https://github.com/huggingface/diffusers/tree/main/examples/server) e o exemplo [server-async](https://github.com/huggingface/diffusers/tree/main/examples/server-async). O exemplo server-async também clona o estado do gerador de números aleatórios para cada solicitação e torna os tokenizadores seguros para compartilhamento entre threads. | |
| ## Próximas etapas | |
| - Quando um lote não cabe em uma GPU, ou você tem mais prompts do que uma GPU pode processar, distribua os prompts entre as GPUs com [paralelismo de dados](../optimization/data_parallelism). | |
Xet Storage Details
- Size:
- 7.84 kB
- Xet hash:
- d5f1a613d288075da11412f6a8025dc8d719a8af6c3c6a5c065ab004b5acf514
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.