/ Модель

Характеристики

Лицензия
OpenRAIL++
Опубликована
29 янв 2023

flex-diffusion-2-1

Генерация изображенийТекст → изображение

Flex Diffusion 2-1 — дообученная на разных соотношениях сторон модель Stable Diffusion для генерации изображений по текстовым описаниям.

15скачиваний за 30 дней26лайковвеса обновлены2 фев 2023

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Изображения» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели сгенерируют результат по каждой задаче. Опубликованный тест появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Flex Diffusion 2-1 — диффузионная модель генерации изображений по тексту, разработанная Jonathan Chang на основе Stable Diffusion 2.1. Она дообучена для работы с разными соотношениями сторон и предназначена в том числе для создания вертикальных и широких изображений с меньшим риском обрезанного или искажённого результата. В репозитории также есть вариант на основе Stable Diffusion 2 Base; оба варианта дообучались 6 тысяч шагов.

Модель обучалась на небольшой выборке пар изображений и подписей из LAION Aesthetics с рейтингом 6 и выше. Для соотношений сторон заданы фиксированные разрешения, поэтому качество генерации на других разрешениях может быть ограничено. Для квадратного формата в карточке указано дообучение при 768×768. Модель принимает текст на английском языке и генерирует изображения. Метаданные указывают лицензию OpenRAIL++; в карточке README указана creativeml-openrail-m.

Сценарии применения

  • создание вертикальных изображений для публикаций и историй
  • генерация широких иллюстраций и фоновых изображений
  • создание изображений по англоязычным текстовым запросам

Ограничения

Модель обучалась на небольшой выборке данных, поэтому улучшение качества может быть ограниченным. Для каждого соотношения сторон предусмотрено фиксированное разрешение, и генерация в других разрешениях может работать хуже.

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Model Card for flex-diffusion-2-1

stable-diffusion-2-1 (stabilityai/stable-diffusion-2-1) finetuned with different aspect ratios.

TLDR:

There are 2 models in this repo:

  • One based on stable-diffusion-2-1 (stabilityai/stable-diffusion-2-1) finetuned for 6k steps.
  • One based on stable-diffusion-2-base (stabilityai/stable-diffusion-2-base) finetuned for 6k steps, on the same dataset.

For usage, see - How to Get Started with the Model

It aims to solve the following issues:

  1. Generated images looks like they are cropped from a larger image.

  2. Generating non-square images creates weird results, due to the model being trained on square images. Examples:

resolutionmodelstable diffusionflex diffusion
576x1024 (9:16)v2-1imgimg
576x1024 (9:16)v2-baseimgimg
1024x576 (16:9)v2-1imgimg
1024x576 (16:9)v2-baseimgimg

Limitations:

  1. It's trained on a small dataset, so it's improvements may be limited.
  2. For each aspect ratio, it's trained on only a fixed resolution. So it may not be able to generate images of different resolutions. For 1:1 aspect ratio, it's fine-tuned at 512x512, although flex-diffusion-2-1 was last finetuned at 768x768.

Potential improvements:

  1. Train on a larger dataset.
  2. Train on different resolutions even for the same aspect ratio.
  3. Train on specific aspect ratios, instead of a range of aspect ratios.

Table of Contents

Model Details

Model Description

stable-diffusion-2-1 (stabilityai/stable-diffusion-2-1) finetuned for dynamic aspect ratios.

finetuned resolutions:

widthheightaspect ratio
051210241:2
157610249:16
25769603:5
364010245:8
45127682:3
56408965:7
65767683:4
75126404:5
86407685:6
964070410:11
105125121:1
1170464011:10
127686406:5
136405125:4
147685764:3
158966407:5
167685123:2
1710246408:5
189605765:3
19102457616:9
2010245122:1

Uses

Training Details

Training Data

aspect_ratiocounts
01:1154727
13:2119615
22:361197
34:352276
416:938862
5400:26721893
63:416893
78:516258
84:515684
96:512228
101000:66712097
112:111006
12800:53310259
135:49753
14500:3339700
15250:1679114
165:38460
17200:1337832
181024:6837176
1911:106470
  • predefined aspect ratios
