Zenn
🔖

日本語からイラスト生成プロンプトに翻訳する LLM を作った

2025/03/24に公開
24

TL;DR

  • 日本語から danbooru タグに翻訳する LLM を作った
  • LLM を使ってデータセットを合成した

成果物

Danbooru tags Translator で略して Danbot です (Danbooru + Bot にもなります)。前回は Dart でしたが流石に名前被りが多くて検索しずらそうなので変えました。

  • モデル:

https://huggingface.co/dartags/DanbotNL-2408-260m

  • 作成したデータセット:

https://huggingface.co/datasets/dartags/danbooru-2408-blind-captions

  • ComfyUI カスタムノード:

https://github.com/p1atdev/danbot-comfy-node

結果だけ見たい方は #画像生成結果 へ。

前提

この記事は、前回の プロンプトは考えたくないけど画像生成がしたい! となっています。
割と前回の手法について触れることがあるので、前回の記事を読まないと理解できない箇所があるかもしれません。

https://zenn.dev/platina/articles/ea6a60f0ad69d0

はじめに

前置きは前回の記事と同じなのでざっくり説明します。

  1. 画像生成モデルのプロンプト、考えるの難しい
  2. じゃあプロンプトを LLM で生成しよう

という感じで、イラストの画像生成に使う danbooru タグをユーザーの意図に沿うように補完することを目的 としています。

データの収集

以下のデータを利用しました。

  • danbooru.donmai.us 上の投稿メタデータ(タグ等)
  • danbooru.donmai.us 上の danbooru タグの Wiki ページ

前回の手法と比較して、データ合成用に Wiki データ を追加で使用しています。詳細は データの合成 のセクションで説明します。

今回も前回と同様、画像データ自体は用いられませんでした。

クリーニング

前回と同様、収集したデータのうち、望ましくないタグを取り除きました。

例えば、

  • bad anatomy: 悪い人体構造
  • watermark: ウォーターマーク
  • lowres: 低画質
  • highres: 高画質

などが挙げられます。

取り除いた全てのタグのパターンのリスト
望ましくない general タグのリスト
artistic error
extra digits
fewer digits
wrong hand
wrong foot
bad anatomy
bad hands
bad feet
bad reflection
bad proportions
bad perspective
bad ass
bad arm
bad face
bad leg
bad vulva
bad neck
engrish text
typo
ranguage
望ましくない meta タグに部分一致するリスト
absurdres
highres
lowres

commentary
commission
translat
language
annotat
request
mismatch
bad
issue
mistake
banding
artifact
resize
scale
edit
stitch
cleaned
noise
transparency
corrupt

source
has
derivative
available
sample
upload
link
paid
reward
check
variant
revision
file
text
gift
guest
conversion
exif
reverse
colorized 
recolor
artist collaboration
metadata
fixed
lossy
adjust
apng
account
redrawn
third-party

emofuri
pixai
pixiv
paintschainer
waifu2x
diffusion
painter
dall-e
xnalara

custom maid
custom girl
custom order maid

open in
scan
trace
rotoscoping
banner
trade
alias
compat
tagme
audi
sound
video
forced
warning
crease
discolorat
bleed
surprise
thumbnail
ai-
spoiler
completion time

self-portrait

これらは生成されて欲しくない要素なので、ほとんどの処理前に取り除いてから使用しました。一部取り除かずに行った処理があったのですが、単にミスなので取り除くことが望ましいです。

また、次のタグを含む投稿は学習から取り除かれました。

duplicate
pixel-perfect duplicate
off-topic
animated
ghosting

今回、学習に meta タグを含めた のですが、最終的に学習対象となった meta タグは以下のようになりました。

学習対象の meta タグ
adoptable
album cover redraw
anime screenshot
app filter
artbook
avatar generator
background color dependent
book cover redraw
color halftone
comic panel redraw
concept art
cosplay photo
countdown illustration
cropped
decensored
disc menu
doujinshi
end card
eyecatch
figure-referenced
game cg
game model
game screenshot
gamma correction
headshop
key visual
kisekae
live2d
making-of
mixed media
novel illustration
nude filter
official wallpaper
photo-referenced
poster redraw
production art
promotional art
reference photo
rotated
screenshot
screenshot redraw
tall image
tegaki draw and tweet
traditional media
unconventional media
unfinished
wide image

これらは、画像のコンテンツ自体に関係する可能性があり、品質に悪影響を与える可能性が低く、視覚的に何かしらの効果が得られることが期待できると判断したため、学習対象としました。これに含まれるもののうち、わかりやすいものだと、traditional media (伝統的な媒体、デジタルではなく現実のツールを使ったもの) があります。

これらの meta タグは、全ての meta タグの中からルールベースでフィルタリングされた後、手動で選定されました。

タグの並び順

前回は、タグをアルファベット順で並べました。これは、相互に関係性を持たないタグを特定のルールに基づいて並べる一つの方法であったが、今回はこれを変更し、1. 意味的に近いものを近くに2. 出現頻度の高いものを前方に 配置するようにしました。

意味的に近いものを近くに配置する理由として、モデルが次のタグを選択する際に、より有意的な選択を行ってほしい という気持ちが挙げられます。例えば、アルファベット順であると、 類似する概念にも関わらず、アルファベット順で後方のタグの生成確率が、単にアルファベット順で若いというだけのタグに依存することになります。


もしアルファベット順の生成を行った場合、animal ears が選択された後に、green ??? のようなタグが選択されてしまうと、その時点で cat ears や dog ears が生成される可能性はゼロになり、アルファベット後方にある rabbit ears の確率が非常に高くなる。これは、類似する概念にも関わらず、それぞれ 別のタグに依存 してしまっており、非直感的となる。

そのため、意味的に近いタグが近くにあると、モデルは私たちにとってより直感的なタグの中から次のタグを選択することになります。


意味的に近いタグが近くに配置されると、直感的な選択が行われる。animal ears の後方のタグは、ears 関連のタグの中から次のタグとして選ぶことになり、意味的に関係ないタグによって生成が阻害されることが減る。なお、ここに表示した確率は単にイメージであり、実際の確率とは異なる。

では、どのように意味的に近いタグを配置すればいいのでしょうか? ??? ears のように、部分一致するタグ達もありますが、そうでないものもあります。Danbooru には類似するタグを解説している Wiki ページもあるが、そこに載っていないタグがあるとうまく関連づけをすることができません。また、タグの量はおよそ 1 万 8000 個ほどあるため、全てを 手動で分類することは困難 です。

そこで、今回は タグをクラスタリング することによってこれを実現しました。

タグのクラスタリング

まず、furusu/danbooru-tag-similarity の手法をもとに、タグの埋め込みを得ました。具体的には以下の方法で行ないました。

  1. 投稿中の general, meta タグをシャッフル
  2. 位置埋め込みをゼロに固定した OPTForCausalLM で次単語予測の学習
  3. 単語埋め込みを取得

これによって得られた埋め込みを、K-means によって 1024 クラスタに分類しました。

以下に同じクラスタに分類されたものを一部紹介します。クラスタに日本語の説明を付加していますが、これは筆者の主観で名前を後付けしたものであり、タグは全て自動で分類されている ことに注意してください。

  • クラスタ 833: 動物耳
    • cat ears
    • dog ears
    • wolf ears
    • rabbit ears
    • mouse ears
    • mouse tail
    • ...
  • クラスタ 232: 複数人物の関係性・動作
    • multiple girls
    • looking at another
    • hug
    • siblings (注: 兄弟や姉妹)
    • holding hands
    • couple
    • eye contact
    • hand on another's shoulder
    • face-to-face
    • hand on another's chin
    • ...
  • クラスタ 96: メガネの形状・状態
    • semi-rimless eyewear
    • round eyewear
    • black-framed eyewear
    • under-rim eyewear
    • bespectacled (注: 普段メガネをかけないキャラクターがメガネをかけている状態)
    • adjusting eyewear (注: メガネをクイっとしてる)
    • rimless eyewear
    • rectangular eyewear
    • pince-nez (注: 耳掛けを使わず、ブリッジ部分のみで装着している状態)
    • ...
  • クラスタ 891: 表情
    • expressionless
    • frown (注: 額に皺を寄せる表情)
    • light smile
    • :< (注: ムッとした表情)
    • jitome (注: ジト目)
    • serious
    • :t (注: ふくれっ面)
    • pout (注: ふくれっ面で、唇を突き出している)
    • covered mouth (注: 口が隠れている)
    • >:) (注: V 型の眉で口を閉じて笑っている)
    • ...

というような感じです。自動で得られた分類にしては、かなり納得できる分類ではないかと思います。

上記のようにうまくクラスタリングできたタグもある一方で、特定のタグ群は非直感的な分類が行われました。例えば、以下のようなクラスタが発生しました。

  • クラスタ 687
    • 1girl
    • solo
    • smile
    • shirt
    • holding
    • animal ears
    • school uniform
    • frills
    • glasses
    • ...

というようなクラスタがありました。これに含まれるタグを解釈しようとするならば、どれも 頻出概念 であったり、他のタグの 前提タグ となっていたりするものとなっています。例えば、1girl, solo, shirt 等は確かに非常に登場回数が多いです。animal earscat ears などの動物耳につながり、glassesrimless eyewear などの具体的なメガネの形状タグに繋がります。つまり、これらはより他のタグよりも 頻出する抽象的な概念 のグループとして考えることができます。

より抽象的で包括的なタグは自然と登場回数が多くなります。そのため、タグを生成する場合は、抽象的な概念から先に並べることで、だんだんと具体的な要素を追加していく形 にすることができる。これを利用して、最終的に次のようにタグの配置を決定しました。

タグのソート

  1. 事前に用意したキーワードは特別枠として先頭に配置
    • 1girl, solo, scenery など 被写体として画像の構成に非常に重要 となるもの
    • 全ての meta タグ
    • traditional media など、画像の制作方法に関係し、画像の内容にも影響を与える もの
    • monochromeblue theme など、全体の 色彩構成に大きく影響を与える もの
    • simple background など、画像の背景 に対して支配的なもの
    • 以上は、画像の内容に大きく関わるため、クラスタリングされたグループではなく、手動で選定 した
  2. 特別枠以外について、以下のようにソート
    1. まず、クラスタごとのタグの 平均登場回数が多い順にクラスタをソート
    2. クラスタ内のタグは、タグの登場回数が多い順にソート
人物・フォーカス系タグ
人数
1girl
2girls
3girls
4girls
5girls
6+girls
multiple girls
1boy
2boys
3boys
4boys
5boys
6+boys
multiple boys
1other
2others
3others
4others
5others
6+others
multiple others
no humans
フォーカス
solo
still life

