> 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/otras-cargas-de-trabajo/kandinsky.md).

# Kandinsky

Genera imágenes con el modelo multilingüe de Kandinsky en Clore.ai

Genera imágenes con una poderosa comprensión multilingüe del texto.

{% 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 %}

## ¿Qué es Kandinsky?

Kandinsky es un modelo de generación de imágenes desarrollado por Sber AI:

* Fuerte comprensión multilingüe del texto
* Generación de imágenes de alta calidad
* Mezcla e interpolación de imágenes
* Compatibilidad con inpainting y outpainting
* Pesos de código abierto

## Recursos

* **GitHub:** [ai-forever/Kandinsky-3](https://github.com/ai-forever/Kandinsky-3)
* **HuggingFace:** [kandinsky-community](https://huggingface.co/kandinsky-community)
* **Artículo:** [Artículo de Kandinsky](https://arxiv.org/abs/2310.03502)

## Versiones del modelo

| Versión       | Resolución | Calidad | Velocidad |
| ------------- | ---------- | ------- | --------- |
| Kandinsky 2.1 | 768x768    | Bueno   | Rápido    |
| Kandinsky 2.2 | 1024x1024  | Mejor   | Medio     |
| Kandinsky 3   | 1024x1024  | Mejor   | Más lento |

## Requisitos de hardware

| Modelo                        | VRAM | GPU recomendada |
| ----------------------------- | ---- | --------------- |
| Kandinsky 2.2                 | 8GB  | RTX 3070        |
| Kandinsky 3                   | 12GB | RTX 3090        |
| Kandinsky 3 (alta resolución) | 16GB | RTX 4090        |

## 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
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    'kandinsky-community/kandinsky-3',
    variant='fp16',
    torch_dtype=torch.float16
).to('cuda')

def generate(prompt, negative, steps, guidance, seed):
    generator = torch.Generator('cuda').manual_seed(seed) if seed > 0 else None
    image = pipe(
        prompt=prompt,
        negative_prompt=negative,
        num_inference_steps=steps,
        guidance_scale=guidance,
        generator=generator
    ).images[0]
    return image

gr.Interface(
    fn=generate,
    inputs=[
        gr.Textbox(label='Instrucción'),
        gr.Textbox(label='Prompt negativo', value='low quality, blurry'),
        gr.Slider(10, 100, value=50, label='Pasos'),
        gr.Slider(1, 20, value=4, label='Guía'),
        gr.Number(value=-1, label='Semilla')
    ],
    outputs=gr.Image(),
    title='Kandinsky 3'
).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 torch
```

## Uso básico

### Kandinsky 3

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "kandinsky-community/kandinsky-3",
    variant="fp16",
    torch_dtype=torch.float16
)
pipe.to("cuda")

image = pipe(
    prompt="Un gato astronauta flotando en el espacio, arte digital, colores vibrantes",
    num_inference_steps=50,
    guidance_scale=4.0
).images[0]

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

### Kandinsky 2.2

```python
import torch
from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline

# Cargar el prior (codificador de texto)
prior = KandinskyV22PriorPipeline.from_pretrained(
    "kandinsky-community/kandinsky-2-2-prior",
    torch_dtype=torch.float16
).to("cuda")

# Cargar el decodificador
decoder = KandinskyV22Pipeline.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder",
    torch_dtype=torch.float16
).to("cuda")

# Generar incrustaciones de imagen
prompt = "Un hermoso atardecer sobre montañas, estilo de pintura al óleo"
image_embeds, negative_embeds = prior(
    prompt=prompt,
    guidance_scale=1.0
).to_tuple()

# Generar imagen
image = decoder(
    image_embeds=image_embeds,
    negative_image_embeds=negative_embeds,
    height=768,
    width=768,
    num_inference_steps=50
).images[0]

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

## Prompts multilingües

Kandinsky admite varios idiomas:

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "kandinsky-community/kandinsky-3",
    variant="fp16",
    torch_dtype=torch.float16
).to("cuda")

# Inglés
image_en = pipe("Un zorro rojo en un bosque nevado").images[0]

# Ruso
image_ru = pipe("Красная лиса в снежном лесу").images[0]

# Chino
image_zh = pipe("雪林中的红狐狸").images[0]

# Alemán
image_de = pipe("Ein roter Fuchs im verschneiten Wald").images[0]

¡Todos producen imágenes similares!
```

## Mezcla de imágenes

```python
import torch
from diffusers import KandinskyV22PriorPipeline, KandinskyV22Pipeline
from diffusers.utils import load_image

prior = KandinskyV22PriorPipeline.from_pretrained(
    "kandinsky-community/kandinsky-2-2-prior",
    torch_dtype=torch.float16
).to("cuda")

decoder = KandinskyV22Pipeline.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder",
    torch_dtype=torch.float16
).to("cuda")

# Dos prompts para mezclar
prompt1 = "Un gato"
prompt2 = "Un perro"

# Obtener incrustaciones para ambos
embeds1, neg1 = prior(prompt1).to_tuple()
embeds2, neg2 = prior(prompt2).to_tuple()

# Mezclar incrustaciones (50% cada una)
mixed_embeds = 0.5 * embeds1 + 0.5 * embeds2
mixed_neg = 0.5 * neg1 + 0.5 * neg2

# Generar imagen mezclada
image = decoder(
    image_embeds=mixed_embeds,
    negative_image_embeds=mixed_neg,
    height=768,
    width=768
).images[0]

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

## Inpainting