widthheightaspect ratio
051210241:2
157610249:16
25769603:5
364010245:8
45127682:3
56408965:7
65767683:4
75126404:5
86407685:6
964070410:11
105125121:1
1170464011:10
127686406:5
136405125:4
147685764:3
158966407:5
167685123:2
1710246408:5
189605765:3
19102457616:9
2010245122:1

Training Procedure

Preprocessing

  1. download files with url & caption from https://huggingface.co/datasets/ChristophSchuhmann/improved_aesthetics_6plus
  • I only used the first file train-00000-of-00007-29aec9150af50f9f.parquet
  1. use img2dataset to convert to webdataset
    • https://github.com/rom1504/img2dataset
    • I put train-00000-of-00007-29aec9150af50f9f.parquet in a folder called first-file
    • the output folder is /mnt/aesthetics6plus, change this to your own folder
echo INPUT_FOLDER=first-file
echo OUTPUT_FOLDER=/mnt/aesthetics6plus
img2dataset --url_list $INPUT_FOLDER --input_format "parquet"\
        --url_col "URL" --caption_col "TEXT" --output_format webdataset\
        --output_folder $OUTPUT_FOLDER --processes_count 3 --thread_count 6 --image_size 1024 --resize_only_if_bigger --resize_mode=keep_ratio_largest \
        --save_additional_columns '["WIDTH","HEIGHT","punsafe","similarity"]' --enable_wandb True
  1. The data-loading code will do preprocessing on the fly, so no need to do anything else. But it's not optimized for speed, the GPU utilization fluctuates between 80% and 100%. And it's not written for multi-GPU training, so use it with caution. The code will do the following:
  • use webdataset to load the data
  • calculate the aspect ratio of each image
  • find the closest aspect ratio & it's associated resolution from the predefined resolutions: argmin(abs(aspect_ratio - predefined_aspect_ratios)). E.g. if the aspect ratio is 1:3, the closest resolution is 1:2. and it's associated resolution is 512x1024.
  • keeping the aspect ratio, resize the image such that it's larger or equal to the associated resolution on each side. E.g. resize to 512x(512*3) = 512x1536
  • random crop the image to the associated resolution. E.g. crop to 512x1024
  • if more than 10% of the image is lost in the cropping, discard this example.
  • batch examples by aspect ratio, so all examples in a batch have the same aspect ratio

Speeds, Sizes, Times

  • Dataset size: 100k image-caption pairs, before filtering.

    • I didn't wait for the whole dataset to be downloaded, I copied the first 10 tar files and their index files to a new folder called aesthetics6plus-small, with 100k image-caption pairs in total. The full dataset is a lot bigger.
  • Hardware: 1 RTX3090 GPUs

  • Optimizer: 8bit Adam

  • Batch size: 32

    • actual batch size: 2
    • gradient_accumulation_steps: 16
    • effective batch size: 32
  • Learning rate: warmup to 2e-6 for 500 steps and then kept constant

  • Learning rate: 2e-6

  • Training steps: 6k

  • Epoch size (approximate): 32 * 6k / 100k = 1.92 (not accounting for the filtering)

    • Each example is seen 1.92 times on average.
  • Training time: approximately 1 day

Results

More information needed

Model Card Authors

Jonathan Chang

How to Get Started with the Model

Use the code below to get started with the model.

from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler, UNet2DConditionModel

def use_DPM_solver(pipe):
    pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
    return pipe

pipe = StableDiffusionPipeline.from_pretrained(
  "stabilityai/stable-diffusion-2-1",
    unet = UNet2DConditionModel.from_pretrained("ttj/flex-diffusion-2-1", subfolder="2-1/unet", torch_dtype=torch.float16),
    torch_dtype=torch.float16,
    )
# for v2-base, use the following line instead
#pipe = StableDiffusionPipeline.from_pretrained(
#  "stabilityai/stable-diffusion-2-base",
#    unet = UNet2DConditionModel.from_pretrained("ttj/flex-diffusion-2-1", subfolder="2-base/unet", torch_dtype=torch.float16),
#    torch_dtype=torch.float16)
pipe = use_DPM_solver(pipe).to("cuda")
pipe = pipe.to("cuda")

prompt = "a professional photograph of an astronaut riding a horse"
image = pipe(prompt).images[0]

image.save("astronaut_rides_horse.png")

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм

Можно запустить

Подбираем GPU…

Ревизия весов
5a0cff8

0 моделей