solo focus
male focus
animal focus
food focus
text focus
ass focus
foot focus
hip focus
other focus
vehicle focus
mecha focus 
eye focus
breast focus 
back focus 
pectoral focus 
hand focus 
crotch focus 
object focus 
weapon focus 
armpit focus 
monster focus 
hair focus 
pokemon focus 
navel focus 
reflection focus 
flower focus 
footwear focus 
pussy focus 
book focus 
sky focus 
thigh focus 
plant focus 
cloud focus 
soft focus 
mouth focus 
creature focus 
leg focus 
ear focus 
kanji focus 
neck focus 
penis focus 
wind chime focus 
ornament focus 
fruit focus 
throat focus 
arm focus 
lens focus 
number focus 
ford focus 
nose focus 
hangul focus
tail focus
画材
画材タイプ
traditional media
painterly

faux traditional media
faux figurine
fake photograph
具体的な画材
3d printing (medium)
acrylic gouache (medium)
acrylic paint (medium)
adobe fresco (medium)
adobe illustrator (medium)
after effects (medium)
airbrush (medium)
amigurumi (medium)
art academy (medium)
artstudio (medium)
artweaver (medium)
aseprite (medium)
autodesk 3ds max (medium)
autodesk sketchbook (medium)
azpainter (medium)
ballpoint pen (medium)
blender (medium)
blockbench (medium)
brush (medium)
calculator (medium)
calligraphy brush (medium)
canvas (medium)
cardboard (medium)
chalk (medium)
charcoal (medium)
cinema 4d (medium)
clay (medium)
coffee (medium)
color ink (medium)
colored pencil (medium)
comic art board (medium)
coupy pencil (medium)
crayon (medium)
cursor (medium)
daz studio (medium)
desmos (medium)
diorama (medium)
dotpict (medium)
electronic dictionary (medium)
embroidery (medium)
felt (medium)
firealpaca (medium)
flipaclip (medium)
flipnote studio (medium)
flyer (medium)
food art (medium)
fudepen (medium)
g-pen (medium)
gacha club (medium)
gacha life (medium)
garage kit (medium)
garry's mod (medium)
gimp (medium)
glitter (medium)
gold foil (medium)
goo engine (medium)
goodnotes (medium)
google sketchup (medium)
gouache (medium)
graffiti (medium)
graphite (medium)
huashijie (medium)
ibispaint (medium)
ink (medium)
inkscape (medium)
iphone notes (medium)
iscribble (medium)
keyshot (medium)
kid pix (medium)
kirigami (medium)
koikatsu (medium)
krita (medium)
kyaraben (medium)
latte art (medium)
leaf (medium)
lego (medium)
marker (medium)
masking tape (medium)
maya (medium)
medibang paint (medium)
microsoft paint (medium)
microsoft powerpoint (medium)
microsoft word (medium)
mikumikudance (medium)
millipen (medium)
minecraft (medium)
model kit (medium)
modo (medium)
mypaint (medium)
nekopaint (medium)
nib pen (medium)
nintendo 3ds (medium)
oil painting (medium)
opencanvas (medium)
origami (medium)
paint.net (medium)
painting (medium)
painttool sai (medium)
paper cutout (medium)
papercraft (medium)
pastel (medium)
pen (medium)
perler beads (medium)
photo (medium)
photoscape (medium)
picrew (medium)
polystrene (medium)
porcelain (medium)
poser (medium)
print (medium)
procreate (medium)
rebelle (medium)
roblox (medium)
snow (medium)
source filmmaker (medium)
strawpage (medium)
swapnote (medium)
tempera (medium)
tomodachi life (medium)
toonio (medium)
tuxpaint (medium)
unreal (medium)
vrchat (medium)
watercolor (medium)
watercolor pencil (medium)
wax (medium)
whiteboard (medium)
whiteboard fox (medium)
wood carving (medium)
zbrush (medium)
カラーテーマ
カラーテーマ
monochrome
multiple monochrome
greyscale
sepia

flat color
muted color
pale color

pastel colors
imageboard colors
inverted colors
analogous colors

neon palette
limited palette

high contrast

greyscale with colored background
spot color
partially colored

aqua theme
black theme
blue theme
brown theme
depression theme
gold theme
gradient theme
green theme
grey theme
orange theme
pink theme
plaid theme
playing card theme
poke ball theme
purple theme
red theme
split theme
white theme
yellow theme
背景
背景
3d background
abstract background
ai-generated background
american flag background
animal background
aqua background
argyle background
arrow background
basketball background
bat background
bear background
beige background
bell background
black background
bloodfountain background
blue background
blueprint background
blurry background
bow background
bright background
brown background
bubble background
butterfly background
camouflage background
canadian flag background
card background
carrot background
censored background
character background
checkered background
cherry background
cherry blossom background
cloud background
clover background
coin background
collage background
column lineup background
comic background
compass background
cosmic background radiation
cracked background
cream background
cross background
damask background
dark background
diagonal striped background
dithered background
doodle background
dotted background
doughnut background
dragon background
egg background
emblem background
eyewear background
fiery background
firework background
fish background
flag background
floral background
food-themed background
fruit background
galaxy background
game screenshot background
gear background
gingham background
gradient background
green background
grey background
grid background
halftone background
heart background
honeycomb background
horseshoe background
houndstooth background
ice background
image background
insect background
lace background
leaf background
light brown background
lightning background
macaron background
map background
marble background
meme template background
monochrome background
moon background
mosaic background
moving background
multicolored background
multicolored squares background
musical note background
newsprint background
number background
orange background
oval background
paneled background
paper background
patterned background
paw print background
photo background
pill background
pink background
pixiv background
pizza background
plaid background
polka dot background
print background
pumpkin background
purple background
puzzle piece background
rabbit background
radial gradient background
rainbow background
red background
rhombus background
rose background
screenshot background
scribble background
scroll background
semi-transparent background
sepia background
shippou background
shrimp background
shuriken background
silver background
simple background
sketch background
skull background
slashed background
snowflake background
sofmap background
sparkle background
speech bubble background
spider web background
spiral background
splatter background
squid background
star-shaped background
starry background
strawberry background
striped background
sunburst background
tan background
text background
three-toned background
tomato background
transparent background
triangle background
triangular tiling background
two-tone background
umbrella background
upside-down background
volleyball background
watercolor background
watermelon background
wavy background
whale background
white background
yellow background

これによって、

  1. 冒頭は抽象的で汎用的な概念
  2. 画面構成に影響が大きいもので後方の傾向を操作
  3. だんだんと具体的な要素が並ぶ

が実現できます。

データの合成

さて、これまでは danbooru タグ自体の順序について取り組んだが、今回は日本語からタグへの翻訳を行うため、日本語のデータを集める必要 があります。しかし、Danbooru タグに対する日本語キャプションデータはまだ存在しないので、これを作るためには以下の方法が考えらます。

  1. VLMによる英語キャプションデータは既に存在するのでそれを翻訳
  2. 日本語 VLM で日本語キャプションデータを生成
  3. Pixiv タグに置換して日本語キャプションとする
  4. danbooru タグから日本語キャプションデータを合成

まず思いつくのは VLM で画像にキャプションをつける方法 だと思います。実際、最近のローカル VLM の性能は高くなっているため、これを作るのはできないこともないかもしれません。しかし、以下のような課題があります。

  1. 画像データを ダウンロード しないといけない (数 TB あって重い)
  2. 自然言語がタグに対して グラウンディングされていない (タグとキャプション間で情報の過不足が発生する)

1 について、画像をダウンロードするとなると、テキストデータを落とすよりも数百倍 ストレージを食う 上、それを ダウンロードする時間 も必要になるので、腰が重いです。また、それらを処理する必要もあるため、計算リソースもより必要 になります。
2 について、自然言語のキャプションは しばしば冗長 であったり、Danbooru タグと事前知識が異なるため、キャプションするレベルが異なることが多いです。特に、海外で有名でないキャラクターだと、VLM は全くキャラクター名を把握できない でしょう。既存キャラクターを生成しない場合でも、きちんとキャラクターの分別ができていないと、意図せず既存キャラクターを生成する可能性が発生するため、キャラクター知識は重要 となります。

これによって、VLM の視覚能力と知識に頼ったキャプション生成は、リソースの観点ドメイン知識 の観点から、今回のタスクには向かない と判断しました。

次に考えられるのは、Pixiv タグを使って日本語キャプションを生成する という方法です。一部の Danbooru タグには Pixiv タグに関連づけられており、これを用いることで日本語のキャプションを作成できる可能性があります。これは確かに有望ですが、今回は自然言語での柔軟な表現に対応したいため、単語の羅列になってしまうタグの置き換えでは、自然言語の理解力が不足する可能性が高い です。

予備実験 1 タグの復元タスク

後述するエンコーダー・デコーダーアーキテクチャで、エンコーダーに投入した danbooru タグからデコーダーで danbooru タグを復元するタスクを行なった際、正確な danbooru タグ表現の入力には対応できた ものの、自然言語の表現にするとほとんど復元できなくなる ことが確認できました。


自然言語の翻訳の失敗例。正確な対タグ形式の場合はほぼ 100% の精度で復元できたのだが、自然言語ではハル氏ネーションや欠落が多く発生した。

これは、事前に学習した表現形式であれば対応できる ものの、未知の表現だと対応できない ことを示唆しており、複数の方法で表現する、表現の augumentation が必要 であることがわかります。自然言語は多様な表現ができるため、それに対応するために多様な表現での学習が必要になります。

最後に残るのは、4. danbooru タグから日本語キャプションを合成 する方法です。これは一見無理がありそうに思えますが、LLM の力を借りて遠回りすると実現 することができます。商用サービスのような強い LLM を使えば遠回りせず一発でできると思いますが、出力に制限 がかかるため、今回は行いません。 ローカルで寛容なライセンスの LLM でできる範囲 で、次のような流れで行いました。

  1. タグは一応既に英語 ではあるため、英単語を組み合わせて英語の長文を作るのはある程度できる はずです。
  2. そして、長文を要約するのも LLM がやってくれます
  3. 英語の短文から日本語の短文に翻訳するのも LLM がやります
  4. 以上の操作から、日本語と danbooru タグのペアが得られます


データ合成と学習タスクの図。オレンジの方向にデータを合成すると、青の方向へ変換を行う学習するデータが作れる。英語長文から意味を保ったまま日本語長文に翻訳するのは現状のローカルLLMでは難しかった。また、生成するトークンも多くなるのでよりコストがかかるため、行わなかった。

次以降のセクションで具体的に説明します。

タグから英語自然言語に合成

このフェーズでは、Qwen2.5 14B Instruct GPTQ Int4 を使用しました。

