> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-es/generacion-de-imagenes/pixart-image-gen.md).

# PixArt

Generación rápida de imágenes con PixArt-Alpha y PixArt-Sigma

Genera imágenes rápidamente con PixArt-Alpha y PixArt-Sigma.

{% hint style="success" %}
Todos los ejemplos se pueden ejecutar en servidores GPU alquilados a través de [Marketplace de CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

## Alquilar en CLORE.AI

1. Visita [Marketplace de CLORE.AI](https://clore.ai/marketplace)
2. Filtra por tipo de GPU, VRAM y precio
3. Elige **Bajo demanda** (tarifa fija) o **Spot** (precio ofertado)
4. Configura tu pedido:
   * Selecciona la imagen de Docker
   * Configura los puertos (TCP para SSH, HTTP para interfaces web)
   * Añade variables de entorno si es necesario
   * Introduce el comando de inicio
5. Selecciona el método de pago: **CLORE**, **BTC**, o **USDT/USDC**
6. Crea el pedido y espera al despliegue

### Accede a tu servidor

* Encuentra los detalles de conexión en **Mis pedidos**
* Interfaces web: Usa la URL del puerto HTTP
* SSH: `ssh -p <port> root@<proxy-address>`

## ¿Qué es PixArt?

Los modelos PixArt ofrecen:

* 10 veces más rápido que SDXL
* Imágenes de alta calidad de 1024 px
* Excelente renderizado de texto
* Métodos de entrenamiento eficientes

## Variantes del modelo

| Modelo       | Calidad   | Velocidad | VRAM |
| ------------ | --------- | --------- | ---- |
| PixArt-Alpha | Excelente | Rápido    | 8GB  |
| PixArt-Sigma | Mejor     | Medio     | 12GB |

## Despliegue rápido

**Imagen de Docker:**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**Puertos:**

```
22/tcp
7860/http
```

**Comando:**

```bash
pip install diffusers transformers accelerate gradio && \\
python -c "
import gradio as gr
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained('PixArt-alpha/PixArt-XL-2-1024-MS', torch_dtype=torch.float16)
pipe.to('cuda')

def generate(prompt, steps):
    image = pipe(prompt, num_inference_steps=steps).images[0]
    return image

demo = gr.Interface(fn=generate, inputs=[gr.Textbox(), gr.Slider(10, 50, 20)], outputs=gr.Image(), title='PixArt')
demo.launch(server_name='0.0.0.0', server_port=7860)
"
```

## Accediendo a tu servicio

Después del despliegue, encuentra tu `http_pub` URL en **Mis pedidos**:

1. Ve a **Mis pedidos** página
2. Haz clic en tu pedido
3. Encuentra la `http_pub` URL (p. ej., `abc123.clorecloud.net`)

Usa `https://YOUR_HTTP_PUB_URL` en lugar de `localhost` en los ejemplos a continuación.

## Instalación

```bash
pip install diffusers transformers accelerate
```

## PixArt-Alpha

### Generación básica

```python
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
)
pipe.to("cuda")

prompt = "Un gato astronauta flotando en el espacio, la Tierra de fondo, fotorrealista"

image = pipe(
    prompt=prompt,
    num_inference_steps=20,
    guidance_scale=4.5
).images[0]

image.save("output.png")
```

### Parámetros de generación

```python
image = pipe(
    prompt="una hermosa puesta de sol sobre montañas",
    negative_prompt="borroso, baja calidad",
    num_inference_steps=20,      # Calidad (10-50)
    guidance_scale=4.5,          # Adhesión al prompt (3-7)
    height=1024,
    width=1024,
    generator=torch.Generator("cuda").manual_seed(42)
).images[0]
```

## PixArt-Sigma

Versión de mayor calidad:

```python
from diffusers import PixArtSigmaPipeline
import torch

pipe = PixArtSigmaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",
    torch_dtype=torch.float16
)
pipe.to("cuda")
pipe.enable_model_cpu_offload()

image = pipe(
    prompt="una fotografía profesional de un coche deportivo rojo",
    num_inference_steps=30,
    guidance_scale=4.5
).images[0]

image.save("sigma_output.png")
```

## Optimización de memoria

### Para 8GB de VRAM

```python
pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
)

# Descarga a CPU
pipe.enable_model_cpu_offload()

# Descarga secuencial a CPU (más agresiva)

# pipe.enable_sequential_cpu_offload()
```

### Habilitar corte del VAE

```python
pipe.enable_vae_slicing()
pipe.enable_vae_tiling()
```

## Generación por lotes

```python
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
).to("cuda")

prompts = [
    "una ciudad cyberpunk de noche",
    "un tranquilo jardín japonés",
    "un castillo de fantasía sobre un acantilado",
    "un arrecife de coral submarino"
]

for i, prompt in enumerate(prompts):
    image = pipe(prompt, num_inference_steps=20).images[0]
    image.save(f"output_{i:03d}.png")
    print(f"Generado: {prompt[:50]}...")
```

## Diferentes resoluciones

```python

# Resoluciones compatibles
resolutions = [
    (512, 512),
    (768, 768),
    (1024, 1024),
    (1024, 512),   # Paisaje
    (512, 1024),   # Retrato
    (768, 1024),
    (1024, 768),
]

for w, h in resolutions:
    image = pipe(
        prompt="un hermoso paisaje",
        width=w,
        height=h,
        num_inference_steps=20
    ).images[0]

    image.save(f"output_{w}x{h}.png")
```

## Renderizado de texto

PixArt destaca en el texto dentro de las imágenes:

```python
prompt = """
Un cartel de película vintage con el título "COSMIC ADVENTURE" en letras gruesas,
con una nave espacial y planetas, estilo retro de los años 50
"""

image = pipe(
    prompt=prompt,
    num_inference_steps=30,
    guidance_scale=5.0
).images[0]
```

## Interfaz de Gradio

```python
import gradio as gr
from diffusers import PixArtAlphaPipeline
import torch

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
).to("cuda")

def generate(prompt, negative_prompt, steps, guidance, width, height, seed):
    generator = torch.Generator("cuda").manual_seed(seed) if seed > 0 else None

    image = pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=steps,
        guidance_scale=guidance,
        width=width,
        height=height,
        generator=generator
    ).images[0]

    return image

demo = gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label="Prompt", lines=3),
        gr.Textbox(label="Prompt negativo"),
        gr.Slider(10, 50, value=20, step=1, label="Pasos"),
        gr.Slider(1, 10, value=4.5, step=0.5, label="Guía"),
        gr.Slider(512, 1024, value=1024, step=64, label="Ancho"),
        gr.Slider(512, 1024, value=1024, step=64, label="Alto"),
        gr.Number(value=-1, label="Semilla (-1 para aleatorio)")
    ],
    outputs=gr.Image(label="Imagen generada"),
    title="Generador de imágenes PixArt"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## Servidor API

```python
from fastapi import FastAPI
from fastapi.responses import Response
from diffusers import PixArtAlphaPipeline
import torch
import io

app = FastAPI()

pipe = PixArtAlphaPipeline.from_pretrained(
    "PixArt-alpha/PixArt-XL-2-1024-MS",
    torch_dtype=torch.float16
).to("cuda")

@app.post("/generate")
async def generate(
    prompt: str,
    negative_prompt: str = "",
    steps: int = 20,
    guidance: float = 4.5,
    width: int = 1024,
    height: int = 1024
):
    image = pipe(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=steps,
        guidance_scale=guidance,
        width=width,
        height=height
    ).images[0]

    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    return Response(content=buffer.getvalue(), media_type="image/png")

# Ejecutar: uvicorn server:app --host 0.0.0.0 --port 8000
```

## Comparación de rendimiento

| Modelo       | GPU      | Tiempo 1024x1024 |
| ------------ | -------- | ---------------- |
| PixArt-Alpha | RTX 3090 | \~3s             |
| PixArt-Sigma | RTX 3090 | \~5 s            |
| SDXL         | RTX 3090 | \~15 s           |
| PixArt-Alpha | RTX 4090 | \~2s             |
| PixArt-Sigma | RTX 4090 | \~3s             |

## Configuración de calidad

| Caso de uso  | Pasos | Guía |
| ------------ | ----- | ---- |
| Vista previa | 10-15 | 4.0  |
| Estándar     | 20    | 4.5  |
| Alta calidad | 30-40 | 5.0  |

## Solución de problemas

### Sin memoria

```python

# Habilitar descarga
pipe.enable_model_cpu_offload()

# O usar una resolución más pequeña
width, height = 768, 768
```

### Calidad deficiente

* Aumentar pasos (25-40)
* Ajustar la escala de guía
* Prompts más detallados

### Generación lenta

* Usar PixArt-Alpha (más rápido)
* Reducir pasos
* Menor resolución

## Estimación de costos

Tarifas típicas del marketplace de CLORE.AI (a partir de 2024):

| GPU       | Tarifa por hora | Tarifa diaria | Sesión de 4 horas |
| --------- | --------------- | ------------- | ----------------- |
| RTX 3060  | \~$0.03         | \~$0.70       | \~$0.12           |
| RTX 3090  | \~$0.06         | \~$1.50       | \~$0.25           |
| RTX 4090  | \~$0.10         | \~$2.30       | \~$0.40           |
| A100 40GB | \~$0.17         | \~$4.00       | \~$0.70           |
| A100 80GB | \~$0.25         | \~$6.00       | \~$1.00           |

*Los precios varían según el proveedor y la demanda. Consulta* [*Marketplace de CLORE.AI*](https://clore.ai/marketplace) *las tarifas actuales.*

**Ahorra dinero:**

* Usa el **Spot** mercado para trabajo interrumpible — alrededor de un tercio de los servidores fija el precio spot por debajo del precio bajo demanda (mediana de \~13% de descuento), el resto lo iguala
* Paga con **CLORE** tokens
* Compara precios entre distintos proveedores

## Siguientes pasos

* Generación FLUX - Mejor calidad
* Stable Diffusion WebUI - Más funciones
* [Guía de ControlNet](/guides/guides_v2-es/procesamiento-de-imagenes/controlnet-advanced.md) - Añadir control


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-es/generacion-de-imagenes/pixart-image-gen.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
