From 34455c46037391fcb4b3217519094f7f0c18f878 Mon Sep 17 00:00:00 2001 From: kim Date: Fri, 30 Oct 2026 16:17:07 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9D=B4=EB=AF=B8=EC=A7=80=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1:=20quality=3D"high"=EB=A5=BC=20FLUX.2=20klein=204B?= =?UTF-8?q?=EB=A1=9C=20=EA=B5=90=EC=B2=B4=20+=20=EC=9D=B4=EB=AF=B8?= =?UTF-8?q?=EC=A7=80=20=EC=83=9D=EC=84=B1=20GPU=EB=A5=BC=200=EB=B2=88?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FLUX.2 klein 4B(distilled) 워크플로 추가. 같은 시드 비교(1024², 4스텝, GPU 0): 따뜻한 상태 5.5초 vs FLUX.1-schnell 9.8초, 첫 로딩 포함 22.9초 vs 24.5초. Qwen3-4B 텍스트 인코더가 한글 프롬프트를 직접 이해해서 번역 단계를 건너뜀(schnell은 같은 한글 프롬프트에 전혀 다른 장면을 그림). 사진 인물 품질도 동등 이상. - klein 파일 3개(diffusion_models/flux-2-klein-4b, text_encoders/qwen_3_4b, vae/flux2-vae)가 없거나 klein 실행이 실패하면 FLUX.1-schnell(영문 번역 프롬프트)로 자동 폴백. SDXL(fast)과 FLUX.1 dev+PuLID 경로는 그대로. - GEN_GPU 1→0: 음성 엔진(GPU 1, PCIe 링크 깨끗)과 VRAM을 나눠 쓰지 않도록 이미지 생성을 화면용 GPU 0(여유 ~15GB)으로 옮김. ComfyUI 서비스의 CUDA_VISIBLE_DEVICES도 0으로 변경함(사용자 systemd 유닛, 레포 밖). - 도구 설명/스키마의 high 항목 문구를 klein 기준으로 갱신. Co-Authored-By: Claude Sonnet 5.5 --- src/tools/imagegen.ts | 67 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 57 insertions(+), 10 deletions(-) diff --git a/src/tools/imagegen.ts b/src/tools/imagegen.ts index 7c2c2e3..c8451e7 100644 --- a/src/tools/imagegen.ts +++ b/src/tools/imagegen.ts @@ -24,12 +24,13 @@ async function translatePromptToEnglish(text: string): Promise { } // Local diffusion models (SDXL, LTX-Video) run in a dedicated venv with their -// own torch/diffusers stack, pinned to the second GPU (04:00.0 — kept free of -// the voice engine that permanently resides on GPU0). See -// /srv/homeclaw/.smallclaw/imagegen-venv. +// own torch/diffusers stack, pinned to GPU 0 (02:00.0, the display GPU with ~15GB +// free). The voice engine lives on GPU 1 (04:00.0) where its PCIe link is clean; +// image generation is batch work that tolerates GPU 0's correctable PCIe retries. +// See /srv/homeclaw/.smallclaw/imagegen-venv. const VENV_PYTHON = '/srv/homeclaw/.smallclaw/imagegen-venv/bin/python3'; const HF_HOME = '/srv/homeclaw/.smallclaw/imagegen-venv/hf-cache'; -const GEN_GPU = '1'; +const GEN_GPU = '0'; function runVenvPython(script: string, timeoutMs: number): Promise { return new Promise((resolve) => { @@ -155,6 +156,39 @@ function sdxlWorkflow(p: { prompt: string; negative_prompt: string; width: numbe }; } +// FLUX.2 klein 4B (distilled) — added 2026-10-30 after a same-seed bench on the +// display GPU: ~5.5s warm vs ~9.8s for FLUX.1-schnell at 1024², and its Qwen3-4B text +// encoder follows Korean prompts directly (schnell's CLIP/T5 drew an unrelated scene). +// Graph mirrors ComfyUI's bundled image_flux2_klein_text_to_image "Distilled" subgraph: +// cfg 1 with a zeroed negative, euler, Flux2Scheduler. Apache-2.0 weights. +const COMFY_MODELS_DIR = '/home/kim/comfyui/models'; +const KLEIN_FILES = [ + 'diffusion_models/flux-2-klein-4b.safetensors', + 'text_encoders/qwen_3_4b.safetensors', + 'vae/flux2-vae.safetensors', +]; +function kleinAvailable(): boolean { + return KLEIN_FILES.every((f) => fs.existsSync(path.join(COMFY_MODELS_DIR, f))); +} + +function fluxKleinWorkflow(p: { prompt: string; width: number; height: number; steps: number; seed: number }) { + return { + '70': { class_type: 'UNETLoader', inputs: { unet_name: 'flux-2-klein-4b.safetensors', weight_dtype: 'default' } }, + '71': { class_type: 'CLIPLoader', inputs: { clip_name: 'qwen_3_4b.safetensors', type: 'flux2', device: 'default' } }, + '72': { class_type: 'VAELoader', inputs: { vae_name: 'flux2-vae.safetensors' } }, + '74': { class_type: 'CLIPTextEncode', inputs: { clip: ['71', 0], text: p.prompt } }, + '76': { class_type: 'ConditioningZeroOut', inputs: { conditioning: ['74', 0] } }, + '63': { class_type: 'CFGGuider', inputs: { model: ['70', 0], positive: ['74', 0], negative: ['76', 0], cfg: 1 } }, + '61': { class_type: 'KSamplerSelect', inputs: { sampler_name: 'euler' } }, + '62': { class_type: 'Flux2Scheduler', inputs: { steps: p.steps, width: p.width, height: p.height } }, + '66': { class_type: 'EmptyFlux2LatentImage', inputs: { width: p.width, height: p.height, batch_size: 1 } }, + '73': { class_type: 'RandomNoise', inputs: { noise_seed: p.seed } }, + '64': { class_type: 'SamplerCustomAdvanced', inputs: { noise: ['73', 0], guider: ['63', 0], sampler: ['61', 0], sigmas: ['62', 0], latent_image: ['66', 0] } }, + '65': { class_type: 'VAEDecode', inputs: { samples: ['64', 0], vae: ['72', 0] } }, + '9': { class_type: 'SaveImage', inputs: { images: ['65', 0], filename_prefix: 'flux2_klein_api' } }, + }; +} + function fluxSchnellWorkflow(p: { prompt: string; width: number; height: number; steps: number; seed: number }) { return { '1': { class_type: 'UNETLoader', inputs: { unet_name: 'flux1-schnell-fp8.safetensors', weight_dtype: 'default' } }, @@ -375,13 +409,13 @@ export const imageGenerateTool = { description: [ 'Generate an image from a text prompt using a local diffusion model via ComfyUI (runs on-machine GPU, no external API).', 'quality="fast" (default): SDXL, ~15-20 seconds, default resolution 1024×1024, good for casual/quick illustrations.', - 'quality="high": FLUX.1-schnell (fp8), ~15-25 seconds, noticeably more photorealistic detail and prompt accuracy — and no longer much slower than fast mode (moved off the old 4-bit bitsandbytes path, which needed ~40-60s), so lean toward "high" more readily than before. Still default to fast for quick/casual requests.', + 'quality="high": FLUX.2 klein 4B (falls back to FLUX.1-schnell if unavailable), ~6-10 seconds warm (~25s right after the model loads), noticeably more photorealistic detail and prompt accuracy, and it reads Korean prompts directly — so lean toward "high" readily. Still default to fast for quick/casual requests.', 'Returns the generated image inline in the chat.', ].join('\n'), schema: { prompt: 'Text description of the image to generate (English works best)', - quality: '"fast" (SDXL, default) or "high" (FLUX.1-schnell, much slower but noticeably better detail/realism)', - negative_prompt: 'Things to avoid in the image (optional, e.g. "blurry, low quality, deformed") — ignored in quality="high" mode (FLUX.1-schnell does not support it)', + quality: '"fast" (SDXL, default) or "high" (FLUX.2 klein 4B — faster than SDXL-quality FLUX.1 and understands Korean prompts directly; noticeably better detail/realism)', + negative_prompt: 'Things to avoid in the image (optional, e.g. "blurry, low quality, deformed") — ignored in quality="high" mode (the FLUX models do not support it)', width: 'Image width in pixels, multiple of 8 (default 1024)', height: 'Image height in pixels, multiple of 8 (default 1024)', steps: 'Denoising steps — more = higher quality but slower (fast mode: default 30, range 15–50; high mode: default 4, range 1–8)', @@ -409,6 +443,9 @@ export const imageGenerateTool = { const prompt = String(args?.prompt || '').trim(); if (!prompt) return { success: false, error: 'prompt is required' }; const isHighQuality = args?.quality === 'high'; + // quality="high" prefers FLUX.2 klein; falls back to FLUX.1-schnell if its files are missing + // or the klein run fails (e.g. a ComfyUI build without the Flux2 nodes). + const useKlein = isHighQuality && kleinAvailable(); const workspacePath = getWorkspacePath(args); let outPath = String(args?.output || '').trim(); @@ -419,8 +456,10 @@ export const imageGenerateTool = { } const negativePromptRaw = args?.negative_prompt || ''; + // klein's Qwen3 encoder reads Korean natively (and keeps quoted Hangul sign text intact), + // so skip the lossy translation round-trip for it. const [translatedPrompt, translatedNegative] = await Promise.all([ - translatePromptToEnglish(prompt), + useKlein ? Promise.resolve(null) : translatePromptToEnglish(prompt), isHighQuality ? Promise.resolve(null) : translatePromptToEnglish(negativePromptRaw), ]); @@ -428,8 +467,11 @@ export const imageGenerateTool = { const height = Math.round((args?.height ?? 1024) / 16) * 16; const seed = args?.seed != null ? toFiniteNumber(args.seed, 0) : randomSeed(); + const highSteps = Math.min(8, Math.max(1, args?.steps ?? 4)); const graph = isHighQuality - ? fluxSchnellWorkflow({ prompt: translatedPrompt || prompt, width, height, steps: Math.min(8, Math.max(1, args?.steps ?? 4)), seed }) + ? (useKlein + ? fluxKleinWorkflow({ prompt, width, height, steps: highSteps, seed }) + : fluxSchnellWorkflow({ prompt: translatedPrompt || prompt, width, height, steps: highSteps, seed })) : sdxlWorkflow({ prompt: translatedPrompt || prompt, negative_prompt: translatedNegative || negativePromptRaw, @@ -438,7 +480,12 @@ export const imageGenerateTool = { guidance_scale: toFiniteNumber(args?.guidance_scale, 7.0), seed, }); - const result = await comfyGenerateImage(graph, outPath, width, height, 180_000); + let result = await comfyGenerateImage(graph, outPath, width, height, 180_000); + if (useKlein && ('error' in result || !result.output)) { + console.warn('[image_generate] FLUX.2 klein failed, falling back to FLUX.1-schnell:', 'error' in result ? result.error : 'no output'); + const fallbackPrompt = (await translatePromptToEnglish(prompt)) || prompt; + result = await comfyGenerateImage(fluxSchnellWorkflow({ prompt: fallbackPrompt, width, height, steps: highSteps, seed }), outPath, width, height, 180_000); + } if ('error' in result || !result.output) { return { success: false, error: 'error' in result ? result.error : 'Generator returned no output file' }; }