https://huggingface.co/Qwen/Qwen2.5-14B-Instruct-GPTQ-Int4

Qwen2.5 14B Instruct GPTQ Int4 の選定理由

日本語が通じ、かつ今回のタスクにおける英語の指示追従能力、生成結果が良好であり、パラメータ数が大きすぎないため選定した。

LLM に対して、Danbooru タグの情報から英語でその画像内の状況を説明する文章を作るようにお願いしたいところですが、一部のタグは意味を知らないと全く使い方がわかりません。例えば、以下のようなタグは説明をしてあげないとうまく使うことができないでしょう。

  • cowboy shot: カウボーイが発砲するわけではなく、腿から頭までが写っている画面構成のこと

他にも、多くの copyright タグや character タグについても全く知らない可能性が高いため、それぞれのタグどういう意味で使われるのか教える必要があります。

そこで、収集した Wiki データを使用しました。およそ 18 万ページ分のタグの説明に関する Wiki データがあるため、それぞれのタグのページについて 最初の段落 を取り出し、LLM に情報として提供しました。

具体的には、cowboy shot であれば、

## cowboy shot
An image framed to show a character from the thighs up, including their face. The character's legs should cut off at the bottom of the image; typically around thigh level, but can be as low as at/right above the knees.

というような説明が与えられます。最初の段落は \r\n で区切った時の最初の要素としました。このような説明を全てのタグについて付加してから、LLM にタグから文章を生成するように指示をしました。

また、タグに対してハルシネーションしてほしくないため、以下を守るように指示しました。

  • 情報を勝手に付け足すな
  • 情報を勝手に削るな
  • 不要な形容詞を使うな
  • 暗喩・比喩を使うな
    • 比喩を使わず、直接的な表現を使え
  • 与えた全てのタグを使え
    • ただし表現は自然な英語になるようにして良い

最終的に与えられるプロンプトの例は以下のようになりました。

キャラクターなしの場合の英語翻訳プロンプト

copyright, character タグなしで、general タグが

1girl, solo, simple background, blue background, looking at viewer, animal ears, school uniform, yellow eyes, black hair, long hair, sitting, cat ears, border, white border, couch

の場合、以下のようなプロンプトになります。

prompt
<|im_start|>system
You are provided with a list of tags representing elements and an explanation of their meanings. 
Based on this, create a descriptive paragraph that accurately reflects the **situations** represented by the tags, without adding or creating any information not provided. 
DO NOT use unnecessary adjectives.
DO NOT use phrases like “This image depicts…” or “This image is….” Instead, start with the main subject as your sentence's subject and describe what it is doing or how it appears, focusing on the situation rather than the image itself.
DO NOT use metaphorical or euphemistic expressions.
You do not have to strictly follow the original tag formatting, and can rephrase the expression to be more natural, as long as you do not add any information that was not provided.
DO NOT mention unspecified or uncertain matters.
DO NOT use euphemism, instead use direct expressions.
Make sure to touch all of the specified tags without exception.<|im_end|>
<|im_start|>user
# Content tag meanings
## 1girl
An image depicting one female character. 

## solo
An image containing a single person. No one else should be visible in the image.

## simple background
An image with an empty or featureless background.

## blue background
Backgrounds with a solid or predominantly blue color. Used for shades of ultramarine, navy or sky blue. For aquamarine or turquoise, use aqua background. Can also apply to gradient background in conjunction with another background color.

## looking at viewer
When a character is making direct eye contact with the viewer. (i.e. simply looking at the camera/through the fourth wall)

## animal ears
A character with animal ears, real or fake animal ears|fake. Also known as [i]kemonomimi[/i]. Do not use this tag for pictures of actual animals. 

## school uniform
A uniform commonly worn by students of various grades depending on the country; in Japan, they're mostly worn by middle school and high school students. The two most common designs are the serafuku and blazer.

## yellow eyes
A character with yellow colored eyes.

## black hair
Hair that is colored black.

## long hair
Hair longer than the shoulders, up to reaching the waist. Shoulder length hair should be tagged with medium hair instead. 

## sitting
The butt resting on a surface (often a chair, couch, or bench), possibly in addition to the legs or feet. For a position with the knees on the floor, use kneeling (except with seiza below).

## cat ears
A character who has, or wears as a fashion accessory, cat ears (nekomimi) on their head.
Do not use this tag for actual cats. 

## border
When a picture has a border along its sides. Most often, this is a simple solid color border on all four sides. See ornate border for more complex borders.

## white border
An image that has a white-colored border surrounding its edges.

## couch
A large upholstered piece of furniture designed to seat several people. Also known as a "sofa."



# All tags
Touch all tags below:
1girl, solo, simple background, blue background, looking at viewer, animal ears, school uniform, yellow eyes, black hair, long hair, sitting, cat ears, border, white border, couch<|im_end|>
<|im_start|>assistant
Certainly! Here's a detailed caption of the situation:

copyright, character タグが存在する場合は、必ずそのキャラクター名を正確に使用してほしいため、danbooru タグの説明文に加えて、より適切な表記が存在する可能性がある Pixiv タグも一応提供 しました。これは、英語への変換時には効果は低いかもしれないですが、日本語へ戻すときも使えるフォーマットなのでそのときに役立ちます。また、副次的な効果として、一部のキャラクターの Wiki にはそのキャラクターの通常時の服装について触れられていることがあるため、複数人が登場するシーンで判別が効きやすくなることがあります。ただし、今回のタスクでは複数人が混同されても特に大きな影響はないです。

プロンプトは具体的に以下のようになります。

キャラクターありの場合の英語翻訳プロンプト
  • copyright: idolmaster, gakuen idolmaster
  • character: shinosawa hiro
  • general: 1girl, solo, jacket, upper body, green jacket, @_@, track jacket, on floor

の場合、