```python
import torch
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image

pipe = AutoPipelineForInpainting.from_pretrained(
    "kandinsky-community/kandinsky-2-2-decoder-inpaint",
    torch_dtype=torch.float16
).to("cuda")

# Cargar imagen y máscara
image = load_image("photo.png")
mask = load_image("mask.png")

# Inpaint
result = pipe(
    prompt="Una corona dorada",
    image=image,
    mask_image=mask,
    num_inference_steps=50
).images[0]

result.save("inpainted.png")
```

## Imagen a imagen

```python
import torch
from diffusers import AutoPipelineForImage2Image
from diffusers.utils import load_image

pipe = AutoPipelineForImage2Image.from_pretrained(
    "kandinsky-community/kandinsky-3",
    variant="fp16",
    torch_dtype=torch.float16
).to("cuda")

init_image = load_image("sketch.png")

image = pipe(
    prompt="Una pintura digital detallada de un castillo, arte de fantasía",
    image=init_image,
    strength=0.75,
    num_inference_steps=50
).images[0]

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

## Generación por lotes

```python
import torch
from diffusers import AutoPipelineForText2Image
import os

pipe = AutoPipelineForText2Image.from_pretrained(
    "kandinsky-community/kandinsky-3",
    variant="fp16",
    torch_dtype=torch.float16
).to("cuda")

prompts = [
    "Un jardín japonés sereno con flores de cerezo",
    "Una ciudad ciberpunk de noche con luces de neón",
    "Una biblioteca antigua llena de libros mágicos",
    "Una acogedora cabaña en las montañas durante el invierno"
]

os.makedirs("outputs", exist_ok=True)

for i, prompt in enumerate(prompts):
    image = pipe(
        prompt=prompt,
        num_inference_steps=50,
        guidance_scale=4.0
    ).images[0]

    image.save(f"outputs/image_{i}.png")
    print(f"Generado: {prompt[:30]}...")

    torch.cuda.empty_cache()
```

## Interfaz de Gradio

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

pipe = AutoPipelineForText2Image.from_pretrained(
    "kandinsky-community/kandinsky-3",
    variant="fp16",
    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", placeholder="Describe tu imagen..."),
        gr.Textbox(label="Prompt negativo", value="low quality, blurry, distorted"),
        gr.Slider(10, 100, value=50, step=5, label="Pasos"),
        gr.Slider(1, 20, value=4, step=0.5, label="Escala de 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="Kandinsky 3 - Generación de imágenes",
    description="Genera imágenes con prompts multilingües. Funcionando en CLORE.AI."
)

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

## Optimización de memoria

```python
import torch
from diffusers import AutoPipelineForText2Image

pipe = AutoPipelineForText2Image.from_pretrained(
    "kandinsky-community/kandinsky-3",
    variant="fp16",
    torch_dtype=torch.float16
)

# Habilitar optimizaciones de memoria
pipe.enable_model_cpu_offload()

# O para VRAM muy baja
pipe.enable_sequential_cpu_offload()

# Habilitar segmentación de la atención
pipe.enable_attention_slicing()

image = pipe(
    prompt="Un hermoso paisaje",
    num_inference_steps=50
).images[0]
```

## Rendimiento

| Modelo        | Resolución | GPU      | Tiempo |
| ------------- | ---------- | -------- | ------ |
| Kandinsky 3   | 1024x1024  | RTX 3090 | 15 s   |
| Kandinsky 3   | 1024x1024  | RTX 4090 | 10s    |
| Kandinsky 2.2 | 768x768    | RTX 3090 | 8s     |
| Kandinsky 2.2 | 768x768    | RTX 4090 | 5s     |

## Solución de problemas

### Sin memoria

**Problema:** CUDA OOM al generar

**Soluciones:**

* Habilitar descarga a CPU
* Reducir resolución
* Usar Kandinsky 2.2 en lugar de 3
* Habilitar fragmentación de atención

```python
pipe.enable_model_cpu_offload()
pipe.enable_attention_slicing()
```

### Mala renderización de texto

**Problema:** El texto en las imágenes se ve mal

**Soluciones:**

* Kandinsky tiene dificultades para renderizar texto (como la mayoría de los modelos de difusión)
* Añadir texto en el posprocesado
* Usar prompts que eviten texto

### Los colores se ven mal

**Problema:** Los colores de la imagen están deslavados o sobresaturados

**Soluciones:**

* Ajustar la escala de guía (prueba el rango de 3 a 6)
* Especificar preferencias de color en el prompt
* Posprocesar con corrección de color

### Generación lenta

**Problema:** Tarda demasiado en generar

**Soluciones:**

* Reducir los pasos de inferencia (30 suele ser suficiente)
* Usar precisión fp16
* Usar Kandinsky 2.2 para resultados más rápidos
* Reducir la resolución para las vistas previas

## Comparación con otros modelos

| Función           | Kandinsky 3 | SDXL     | FLUX        |
| ----------------- | ----------- | -------- | ----------- |
| Multilingüe       | Excelente   | Limitado | Limitado    |
| Calidad de imagen | Alta        | Muy alta | La más alta |
| Velocidad         | Medio       | Medio    | Lento       |
| VRAM              | 12GB        | 12GB     | 24GB        |
| Inpainting        | Sí          | Sí       | Limitado    |

## 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. Consulta* [*Marketplace de CLORE.AI*](https://clore.ai/marketplace) *las tarifas actuales.*

## Siguientes pasos

* FLUX Generation - Imágenes de la más alta calidad
* Stable Diffusion - Opción más popular
* [PixArt](/guides/guides_v2-es/generacion-de-imagenes/pixart-image-gen.md) - Generación rápida
* ComfyUI - Flujos de trabajo avanzados


---

# 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/otras-cargas-de-trabajo/kandinsky.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.