<|im_start|>system
You are provided with a list of tags representing elements and an explanation of their meanings. 
Based on this, create a descriptive paragraph that accurately reflects the **situations** represented by the tags, without adding or creating any information not provided. 
DO NOT use unnecessary adjectives.
DO NOT use phrases like “This image depicts…” or “This image is….” Instead, start with the main subject as your sentence's subject and describe what it is doing or how it appears, focusing on the situation rather than the image itself.
DO NOT use metaphorical or euphemistic expressions.
You do not have to strictly follow the original tag formatting, and can rephrase the expression to be more natural, as long as you do not add any information that was not provided.
DO NOT mention unspecified or uncertain matters.
If copyright or character information is provided, you must use their English name or Japanese one.
DO NOT use euphemism, instead use direct expressions.
Make sure to touch all of the specified tags without exception.<|im_end|>
<|im_start|>user
# Tag meanings
# Copyright information
## idolmaster
Also known as: アイドルマスター, idolm@ster, theidolm@ster, im@s, アイマス, アイドルマスタ
Idolmaster (アイドルマスター, stylized as [i]iDOLM@STER [/i]) is a 2005 video game series by Namco (later Bandai Namco, originally released for the arcade and subsequently for multiple platforms including Xbox 360, PlayStation Portable, Nintendo DS, PS3, PS4, PS5, and PC. The game follows the career of a producer from the 765 Production studio handling ten young idol|idols.

## gakuen idolmaster
Also known as: 学園アイドルマスター, 学マス, 学园偶像大师
An addition to the Idolmaster|iDOLM@STER franchise, in the form of an idol-raising simulation mobile game developed by QualiArts of IDOLY PRIDE fame. Released on May 16, 2024, it centers around the Idol Department at Hatsuboshi Gakuen, where the idols consider each other rivals, each striving to become the number one idol. The player assumes the role of a fellow student training to become a Producer (idolmaster)|.

# Character information
## shinosawa hiro
Also known as: 篠澤広
Character from Gakuen Idolmaster. A genius girl who gives off a mysterious vibe. Tired of living an easy and boring life, she enrolled in Hatsuboshi Gakuen to try things she's bad at.

# Content information
## 1girl
An image depicting one female character. 

## solo
An image containing a single person. No one else should be visible in the image.

## jacket
A garment that is sleeved and hip- or waist-length. Jackets are made from thin material, therefore they are lighter. While some are for fashion, they can also serve as protective clothing when thicker material is used.

## upper body
An image of the upper body of the character, approximately from the navel up. This may or may not include the head. 

## green jacket
A jacket that is coloured green.

## @_@
Indicates swirling which represents confusion, dizziness, being overwhelmed, goofiness, or being K.O.|KO'd. More rare, a character who is drunk or angry can be shown with these eyes.

## track jacket
A type of jacket generally used as athletic wear. Often seen with stripes running lengthwise, a ribbed collar, and/or a prominent zipper.

## sleeping
Being in a state of relatively suspended sensory and motor activity, characterized by total or partial unconsciousness and the inactivity of nearly all voluntary muscles.

## on floor
When a character is sitting, lying, or kneeling on the floor of a room or other indoors building.



# All tags
Touch all tags below:
idolmaster, gakuen idolmaster, shinosawa hiro, 1girl, solo, jacket, upper body, green jacket, @_@, track jacket, sleeping, on floor<|im_end|>
<|im_start|>assistant
Certainly! Here's a detailed caption of the situation:

今回は起きなかったのですが、回答拒否をする可能性を考えてアシスタントの発言の最初の部分も含めています。

実際に生成されたキャプションを紹介します:

元のタグ 生成された英語キャプション 参考用のGoogle翻訳
genshin impact, hu tao (genshin impact), boo tao (genshin impact), 1girl, solo, looking at viewer, smile, long sleeves, hat, jewelry, flower, red eyes, teeth, twintails, thighs, +_+, bracelet, beads, bead necklace, short shorts, black hat, ghost, shorts, necklace, ring, red flower, plum blossoms, porkpie hat, bug, butterfly Hu Tao, the 77th Director of the Wangsheng Funeral Parlor, stands with a smile, her eyes glowing with excitement, marked by a yellow four-pointed sparkle. She wears a black porkpie hat and a black hat, both covering her head. Hu Tao's red eyes are prominent, and she is adorned with jewelry, including a bead necklace, a ring, and a bracelet. She is dressed in a long-sleeved outfit and short shorts, revealing her thighs. Hu Tao's twintails are tied up, and she looks directly at the viewer. Boo Tao, the ghost that often accompanies her, is visible with an indistinct "ghost tail" instead of legs. Hu Tao is also holding a red flower and a butterfly, and there are plum blossoms around her. 王盛葬儀場の第77代所長、胡涛さんは笑顔で立っており、その目は興奮で輝き、黄色い四角い輝きを放っている。彼女は黒い豚の角帽と黒い帽子をかぶり、両方とも頭を覆っている。胡涛さんの赤い目は際立っており、ビーズのネックレス、指輪、ブレスレットなどの宝石で飾られている。彼女は長袖の服と短いパンツを着ており、太ももが露出している。胡涛さんのツインテールは結ばれており、彼女はまっすぐに見る人を見ている。彼女によく付き添う幽霊のブータオは、足の代わりに不明瞭な「幽霊のしっぽ」で見える。胡涛さんは赤い花と蝶も持っており、彼女の周りには梅の花がある。
idolmaster, gakuen idolmaster, fujita kotone, hanami saki, tsukimura temari, 3girls, multiple girls, simple background, white background, blush, smile, open mouth, shirt, long sleeves, hair between eyes, closed mouth, jacket, collarbone, braid, open clothes, v-shaped eyebrows, brown eyes, blonde hair, brown hair, green hair, long hair, short sleeves, medium hair, two side up, white shirt, grey shirt, closed eyes, ^^, ><, black jacket, speech bubble, wavy mouth, sound effects, afterimage, twin braids, low twin braids, :c, outline, open jacket, yellow outline, cropped torso, hitting Fujita Kotone, Hanami Saki, and Tsukimura Temari are depicted in a simple background scene, each with distinct features and expressions. Fujita Kotone, with blonde hair and brown eyes, wears a grey shirt and has her mouth open, showing her smiling. Hanami Saki, with brown hair and brown eyes, has her mouth closed and is wearing a black jacket that is open, revealing her white shirt underneath. She has a wavy mouth and is hitting Tsukimura Temari, who has green hair and brown eyes. Tsukimura Temari, with her mouth closed and a blush on her cheeks, is wearing a black jacket and has her hair in low twin braids. She has a closed eye and a v-shaped eyebrow, indicating a sense of mischievousness. The background is white, and all three characters have cropped torsos, showing their collarbones. Fujita Kotone has her hair between her eyes, and Hanami Saki has her hair in a braid. Tsukimura Temari's hair is long and falls down loosely. All three characters have outlines, with Fujita Kotone and Tsukimura Temari having yellow outlines. Additionally, there is an afterimage of Tsukimura Temari, showing her in a previous position. 藤田琴音、花見咲、月村てまりは、それぞれ特徴と表情がはっきりとしたシンプルな背景シーンに描かれています。金髪で茶色の目をした藤田琴音は、グレーのシャツを着て口を開けており、笑っていることを示しています。茶色の髪と茶色の目をした花見咲は、口を閉じており、開いた黒いジャケットを着ており、その下の白いシャツが見えています。彼女は口を波打たせ、緑の髪と茶色の目をした月村てまりを殴っています。口を閉じて頬を赤らめた月村てまりは、黒いジャケットを着ており、髪を低い位置でツインブレイドにしています。彼女は目を閉じており、V字型の眉毛がいたずらっぽい雰囲気を示しています。背景は白で、3人のキャラクターはすべて胴体が短く、鎖骨が見えます。藤田琴音は髪を目の間に入れており、花見咲は髪を三つ編みにしています。月村てまりの髪は長く、ゆるく垂れています。 3人のキャラクターにはアウトラインがあり、藤田琴音と月村てまりには黄色のアウトラインがあります。また、月村てまりの残像があり、以前の位置を示しています。

これを約 760 万件のデータ全てに対して行い、タグに対してグラウンディングされた英語の詳細なキャプションと、タグのペア が作成できました。

タグ→英語変換 所要コスト
デバイス 時間
A6000 x16?, RTX 4090 x4? 累計 400 GPU 時間?

記憶が曖昧なのですが、200万件に対して約 100 時間ちょいかかったため、760万件だと大体 400 時間になりそうです。使用した正確な GPU 忘れましたが、大体こんな感じだった気がします。

英語を要約

今回のタスクは、タグへの翻訳も行うと同時に、ユーザーが明示的に提供していない、暗黙的な指示を推測してプロンプトを拡張する ことも行います。そのためには、合理的な情報の切り落とし が必要になります。言い換えると、本来の意味を変えずに細かい部分を捨てる要約 を行うことができれば、本質が凝縮された少量の情報から、装飾的な細部を追加するためのデータセットを作る ことができます。私たちが画像生成をするときも、プロンプトをざっくり指定することがあると思いますが、それは同時に 一番重要な本質だけを渡している のと同じだと考えることができます。


要約とその逆の処理の図。要約は情報を削るだけなので簡単に入手ができる。最終的なモデルには、要約から元の情報量に戻すことを学習してほしいわけですね。TIPO でも同様のことが言及されています [2]

そう言うわけで、タグの集合から本質となるタグを選別したいのですが、danbooru タグの状態から直接タグの選別行うのは 14B の LLM には少々難しいと思われる(検証していない)ので、先ほど作った 英語長文を要約し、それをタグに戻すことで凝縮されたタグを得る ことにしました。

このデータ合成では、Phi4 の日本語 GPTQ 量子化 を使用しました。日本語と英語の理解が 14B の割に優れており、非常に良いモデルです。

https://huggingface.co/nejumi/phi-4-GPTQ-Int4-calib-ja-1k

今回のタスクはかなりシンプルで、以下のような指示を行いました。

  • ざっくり1文に要約しろ (LLM に本気を出されると、元々数文だったものを 1 文にほとんどの情報を詰め込んでしまうため、逆に困る。細かい情報は捨ててほしい。自然言語はそれだけ冗長にすることができるということでもある。)
  • 細かい情報を捨てろ (本筋だけ残してほしい)
  • 比喩を使うな

また、キャラクターを含む場合はその情報が削られないように 追加の指示を与えました。

キャラクターありの要約プロンプト例
<|im_start|>system<|im_sep|>
You are provided with a long description about an situation, and your task is to roughly summarize it in a short description within one sentence in casual style.
You should omit minor details and descriptions. Start with the main subject as your sentence's subject and describe what it is doing or how it appears, focusing on the situation rather than the image itself.
DO NOT include the explanation about the copyright/game/work information. Just focus on the contents.
Avoid using euphemisms or metaphors.<|im_end|>
<|im_start|>user<|im_sep|>
# Copyright and Character information
## mahou tsukai no yoru
Also known as: 魔法使いの夜, mahoyo, まほよ
[b]Mahou Tsukai no Yoru[/b] (魔法使いの夜) is a visual novel, developed by Type-Moon and released on April 12, 2012. Koyama Hirokazu is the lead artist. The VN is based on a novel of the same name, which was written by Type-Moon co-founder Nasu Kinoko in 1996, but never released publicly.

## type-moon
Also known as: TYPE-MOON
"Type-Moon":http://www.pixiv.net/tags.php?tag=TYPE-MOON ("タイプムーン":http://www.pixiv.net/tags.php?tag=%E3%82%BF%E3%82%A4%E3%83%97%E3%83%A0%E3%83%BC%E3%83%B3) is a Japanese media company founded by Nasu Kinoko and Takeuchi Takashi.
## kuonji alice
Also known as: 久遠寺有珠
One of the main characters of Mahou Tsukai no Yoru.

# Other expression notes
## 1girl
An image depicting one female character. 

## black eyes
A character with black colored eyes.

## black hair
Hair that is colored black.

## black sweater
A sweater that is colored black.

## jewelry
Any decorative adornments worn on a person made from various metals, gem|gemstones, shells and beads. Its purpose is to enhance the wearer's appearance, although there are practical-usage pieces such as medic-alert bracelets and military dog tags.

## light blush
The subject of the picture is visibly blush|blushing, but only faintly.

## necklace
A simple, circular chain worn loosely around the neck as jewelry. 

## pantyhose
A type of hosiery made of a sheer material that covers from the waist to the toes. These are distinct from thighhighs which only cover the legs, and leggings which don't cover the feet.

## seiza
Formal Japanese sitting position. Formed by kneeling on the floor and then resting the buttocks on the heels, keeping the legs folded under the thighs and the top side of the feet flat on the ground.

## short hair
Hair reaching the neck, but not reaching the shoulders.

## sitting
The butt resting on a surface (often a chair, couch, or bench), possibly in addition to the legs or feet. For a position with the knees on the floor, use kneeling (except with seiza below).

## skirt
A skirt is a tube- or cone-shaped garment which hangs from the waist and covers all or part of the legs.

## solo
An image containing a single person. No one else should be visible in the image.

## sweater
A relatively heavy garment intended to cover the torso and arms of the body. Commonly created from wool or cotton. Light sweaters that open in the front are known as cardigan|cardigans. Sweaters with an attached hood are known as hoodie|hoodies.

## turtleneck
A turtleneck is a type of garment, usually a sweater, with a high collar that covers the neck.

## turtleneck sweater
A sweater which has a turtleneck.

## white background
Backgrounds that are completely or predominantly white in color. Can also apply to gradient background in conjunction with another background color.


# Long description
Alice Kuonji, a character from "Mahou Tsukai no Yoru," sits in the traditional seiza position on a white background. She has short, black hair and black eyes. Alice wears a black turtleneck sweater and a skirt, along with black pantyhose. A light blush is visible on her face, and she has a necklace as a piece of jewelry.<|im_end|>
<|im_start|>assistant<|im_sep|>
Short description:

要約された例を紹介します:

長文 要約 参考用の要約のGoogle翻訳
Laplace, a character from Goddess of Victory: Nikke, is sitting on the floor with her butt resting on the ground. She is wearing a blue jacket with multicolored designs and a white jacket over it, both with shoulder cutouts. Her long blonde hair, which reaches her waist, is styled with crossed bangs and twintails. Laplace has a light blush on her face and is smiling while looking directly at the viewer. She is wearing a black crop top that hangs loosely over her midriff, revealing some skin, and a pleated miniskirt that exposes her zettai ryouiki, the area of bare thighs between her skirt and black thighhighs. Laplace has a bandaid on her cheek and is holding a pair of unworn sunglasses. Her long hair falls over her forehead, reaching between her eyes. She is wearing black gloves and fingerless gloves, and her elbows are covered with elbow gloves. Laplace has a skin fang, and her blue eyes are visible through her smile. She is wearing black sneakers and is depicted from above, with her body fully visible. Laplace, a character from "Goddess of Victory: Nikke," is sitting on the floor with her butt resting on the ground, wearing a blue and white jacket with shoulder cutouts, a black crop top, and a pleated miniskirt that exposes her thighs. She has a bandaid on her cheek, is holding unworn sunglasses, and has crossed bangs with twintails, long blonde hair, and a light blush. She's smiling, looking directly at the viewer, with blue eyes, a skin fang, black gloves, fingerless gloves, elbow gloves, and black sneakers. 「勝利の女神 ニッケ」の登場人物ラプラスは、床に座り、お尻を地面につけている。肩にカットアウトのある青と白のジャケット、黒のクロップトップ、太ももが見えるプリーツミニスカートを身につけている。頬には絆創膏を貼り、未使用のサングラスを持ち、前髪はクロスさせてツインテールにし、長いブロンドの髪にほんのりと頬紅を浮かべている。青い目、スキンファング、黒の手袋、指なし手袋、エルボーグローブ、黒のスニーカーを身につけ、笑顔で視聴者をまっすぐに見つめている。
Plana, a character from Blue Archive, is sitting on a desk with her long, pink and white two-tone hair cascading down to her waist. She has her arm up, supporting her body weight, and her long sleeves extend past her wrists. Plana's eyes are black, and she is wearing a black choker and a black hairband that holds her hair back. Her black shirt is off the shoulders, revealing her collarbone, and her black skirt is pleated. She has a blush on her cheeks, and her eyes are looking directly at the viewer. Her black pantyhose are visible, and her black coat is open, hanging loosely around her. She has a red halo above her head and a white ribbon in her hair. Plana's single braid is to the side, and her hair ribbon is tied in a bow. Her black sailor collar is visible, and her neckerchief is white. Her index finger is raised, and her eyelashes are clearly depicted. The image is from above, emphasizing the three-dimensional aspects of the scene. Plana from Blue Archive is sitting on a desk, with her long, two-tone hair cascading down, her arm up for support, and her eyes directly engaging the viewer, all while wearing a black outfit with a red halo and a white ribbon in her hair. ブルーアーカイブのプラナは、長いツートンカラーの髪を垂らしながら机に座り、支えるために腕を上げ、見る者をまっすぐに見つめています。黒い衣装を着て赤い光輪をまとい、髪には白いリボンをつけています。

これを同様に約 700 万件に対して行いました。

英語長文→英語要約 所要コスト
デバイス 時間
A6000 x16?, A6000 Ada x2?, RTX 4090 x4? 累計 300 GPU 時間?

こちらもほぼ同様な構成でしたが、若干早く終わった気がします。あんまりよく覚えてないので参考値です。

要約からタグに戻す

さて、英語の要約が得られましたが、これをタグに戻す 必要があります。これも既存の LLM にやらせることは難しいです。というかそれができないので今頑張ってデータ作ってるわけですが。

どのようにしたかというと、最初にした英語長文とフルのタグのペアができているため、この状態で 一度英語からタグに翻訳するモデルを学習 し (ステージ 1)、そのモデルで要約文のタグを予測 することで、要約されたタグを作成しました。

これを行うための ステージ1モデルの学習は後述 します。

英語要約を日本語に翻訳

最後に、日本語のデータを作ります。LLM がいくら翻訳ができるといっても、長文になればなるほどミス発生しやすくなるため、なるべく短い文章を翻訳させたいです。なので、先ほど作った 英語要約を日本語に翻訳 します。

このデータ合成では、Phi4 の日本語 GPTQ 量子化 を使用しました。

https://huggingface.co/nejumi/phi-4-GPTQ-Int4-calib-ja-1k

以下の指示を与えました。

与えられる英文を正確に日本語に翻訳して。敬語と丁寧語は使わないで。
カタカナ表現を避けて、代わりに相応しい日本語表現を使って。
説明せず、単に翻訳して。

これに加え、2 つ few-shot を与えました。要約時と同様に、キャラクターが存在する場合はそれらのタグの説明、Pixiv タグを提供し、適切な日本語名が使われるようにしました。

例えば、プロンプト以下のようになります。

キャラありの場合の日本語翻訳プロンプト
<|im_start|>system<|im_sep|>
与えられる英文を正確に日本語に翻訳して。敬語と丁寧語は使わないで。
カタカナ表現を避けて、代わりに相応しい日本語表現を使って。
語注の説明と語注の説明を参考に、ふさわしい日本語名に置き換えて使って。特に、作品名とキャラクター名は適切な日本語を使用して。もし日本語が提供されていない場合、カタカナで表現して。
説明せず、単に翻訳して。<|im_end|>
<|im_start|>user<|im_sep|>
# 作品の説明
## gakuen idolmaster
Also known as: 学園アイドルマスター, 学マス, 学园偶像大师, 学マスFA
An extension of the [[idolmaster|iDOLM@STER]] franchise, in the form of an idol raising simulation mobile game developed by QualiArts of [[IDOLY PRIDE]] fame. It was released on May 16, 2024. It centers around the Idol Department of Hatsuboshi Gakuen, where the idols consider each other rivals striving to become the number one idol. The player takes the role of a fellow student training to become a [[producer (idolmaster)|]].

# キャラクターの説明
## shinosawa hiro 
Also known as: 篠澤広
Character from Gakuen Idolmaster. A genius girl who gives off a mysterious vibe. Tired of living an easy and boring life, she enrolled in Hatsuboshi Gakuen to try things she's bad at.

# 翻訳対象
The image is a close-up of Shinosawa Hiro from Gakuen Idolmaster, who has long grey hair and wearing a blue track jacket and white shirt, is making a peace sign with their hand towards viewer.<|im_end|>
<|im_start|>assistant<|im_sep|>
# 翻訳
長い灰色の髪をしており、青いジャージと白いシャツを着て画面に向かってピースをしている学園アイドルマスターの篠澤広のクローズアップ。<|im_end|>
<|im_start|>user<|im_sep|>
# 作品の説明
## arknights: endfield
Also known as: 明日方舟终末地, アークナイツエンドフィールド, ArknightsEndfield, エンドフィールド, Endfield, アークナイツ:エンドフィールド, 终末地
3D RPG game developed by Hypergryph, published by Hypergryph (CN) and Gryphline (Global).

# キャラクターの説明
## chen qianyu (arknights)
Also known as: 陈千语
A playable operator in [[arknights:_endfield|Arknights: Endfield]].

## perlica (arknights)
Also known as: 佩丽卡, ペリカ, Perlica
A playable operator in [[arknights:_endfield|Arknights: Endfield]].

# 翻訳対象
Two female characters stand in a futuristic spaceship, one is Chen Qianyu with long black hair and horns, and the other is Perlica with white hair and animal ears, both from Arknights: Endfield, and they are wearing detailed outfits and accessories.<|im_end|>
<|im_start|>assistant<|im_sep|>
# 翻訳
二人の少女が近未来的な宇宙船の中におり、黒髪で角の生えた一人はChen Qianyu、白髪にケモ耳のついたもう一人はペリカで、どちらもアークナイツ:エンドフィールドのキャラクター。彼女らは繊細な服装や装飾を身につけている。<|im_end|>
<|im_start|>user<|im_sep|>
# 作品の説明
## idolmaster
Also known as: アイドルマスター, idolm@ster, theidolm@ster, im@s, アイマス, アイドルマスタ
Idolmaster (アイドルマスター, stylized as [i]iDOLM@STER [/i]) is a 2005 video game series by Namco (later Bandai Namco, originally released for the arcade and subsequently for multiple platforms including Xbox 360, PlayStation Portable, Nintendo DS, PS3, PS4, PS5, and PC. The game follows the career of a producer from the 765 Production studio handling ten young idol|idols.

## gakuen idolmaster
Also known as: 学園アイドルマスター, 学マス, 学园偶像大师
An addition to the Idolmaster|iDOLM@STER franchise, in the form of an idol-raising simulation mobile game developed by QualiArts of IDOLY PRIDE fame. Released on May 16, 2024, it centers around the Idol Department at Hatsuboshi Gakuen, where the idols consider each other rivals, each striving to become the number one idol. The player assumes the role of a fellow student training to become a Producer (idolmaster)|.

# キャラクターの説明
## fujita kotone
Also known as: 藤田ことね, 藤田琴音
Character from Gakuen Idolmaster.

# 翻訳対象
Fujita Kotone from Gakuen Idolmaster, with blonde hair styled in pigtails, wearing a colorful jacket, a plaid skirt, and pink sneakers, set against a cosmic background with stars and a spaceship.<|im_end|>
<|im_start|>assistant<|im_sep|>
# 翻訳

翻訳結果の例は以下のようになります。

英語要約 日本語要約
Plana from Blue Archive is sitting on a desk, with her long, two-tone hair cascading down, her arm up for support, and her eyes directly engaging the viewer, all while wearing a black outfit with a red halo and a white ribbon in her hair. ブルーアーカイブのプラナが机に座っており、長く二色の髪が垂れ下がり、腕を支えに上げ、視線を直接見つめている。黒い服を着ており、頭には赤い光輪と白いリボンがある。
Agnes Tachyon, a horse girl from Umamusume, stands with her upper body shown, wearing a black shirt and long-sleeved white lab coat, with brown hair and horse ears, smiling and looking at the viewer while solving a math equation with her mouth open. アグネスタキオンは、黒いシャツと白い長袖の白衣を着て、茶髪と馬耳を持つウマ娘のキャラクター。彼女は上半身を見せており、視聴者に向かって笑顔で見つめながら口を開けて数式を解いている。

ただし、この段階では、タグ→英語英語→要約 のステージと異なり、general タグの説明に関しての情報を提供しなかったため、danbooru タグのまま英語で使われた用語を 適切に日本語に翻訳できなかった事例 がいくつか観察されました。なので次回以降は general タグに関しても適切な情報を提供したいと思います。例えば、「地雷系」を意味する jirai kei というタグを人物名だと判断したり、カタカナのまま使うケースが見られました。

失敗例:

英語要約 日本語要約 失敗要素の説明
A young woman in jirai kei fashion, with blonde hair, grey eyes, and various accessories, holds a smartphone while her nails are decorated with nail art. 金髪で青灰色の瞳を持つ若い女性が、様々なアクセサリーを身につけ、ジャライケイ ファッションでスマートフォンを持っている。その爪にはネイルアートが施されている。 jirai keiジャライケイ ではなく、地雷系。
A young woman with black hair, brown eyes, and pale skin is shown in a portrait with swept bangs and two side-up sections on her head. 黒髪で、目が茶色く、肌が白い若い女性が、前髪をかきあげ、頭の両側に上げた髪の毛がある 肖像画 に描かれている。 swept bangs は前髪を掻き上げているわけではなく、前髪を横にすいている感じ。また、danbooru タグの portrait は日本語の肖像画とは若干ニュアンスが違う気がする...?

LLM の推論バックエンド

これらのデータの加工のために、ローカル LLM を効率的に利用することが必要でした。今回は、LLM の推論のために vllm を採用しました。

https://github.com/vllm-project/vllm

vllm を採用した理由は以下が挙げられます:

  • pip でインストールするだけですぐ使えて 簡単
  • HuggingFace transformers で利用できる多くのモデルに対応していた
  • なんかいい感じに 効率的 らしい[3]
  • OpenAI API 互換[4]
    • クライアント側では推論バックエンドを意識しない、透過的な LLM 呼び出しが可能 (クライアントに変更を加えずに利用する LLM を切り替えられる)
    • Open WebUI での手動の検証に便利

vllm serve コマンドを利用して、複数のノード (それぞれ別のモデルを serve) で LLM の推論サーバーを立てて、別のマシンから OpenAI API 形式でリクエストを送り生成を行いました。

データセットの公開

以上で、データセットの合成が完了しました。データをまとめたものを HuggingFace で公開しています:

https://huggingface.co/datasets/dartags/danbooru-2408-blind-captions

画像を見ずに作成したキャプションであるため、画像からテキストへの直接的なキャプショニングには使いづらいかもしれませんが、フィルタリングすれば VQA データの作成には使えるかもしれません。

アーキテクチャ

モデルは以下のようなアーキテクチャにしました。Llava[5] の画像エンコーダーがテキストエンコーダーになった感じです。


Danbot のアーキテクチャ図。自然言語テキストをエンコーダーでエンコードした後、プロンプトのテンプレートに当てはめてデコーダーに通し、中間言語(danbooru タグ)を生成する。

デコーダーは前回同様、Danbooru タグのみを喋るモデルになっています。

学習

トークナイザー・テンプレート

copyright, character, general, meta のタグから不要なタグを除去し、スペシャルトークンを追加してトークナイザーを作成しました。
語彙サイズは 37555 となりました。

前回からの変更点として、

  • rating タグは細かいもののみに (操作性が悪かったので、 sfw, nsfw の大きな括りはやめて普通に general, sensitive, questionable, explicict のみにした)
  • 後から語彙サイズの変更は面倒なので 予約タグ枠 を追加
  • アスペクト比タグ を追加 (アスペクト比を条件に含めることの初出は DanTagGen [6] で、Dart v2 でも採用。最終的に生成される画像の縦横比を考慮してくれるようになるため、より現実的な生成が可能に)

また、生成テンプレートは最終的に以下のようにしなりました(ステージ2)。途中の段階ではこれに従っていないことがあります。

<|bos|>
  <|aspect_ratio:{アスペクト比}|><|length:{生成する長さ}|><|rating:{レーティング}|>
  <text><|text|></text>
  <|translate:{生成モード}|><|input_end|>
  <copyright>{ここにシリーズ名}</copyright>
  <character>{ここにキャラクター名}</character>
  <general>
    <translation>{ここに翻訳結果}</translation>
    <extension>{ここに拡張結果}</extension>
  </general>
<|eos|>

前回と比較すると、前回は <|aspect_ratio:{アスペクト比}|><|length:{生成する長さ}|><|rating:{レーティング}|><general> の直前に置いていましたが、今回は <|bos|> の直後にしました。これは、<copyright></copyright> 部分もモデルに生成させるので、それよりも前に置く必要があったためです。

また、<text><|text|></text> という謎のパートがありますが、これは エンコーダーの出力を入れるためのプレースホルダー となります。エンコーダーの出力の長さが 100 トークンの場合、<text><|text|><|text|><|text|>...(100個続く)</text> のように、<|text|> が 100 個に増えて、エンコーダーの出力を差し込むための場所を確保します。

アスペクト比の分類

アスペクト比をどのように分類するかについて、現実のデータに基づいて納得のできる分類を行いました。
まず、以下は danbooru 上の画像の縦横比を log2(/)\log_{2}(横 / 縦) として表したものを分布にしたものです。


log2(/)\log_{2}(横 / 縦) の分布。ところどころ山になっている部分が存在することがわかる。

山になっている箇所を見ると、0.5-0.5, 0.00.0, 0.50.5 付近が多い ことがわかります。これらの値は log2log_{2} を取った値なので、実際の /横 / 縦20.5=122^{-0.5} = \frac{1}{\sqrt{2}}, 20.0=1.02^{0.0} = 1.0, 20.5=22^{0.5} = \sqrt{2} となります。つまり、:縦 : 横 はそれぞれ 2:1.0\sqrt{2} : 1.0, 1.0:1.01.0 : 1.0, 1.0:21.0 : \sqrt{2} になります。1.01.0 の方は単に 正方形 ですね。2\sqrt{2} が含まれる方は、紙のアスペクト比に対応 します。

ついで、±0.5\pm 0.5 付近と ±1.0\pm 1.0 付近にも小さな山がありますが、これはそれぞれ 3:43:416:916:9 といった 壁紙のアスペクト比 に対応します。

これらを見ると、画像のアスペクト比と内容を表すタグには何かしら傾向の違いがあると考えることができそうです。

そのため、これらの山に合わせて以下のように分類しました。

  • 9:16 よりもずっと縦長の画像 (log2(width/height)1.25\log_2{(\text{width} / \text{height})} \le -1.25)
  • 9:16 付近の壁紙っぽい縦長の画像 (1.25<log2(width/height)<0.75-1.25 \lt \log_2{(\text{width} / \text{height})} \lt -0.75)
  • 1:21 : \sqrt{2} 付近の紙っぽい縦長の画像 (0.75<log2(width/height)0.25-0.75 \lt \log_2{(\text{width} / \text{height})} \le -0.25)
  • 正方形 (0.25<log2(width/height)<0.25-0.25 \lt \log_2{(\text{width} / \text{height})} \lt -0.25)
  • 2:1\sqrt{2} : 1 付近の紙っぽい横長の画像 (0.25log2(width/height)<0.750.25 \le \log_2{(\text{width} / \text{height})} \lt 0.75)
  • 16:9 付近の壁紙っぽい横長の画像 (0.75log2(width/height)<1.250.75 \le \log_2{(\text{width} / \text{height})} \lt 1.25)
  • 16:9 よりもずっと横長の画像 (1.25log2(width/height)1.25 \le \log_2{(\text{width} / \text{height})})
アスペクト比分類の Python コード例
aspect_ratio.py
import math

def calculate_aspect_ratio_tag(width: int, height: int):
    """Calculate the aspect ratio tag based on the height and width of the image."""
    aspect_ratio = math.log2(width / height)  # log 2 of the aspect ratio

    if aspect_ratio <= -1.25:
        return "too_tall"
    elif aspect_ratio <= -0.75:
        return "tall_wallpaper"
    elif aspect_ratio <= -0.25:
        return "tall"
    elif aspect_ratio < 0.25:
        return "square"
    elif aspect_ratio < 0.75:
        return "wide"
    elif aspect_ratio < 1.25:
        return "wide_wallpaper"
    else:
        return "too_wide"

Stage 0: 事前学習

前回同様、デコーダーのみのモデルで事前学習と、ランダムなタグを条件とした SFT を行いました。次以降でこのモデルを用いて、エンコーダー・デコーダーの形にしました。

モデルは 133M パラメータの Llama アーキテクチャで、transformers ライブラリの Trainer を用いて学習を 5 エポック行いました。

Stage 1:英語→タグ翻訳

英語の長文と完全なタグのペアを利用して、英語からタグに翻訳するモデルを作成しました。

このモデルでは、エンコーダーに Qwen2.5 0.5B Instruct を使用しました。

検討したけど結局使わなかったモデル

以下のモデルも候補にしましたが、結局採用しませんでした。

  • T5系: 今でも画像生成のテキストエンコーダーに使われているのですが、流石に古いので、もっと新しいモデルの方が小さくでも性能が良さそうと思った。
  • CLIP系: Llava をイメージしたアーキテクチャにしたので、CLIP のテキスト側も一瞬いいかなと考えたが、トークン長の制限が厳しすぎる (大抵 100 トークンもない) ので無理だった。
  • multilingual-e5: 日英対応の埋め込みモデルで、良いパラメータ数だったが、コンテキスト長が少し短かった(512)ため断念。英語長文が入りきらなかった。
  • GTE系: 多言語対応で良いパラメータ数、コンテキスト長だったが、transformers に正式実装されてなくてリモートコードのみで、少々面倒だったので断念。
  • その他BERT系: 古いのが多くて、古いのを使うくらいなら新しめのデコーダーモデル使った方がいいのではないかと思ったので使わなかった。

transformers ライブラリの Trainer を用いて学習を 5 エポック行いました。

学習データ量 GPU 学習時間
約 700 万件 RTX 4070 Ti Super x1 約 130 時間
ハイパーパラメータ等
パラメータ
学習率 2e-4
オプティマイザー adamw_torch_fused (transformers)
Adam eps 1e-8
バッチサイズ 8
Gradient accumulation steps 8
Gradient checkpointing No
torch.compile エンコーダーとプロジェクターのみ
neftune_noise_alpha 5
エンコーダー出力層インデックス -1 (一番最後の層)

特に言及していなければデフォルトを使用。

実質的に trl の SFTTrainer & DataCollatorForCompletionOnlyLM での学習と同じことをやったのですが、SFTTrainer はかなりハイレベルなAPIであり、少ない設定で使える一方、変更を加えるのが少々面倒なので、transformers の Trainer で、手動で学習しないトークンを設定 (label-100 を設定すると CrossEntropyLoss の計算時に無視されます [7]) して学習を行いました。

学習データがどんな感じかは、実際にデータを見た方がイメージが掴みやすいと思うので、一例を紹介します:

英語長文
Fubuki Kurokami, the dark persona of Shirakami Fubuki, stands alone in the image. She has black hair and red eyes, with a single red rose held to her mouth. Her hair is long and braided, with a lock of hair, known as an ahoge, sticking out. She wears fox ears with fluffy fur inside, and a red neckerchief with a black sailor collar. Her expression is blank and expressionless, with a flat line at the top of her eyes, indicating a sense of listlessness. She is staring directly at the viewer, wearing a single earring and a red rose in her hand. Her upper body is visible, showing her collarbone and detached sleeves. Light particles are visible around her, enhancing the image.
タグのテンプレート。実際は改行・インデントなし。<|input_end|>以降を学習
<|bos|>
  <|aspect_ratio:tall|><|length:long|><|rating:general|>
  <text><|text|></text>
  <|translate:exact|><|input_end|>
  <copyright>hololive</copyright>
  <character>kurokami fubuki</character>
  <general>1girl, solo, looking at viewer, holding, animal ears, hair between eyes, jewelry, collarbone, upper body, braid, flower, sidelocks, detached sleeves, virtual youtuber, red eyes, black hair, long hair, ahoge, light particles, straight-on, glint, earrings, neckerchief, black sailor collar, side braid, expressionless, jitome, fox girl, staring, blank stare, single earring, sailor collar, red neckerchief, animal ear fluff, fox ears, rose, red flower, red rose, holding flower, flower to mouth</general>
<|eos|>

前回の SFT と異なり、copyright タグと character タグも学習に含めています。これは、自然言語テキストでキャラクターを指定された際に自動で検出できるようにするためです。

これらのテキストは、トークナイズされる際に、長文のトークン長だけ<|text|> を繰り返し、エンコーダーの出力を入れるための枠を作ります。例えば、長文が 4 トークンにトークナイズされたら、タグテンプレートの <text><|text|></text> 部分は <text><|text|><|text|><|text|><|text|></text> となってからトークナイズされます。その後、デコーダーの単語埋め込みに通し、テンプレートの埋め込みを作成したら、<|text|> 部分をエンコーダーの出力に置き換えることで、通常のデコーダーの入力と同じように扱うことができます。これは通常の Llava が画像エンコーダーの出力をデコーダーに渡す方法 と同じです。

これらのデータをそれぞれエンコーダーデコーダーに通し、<|input_end|> 以降のトークンのみでロスを取ることで、タグへの翻訳ができるように学習しました。

Stage 2:日英要約→タグ翻訳+タグ拡張

ステージ 2 では、ステージ 1 と同様のアーキテクチャのモデルを用いましたが エンコーダーを変更 しました。
エンコーダーには sbintuitions/modernbert-ja-130m を使用しました。

https://huggingface.co/sbintuitions/modernbert-ja-130m

日本語・英語対応、130M パラメータと 軽量 で、8k コンテキスト長MITライセンス と、今回の目的に非常にマッチしています。ステージ 1 の学習が終わった後、ステージ 2 の学習を始める前にリリースされたので、ちょうど良いタイミングでした。

ステージ 2 では、得られた英語長文、英語要約、日本語要約のデータを用いて、以下の三種類のタスクを学習しました。

  1. ステージ1 ど同様の「英語長文 → タグ」の 翻訳 タスク
  2. 「英語要約 → 翻訳 + 拡張」 タスク
  3. 「日本語要約 → 翻訳 + 拡張」 タスク

です。1 は ステージ 1 と同じですが、2, 3 はユーザーの意図を汲んだプロンプトの拡張部分も含んでいます。

プロンプト拡張のためのデータ作成

プロンプト拡張をする際、モデルには以下の図のように生成をしてもらいます。


生成されるタグの図。まず自然言語の要約を元に、正確な翻訳タグを生成する。その後、要約とタグをヒントとして、適切なタグを追加し、拡張する。

ここで、拡張されたタグは、完全なタグの集合から要約されたタグの集合を引いた差集合になります。
要は、要約されたタグに含まれてない方を拡張されたタグ とすることができます。要約に含まれていないということは、本筋には大きく関わらなかった細部の情報になります。

特徴量の層の選択

ステージ 2 では、エンコーダーの特徴量として 最後から二番目の層の出力 を使用しました。


最後の層を利用した時(緑)と最後から二番目の層を利用した時(黄)のロスの比較

一番最後の層の出力を利用した時(緑)よりも、最後から二番目の層の出力を利用した時(黄)の方が eval loss が低くなった ので、最後から二番目の層の出力を使用しました。最後から三番目以前の出力は検証していないので、ロスがどうなるかは不明です。

モデルの公開

以上の流れでモデルが学習されました。ステージ 2 のモデルを HuggingFace で公開しています:

https://huggingface.co/dartags/DanbotNL-2408-260M

このモデルでは、ファイルサイズの削減を目的として、推論時に不要なエンコーダーの最後の層を取り除いている (19層→18層) ため、encoder_feature_layer-1 となっています。

推論 (transformers)

transformers のカスタムコードを利用しているため、簡単に利用できます。

以下は、日本語から danbooru タグに翻訳する例です。

翻訳
import torch
from transformers import AutoModelForPreTraining, AutoProcessor

REPO = "dartags/DanbotNL-2408-260M"

processor = AutoProcessor.from_pretrained(
    REPO,
    trust_remote_code=True,
    revision="f992aa6", # optional 
)
model = AutoModelForPreTraining.from_pretrained(
    REPO,
    trust_remote_code=True,
    revision="f992aa6", # optional
    torch_dtype=torch.bfloat16
)

# 翻訳
inputs = processor(
    encoder_text="一人の猫耳の少女が座ってこっちを見ている。",
    decoder_text=processor.decoder_tokenizer.apply_chat_template(
        {
            "aspect_ratio": "tall",
            "rating": "general",
            "length": "very_short",
            "translate_mode": "exact",
        },
        tokenize=False,
    ),
    return_tensors="pt",
)

with torch.inference_mode():
    outputs = model.generate(
        **inputs.to(model.device),
        do_sample=False,
        eos_token_id=processor.decoder_tokenizer.convert_tokens_to_ids(
            "</translation>"
        ),
    )
translation = ", ".join(
    tag
    for tag in processor.batch_decode(
        outputs[0, len(inputs.input_ids[0]) :],
        skip_special_tokens=True,
    )
    if tag.strip() != ""
)
print("translation:", translation)
# translation: 1girl, solo, looking at viewer, sitting, cat girl

apply_chat_template で必要な引数を渡してデコーダー用のテンプレートを作成しています。そして、プロセッサーにエンコーダー用の翻訳したいテキストと、デコーダー用のテンプレートを渡してトークナイズした後、全部をモデルに渡し、</translation> が生成されるまで(翻訳が終了するまで)生成を行っています。

一人の猫耳の少女が座ってこっちを見ている。 に対する翻訳結果は 1girl, solo, looking at viewer, sitting, cat girl となりました。入力した文に対して余計な要素なく翻訳できています。

翻訳向け apply_chat_template 引数
  • 必須

    • translate_mode: 生成の挙動

      • exact: 正確に翻訳。(翻訳時に推奨)
      • approx: 若干のハルシネーションを許す。(拡張時に推奨)
    • aspect_ratio: 生成する画像のアスペクト比。

      • too_tall: 1:2 よりも縦長
      • tall_wallpaper: 9:16 くらいの縦長壁紙に近いアスペクト比
      • tall: 紙のアスペクト比くらいの縦長 (特に何も考えたくない場合はおすすめ)
      • square: 正方形
      • wide: 紙のアスペクト比くらいの横長
      • wide_wallpaper: 16:9 くらいの縦長壁紙に近いアスペクト比
      • too_wide: 2:1 よりも縦長
    • rating: セーフティレーティング

      • general, sensitive, questionable, explicit
    • length: 生成する長さ

      • very_short: だいたい15個未満 (翻訳時に推奨)
      • short: だいたい 10~25 個
      • long: だいたい 25~40 個 (拡張時に推奨)
      • very_long: だいたい 40 個以上
  • オプション

    • copyright: copyright タグを手動で設定する場合
    • character: character タグを手動で設定する場合
翻訳向け generate パラメータ
  • do_sample: サンプリングするかどうか。False 推奨

ハルシネーションを避けるため、サンプリングを行わないことを推奨します。

拡張
inputs = processor(
    encoder_text="一人の猫耳の少女が座ってこっちを見ている。",
    decoder_text=processor.decoder_tokenizer.apply_chat_template(
        {
            "aspect_ratio": "tall",
            "rating": "general",
            "length": "long",
            "translate_mode": "approx",
            "copyright": "",
            "character": "",
            "translation": translation,
        },
        tokenize=False,
    ),
    return_tensors="pt",
)
with torch.inference_mode():
    outputs = model.generate(
        **inputs.to(model.device),
        do_sample=False,
        eos_token_id=processor.decoder_tokenizer.convert_tokens_to_ids("</extension>"),
    )
extension = ", ".join(
    tag
    for tag in processor.batch_decode(
        outputs[0, len(inputs.input_ids[0]) :],
        skip_special_tokens=True,
    )
    if tag.strip() != ""
)
print("extension:", extension)
# extension: simple background, white background, shirt, skirt, long sleeves, animal ears, closed mouth, ribbon, jacket, pantyhose, open clothes, blue eyes, brown hair, long hair, shoes, white shirt, full body, cat ears, black skirt, loafers

こちらも同様にデコーダー用のテンプレートを作成し、プロセッサーにエンコーダー用の翻訳したいテキスト一緒にトークナイズした後、全部をモデルに渡し、</extension> が生成されるまで(拡張が終了するまで)生成を行っています。

一人の猫耳の少女が座ってこっちを見ている。 とその翻訳結果を元に拡張した結果は、 simple background, white background, shirt, skirt, long sleeves, animal ears, closed mouth, ribbon, jacket, pantyhose, open clothes, blue eyes, brown hair, long hair, shoes, white shirt, full body, cat ears, black skirt, loafers となりました。特に指定していない服装等を補完できていることがわかります。

拡張向け apply_chat_template 引数
  • 必須

    • translate_mode: 生成の挙動

      • exact: 正確に翻訳。(翻訳時に推奨)
      • approx: 若干のハルシネーションを許す。(拡張時に推奨)
    • aspect_ratio: 生成する画像のアスペクト比。

      • too_tall: 1:2 よりも縦長
      • tall_wallpaper: 9:16 くらいの縦長壁紙に近いアスペクト比
      • tall: 紙のアスペクト比くらいの縦長 (特に何も考えたくない場合はおすすめ)
      • square: 正方形
      • wide: 紙のアスペクト比くらいの横長
      • wide_wallpaper: 16:9 くらいの縦長壁紙に近いアスペクト比
      • too_wide: 2:1 よりも縦長
    • rating: セーフティレーティング

      • general, sensitive, questionable, explicit
    • length: 生成する長さ

      • very_short: だいたい15個未満 (翻訳時に推奨)
      • short: だいたい 10~25 個
      • long: だいたい 25~40 個 (拡張時に推奨)
      • very_long: だいたい 40 個以上
    • copyright: 翻訳された copyright タグ (存在しなくても必ず空文字 ""を渡すこと)

    • character: 翻訳された character タグ (存在しなくても必ず空文字 ""を渡すこと)

    • translation: 翻訳された general/meta タグ (存在しなくても必ず空文字 ""を渡すこと)

拡張向け generate パラメータ
  • do_sample: bool。サンプリングするかどうか。
  • temperature: float。 ~ 1.0 までで推奨。高くするとよりランダム。
  • top_p: float。 ~ 1.0 までで推奨。高くするとよりランダム。
  • top_k: int。~ 100 程度までで推奨。高くするとよりランダム。
  • min_p: float。~ 0.1 までで推奨。この値よりも高い確率のトークンしか選ばないため、低くするとよりランダム。

意図に沿った生成を期待したい場合は、ランダムさを抑えるような値にすると良いです。

今回は特にキャラクター等を指定していないですが、指定したい場合は、翻訳結果からタグをパースする必要があります (スペシャルトークンをスキップしなければ、<copyright></copyright><character></character> で囲われているため、難しくはないです)。

推論 (ComfyUI)

ComfyUI のカスタムノードを作成したので、ComfyUI から利用することもできます。

https://github.com/p1atdev/danbot-comfy-node

詳細はレポの README を参照してください。

画像生成結果

ここからは学習されたモデルでプロンプトを生成し、さらにそのプロンプトで画像を生成した結果を紹介します。生成には、AnimagineXL 4.0 を使用しました。

https://huggingface.co/cagliostrolab/animagine-xl-4.0

生成設定
ネガティブプロンプト
lowres, bad anatomy, bad hands, text, error, missing finger, extra digits, fewer digits, cropped, worst quality, low quality, low score, bad score, average score, signature, watermark, username, blurry, 
クオリティタグ
, masterpiece, best quality, high score, great score, absurdres
パラメータ
生成ステップ数 25
サンプラー EulerAncestralDiscreteScheduler (diffusers)
CFG スケール 5.0
  • 版権キャラクターなし
入力プロンプト 生成画像
猫耳で黒髪ロング、制服を着ており、目は黄色の少女。背景はハーフトーンのついた青で、白枠が付いている。ソファーに座って足を組みながらこっちを見ている。
少女がペットボトルに入った水を飲んでいる。全身が写っている。斜めからこっちを見ている。
黒いタキシードを着た男性と赤いドレスをきた女性が舞踏会でダンスを踊っている。被写界深度で背景がボケてる。躍動的。
一人の少女。真正面で上半身。背景はシンプルでオレンジ色。髪は肩までの長さの白で、フリルのついた緑のドレス。青い目をしている。目を逸らしている。ピクセルアート
一人の少女。目が @_@ になってる。
翻訳・拡張結果の詳細
入力プロンプト 翻訳 拡張
猫耳で黒髪ロング、制服を着ており、目は黄色の少女。背景はハーフトーンのついた青で、白枠が付いている。ソファーに座って足を組みながらこっちを見ている。 1girl, solo, blue background, halftone background, looking at viewer, animal ears, school uniform, yellow eyes, black hair, long hair, sitting, crossed legs, cat ears, border, halftone, white border, couch white background, two-tone background, blush, shirt, skirt, long sleeves, hair ornament, closed mouth, pantyhose, blunt bangs, sleeves past wrists, white shirt, blue skirt, pleated skirt, shadow, collared shirt, tail, hairclip, cat tail, black pantyhose, sweater, black sweater, on couch
少女がペットボトルに入った水を飲んでいる。全身が写っている。斜めからこっちを見ている。 1girl, solo, looking at viewer, from side, full body, looking to the side, drinking, bottle, water bottle simple background, white background, shirt, holding, jewelry, brown eyes, blonde hair, long hair, ponytail, hand up, shoes, white shirt, brown footwear, earrings, blue shorts, shorts, denim, denim shorts, holding bag, drinking straw, holding drink, drinking straw in mouth, bag
黒いタキシードを着た男性と赤いドレスをきた女性が舞踏会でダンスを踊っている。被写界深度で背景がボケてる。躍動的。 1girl, 1boy, dress, red dress, blurry, depth of field, tuxedo, ballroom open mouth, shirt, bow, hair between eyes, jacket, pantyhose, open clothes, yellow eyes, blonde hair, short hair, dancing, shoes, white shirt, red bow, high heels, black footwear, black jacket, bowtie, collared shirt, pants, black pants, red bowtie, open jacket, black vest, waistcoat, vest
一人の少女。真正面で上半身。背景はシンプルでオレンジ色。髪は肩までの長さの白で、フリルのついた緑のドレス。青い目をしている。目を逸らしている。ピクセルアート 1girl, solo, simple background, orange background, dress, upper body, frills, blue eyes, white hair, medium hair, green dress, straight-on, looking away, pixel art closed mouth, parted bangs, curly hair, long hair, eyelashes, close-up, tareme, hatching (texture), linear hatching, expressionless, collared dress, frilled sleeves
一人の少女。目が @_@ になってる。 1girl, solo, @_@ smile, shirt, hair between eyes, closed mouth, collarbone, brown eyes, black hair, short hair, ahoge, white shirt, collared shirt, cardigan, grey cardigan, portrait
  • 版権キャラクターあり
入力プロンプト 生成画像
VOICEVOX のずんだもんが緑のドレスを着ている。
ブルーアーカイブのアロナが座って片腕を上げながら上を見上げいている。上から見た様子で、こっちを見ている。手はVサイン。
翻訳・拡張結果の詳細
入力プロンプト 翻訳 拡張
VOICEVOX のずんだもんが緑のドレスを着ている。 voicevox, zundamon, 1girl, dress, green dress solo, simple background, open mouth, hat, thighhighs, very long hair, brown eyes, green hair, long hair, alternate costume, full body, white footwear, green thighhighs, short dress, zettai ryouiki, garter straps, capelet, brown capelet, legwear garter, aqua capelet
ブルーアーカイブのアロナが座って片腕を上げながら上を見上げいている。上から見た様子で、こっちを見ている。手はVサイン。 blue archive, arona (blue archive), 1girl, solo, looking at viewer, sitting, arm up, from above, looking up, v simple background, white background, blush, shirt, skirt, long sleeves, closed mouth, ribbon, school uniform, collarbone, multicolored hair, braid, hairband, choker, hair over one eye, blue eyes, blue hair, pink hair, short hair, blue shirt, two-tone hair, white skirt, pleated skirt, miniskirt, white ribbon, serafuku, white sailor collar, single braid, side braid, hair ribbon, halo, blue halo, white choker, white hairband, sailor collar, light blue hair, w

利点・長点

既存の LLM サービスや、ある程度のパラメータ数を持ったローカル LLM であれば、few-shot を与えればかなりそれっぽいエセ danbooru タグを生成することができます。それらと比較すると以下の点で優れていると言えます

  • 軽量なパラメータ数
    • 今回のモデルは約 260M パラメータなので、ほとんどの意思疎通可能なローカル LLM と比べて少メモリで動作し、匹敵する品質で翻訳が可能です
  • 正確な danbooru タグ
    • 既存のローカル LLM は正確な danbooru タグを生成することは難しいですが、今回のモデルは、danbooru タグしか生成できないので、正確な danbooru タグが欲しい場合に適しています
  • 版権知識
    • 既存のローカル LLM は多くの場合版権キャラ知識に疎いため、版権キャラを生成したい場合に望んだ出力を得られない場合がありますが、今回のモデルでは、ある程度[8]知名度あるキャラクターなら生成が可能です

限界・課題

一方で、限界や課題もあります

  • 曖昧な表現に弱い
    • 例えば、「最強の斧」みたいなざっくりした指示にはうまく対応できません。今回、「美しい」や「〜と思われる」といった主観や推測を含む表現を使わないようにデータを作成した上、作成した要約文でも、明示的に要素の指定がされているため、曖昧・抽象的な指示に弱く、意図した生成がされづらい です
  • 柔軟に状況を表現できない
    • 例えば、black apple はモデルの生成できる語彙に含まれない[9]ため、「黒いリンゴ」を指示されても、望んだ結果を得られないです。danbooru タグしか生成できないため表現できる範囲が danbooru タグに制限され、danbooru タグにない概念に対応できません
  • 複数の被写体の操作ができない
    • danbooru タグのみを生成する都合上、登場人物が複数人いたり、指示対象となる存在が複数あると、意図に沿った操作を完全には行うことができません。例えば、服装や動作の描きわけを指示できなかったり、被写体が一つだけでも、左右の指定を通すことができません
  • キャラクターの誤認識
    • 版権キャラの誤認識が稀に発生し、望んでいないキャラクターが誤認識されたり、指定していないのに稀にキャラクターを認識(ハルシネーション) することがあります。これは、手動でキャラクタータグの生成を制限することである程度回避可能ですが、生成体験に若干影響を及ぼします。
  • 文意の理解が弱い
    • 今回、自然言語のデータで学習したとはいえ、データの作成に用いたモデル・プロンプトのバリエーションが低いため、ある表現には反応するのに別の表現にすると反応しなくなったり、そもそも誤った表現で学習されていて指示がちゃんと通じなかったりといったことが発生しました。例えば、「ピースサイン」は認識できないのに「Vサイン」は認識できるといったケースや、「体育座り」が「正座」と認識されるケースがありました。これを改善するには、データの合成をする際に、複数のプロンプトで複数種類のデータを作成して多様性を持たせたり、正しい意味で翻訳が行われるように何かしら改善することが必要になりそうです。

おわりに

今回は、日本語に対応した、自然言語から danbooru タグに翻訳するモデルを作成してみました。データ合成やモデルの学習を通じてさまざまな課題も見えたので、今後に活かしたいと思います。

感想として、danbooru タグへの翻訳は想像していたよりはうまくいったものの、表現力の限界や柔軟性の欠如も見える結果となったのですが、それはそうと日本語のプロンプトを使いながらいつものモデルでイラスト生成できるのは少し新鮮な体験で面白かったです。

NovelAI や Illustrious では danbooru タグだけでなく自然言語のプロンプトに対応する/しているということで、これからのイラスト生成用のプロンプトがどのような形になっていくのかわからないのですが、ユーザー目線としては、「関係性が自明な要素はタグ列挙、細かい指定を自然言語で」みたいな雰囲気で指示できると認知負荷が低くなって良さそうだなとか思いました。一方で、最近の実写系のモデルや動画生成モデルで採用されているような、「UI の裏側で強力な LLM に全てを託す」みたいなのも増えていますが、裏側にいる LLM と方向性の違いで決裂するケースも発生しそうで、プロンプトの高度化とユーザー体験をどのように両立していくのかは気になるところです。

脚注
  1. danbooru の全投稿は約 800 万件、original タグが割り当てられた投稿は約 120 万件なので、大体 1/8 ↩︎

  2. https://arxiv.org/abs/2411.08127 ↩︎

  3. https://blog.vllm.ai/2023/06/20/vllm.html ↩︎

  4. https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html ↩︎

  5. https://arxiv.org/abs/2304.08485 ↩︎

  6. https://huggingface.co/KBlueLeaf/DanTagGen-alpha ↩︎

  7. https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html ↩︎

  8. danbooru に 100 件以上で学習対象 ↩︎

  9. danbooru タグには存在するが、数が少ないため学習の対象ではない ↩︎

GitHubで編集を提案
24

Discussion

ログインするとコメントできます