Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

14.9 KB
Raw Blame
import { logger } from 'app/logging/logger';
import { getPrefixedId } from 'features/controlLayers/konva/util';
import { selectMainModelConfig, selectParamsSlice } from 'features/controlLayers/store/paramsSlice';
import { selectRefImagesSlice } from 'features/controlLayers/store/refImagesSlice';
import { selectCanvasMetadata } from 'features/controlLayers/store/selectors';
import { isQwenImageReferenceImageConfig } from 'features/controlLayers/store/types';
import { getGlobalReferenceImageWarnings } from 'features/controlLayers/store/validators';
import { fetchModelConfigWithTypeGuard } from 'features/metadata/util/modelFetchingHelpers';
import { zImageField } from 'features/nodes/types/common';
import { addImageToImage } from 'features/nodes/util/graph/generation/addImageToImage';
import { addInpaint } from 'features/nodes/util/graph/generation/addInpaint';
import { addNSFWChecker } from 'features/nodes/util/graph/generation/addNSFWChecker';
import { addOutpaint } from 'features/nodes/util/graph/generation/addOutpaint';
import {
  addPidDecode,
  addPidImageToImageNative,
  buildPidDecodeChain,
} from 'features/nodes/util/graph/generation/addPidDecode';
import { addQwenImageLoRAs } from 'features/nodes/util/graph/generation/addQwenImageLoRAs';
import { addTextToImage } from 'features/nodes/util/graph/generation/addTextToImage';
import { addWatermarker } from 'features/nodes/util/graph/generation/addWatermarker';
import { Graph } from 'features/nodes/util/graph/generation/Graph';
import {
  getOriginalAndScaledSizesForOtherModes,
  getOriginalAndScaledSizesForTextToImage,
  selectCanvasOutputFields,
  selectPresetModifiedPrompts,
} from 'features/nodes/util/graph/graphBuilderUtils';
import type { GraphBuilderArg, GraphBuilderReturn, ImageOutputNodes } from 'features/nodes/util/graph/types';
import { UnsupportedGenerationModeError } from 'features/nodes/util/graph/types';
import { selectActiveTab } from 'features/ui/store/uiSelectors';
import { t } from 'i18next';
import type { Invocation } from 'services/api/types';
import { isNonRefinerMainModelConfig } from 'services/api/types';
import type { Equals } from 'tsafe';
import { assert } from 'tsafe';

const log = logger('system');

/**
 * Determine whether the given model config represents a Qwen Image Edit model.
 * Only edit-variant models should use reference images for conditioning.
 * Generate (txt2img) models should never receive reference images, even if
 * they exist in state from a previous edit session.
 */
export const isQwenImageEditModel = (model: { variant?: string | null } | null): boolean => {
  if (!model) {
    return false;
  }
  return 'variant' in model && model.variant === 'edit';
};

/**
 * Determine whether classifier-free guidance (negative conditioning) should be used.
 * CFG is only enabled when cfg_scale > 1. With cfg_scale <= 1, the negative prompt
 * is mathematically unused and the model runs once per step instead of twice.
 */
export const shouldUseCfg = (cfgScale: number | number[]): boolean => {
  if (typeof cfgScale === 'number') {
    return cfgScale > 1;
  }
  // For per-step CFG arrays, enable CFG if any value exceeds 1
  return cfgScale.some((value) => value > 1);
};

/**
 * Compute the target dimensions for the VAE-encoded reference image, matching
 * diffusers' `calculate_dimensions(VAE_IMAGE_SIZE=1024*1024, aspect_ratio)` used
 * by QwenImageEditPipeline / QwenImageEditPlusPipeline. The reference is resized
 * so its area is ~1024² while preserving aspect ratio, with each dimension
 * snapped to a multiple of 32 (the model was trained at this scale; feeding it a
 * much larger reference produces a sequence length it was not trained on).
 */
const QWEN_IMAGE_EDIT_REF_TARGET_AREA = 1024 * 1024;
export const calculateQwenImageEditRefDimensions = (
  width: number,
  height: number
): { width: number; height: number } => {
  const ratio = width / height;
  let w = Math.sqrt(QWEN_IMAGE_EDIT_REF_TARGET_AREA * ratio);
  let h = w / ratio;
  w = Math.max(32, Math.round(w / 32) * 32);
  h = Math.max(32, Math.round(h / 32) * 32);
  return { width: w, height: h };
};

export const buildQwenImageGraph = async (arg: GraphBuilderArg): Promise<GraphBuilderReturn> => {
  const { generationMode, state, manager } = arg;

  log.debug({ generationMode, manager: manager?.id }, 'Building Qwen Image Edit graph');

  const model = selectMainModelConfig(state);
  assert(model, 'No model selected');
  assert(model.base === 'qwen-image', 'Selected model is not a Qwen Image Edit model');

  const params = selectParamsSlice(state);

  const { cfgScale: cfg_scale, steps, pidMode } = params;

  const prompts = selectPresetModifiedPrompts(state);

  const g = new Graph(getPrefixedId('qwen_image_graph'));

  const modelLoader = g.addNode({
    type: 'qwen_image_model_loader',
    id: getPrefixedId('qwen_image_model_loader'),
    model,
    vae_model: params.qwenImageVaeModel ?? undefined,
    qwen_vl_encoder_model: params.qwenImageQwenVLEncoderModel ?? undefined,
    component_source: params.qwenImageComponentSource,
  });

  const positivePrompt = g.addNode({
    id: getPrefixedId('positive_prompt'),
    type: 'string',
  });
  const posCond = g.addNode({
    type: 'qwen_image_text_encoder',
    id: getPrefixedId('pos_prompt'),
    quantization: params.qwenImageQuantization,
  });

  // Negative conditioning for CFG (only when cfg_scale > 1)
  const useCfg = shouldUseCfg(cfg_scale);
  const negCond = useCfg
    ? g.addNode({
        type: 'qwen_image_text_encoder',
        id: getPrefixedId('neg_prompt'),
        prompt: prompts.negative || ' ',
        quantization: params.qwenImageQuantization,
      })
    : null;

  const seed = g.addNode({
    id: getPrefixedId('seed'),
    type: 'integer',
  });
  const denoise = g.addNode({
    type: 'qwen_image_denoise',
    id: getPrefixedId('denoise_latents'),
    cfg_scale,
    steps,
    shift: params.qwenImageShift,
  });
  const l2i = g.addNode({
    type: 'qwen_image_l2i',
    id: getPrefixedId('l2i'),
  });

  g.addEdge(modelLoader, 'transformer', denoise, 'transformer');
  g.addEdge(modelLoader, 'qwen_vl_encoder', posCond, 'qwen_vl_encoder');
  g.addEdge(modelLoader, 'vae', l2i, 'vae');

  g.addEdge(positivePrompt, 'value', posCond, 'prompt');
  g.addEdge(posCond, 'conditioning', denoise, 'positive_conditioning');

  if (negCond) {
    g.addEdge(modelLoader, 'qwen_vl_encoder', negCond, 'qwen_vl_encoder');
    g.addEdge(negCond, 'conditioning', denoise, 'negative_conditioning');
  }

  g.addEdge(seed, 'value', denoise, 'seed');
  g.addEdge(denoise, 'latents', l2i, 'latents');

  // Add Qwen Image Edit LoRAs if any are enabled
  addQwenImageLoRAs(state, g, denoise, modelLoader);

  // Only collect reference images for edit-variant models.
  // For txt2img (generate) models, reference images are not used even if they exist in state.
  const isEditModel = isQwenImageEditModel(model);
  const validRefImageConfigs = isEditModel
    ? selectRefImagesSlice(state).entities.filter(
        (entity) =>
          entity.isEnabled &&
          isQwenImageReferenceImageConfig(entity.config) &&
          entity.config.image !== null &&
          getGlobalReferenceImageWarnings(entity, model).length === 0
      )
    : [];

  if (validRefImageConfigs.length > 0) {
    // Use collector chaining to preserve reference image ordering.
    // Each image gets its own collect node; each subsequent collector chains
    // from the previous one via collection → collection edge.
    // (Same pattern as FLUX.2 Klein's kontext conditioning.)
    let prevCollect: Invocation<'collect'> | null = null;
    for (const { config } of validRefImageConfigs) {
      const imgField = zImageField.parse(config.image?.crop?.image ?? config.image?.original.image);
      const imageNode = g.addNode({
        type: 'image',
        id: getPrefixedId('qwen_ref_img'),
        image: imgField,
      });
      const collectNode = g.addNode({
        type: 'collect',
        id: getPrefixedId('qwen_ref_img_collect'),
      });
      g.addEdge(imageNode, 'image', collectNode, 'item');
      if (prevCollect !== null) {
        g.addEdge(prevCollect, 'collection', collectNode, 'collection');
      }
      prevCollect = collectNode;
    }
    assert(prevCollect !== null);
    // Pass reference images to text encoder for vision-language conditioning
    g.addEdge(prevCollect, 'collection', posCond, 'reference_images');

    // Also VAE-encode the first reference image as latents for the denoising transformer.
    // The transformer expects [noisy_patches ; ref_patches] in its sequence.
    const firstConfig = validRefImageConfigs[0]!;
    const firstImage = firstConfig.config.image?.crop?.image ?? firstConfig.config.image?.original.image;
    const firstImgField = zImageField.parse(firstImage);
    // Resize the reference image to ~1024² area preserving aspect ratio, matching the
    // diffusers QwenImageEdit(Plus)Pipeline's VAE_IMAGE_SIZE. The denoise node uses
    // the reference latent's own dimensions for RoPE, so the ref segment is encoded
    // at the resolution the model was trained on rather than the source image's
    // native size.
    const refDims = firstImage ? calculateQwenImageEditRefDimensions(firstImage.width, firstImage.height) : undefined;
    const refI2l = g.addNode({
      type: 'qwen_image_i2l',
      id: getPrefixedId('qwen_ref_i2l'),
      ...(refDims ? { width: refDims.width, height: refDims.height } : {}),
    });
    const refImageNode = g.addNode({
      type: 'image',
      id: getPrefixedId('qwen_ref_img_for_vae'),
      image: firstImgField,
    });
    g.addEdge(refImageNode, 'image', refI2l, 'image');
    g.addEdge(modelLoader, 'vae', refI2l, 'vae');
    g.addEdge(refI2l, 'latents', denoise, 'reference_latents');

    g.upsertMetadata({ ref_images: validRefImageConfigs }, 'merge');
  }

  const modelConfig = await fetchModelConfigWithTypeGuard(model.key, isNonRefinerMainModelConfig);
  assert(modelConfig.base === 'qwen-image');

  g.upsertMetadata({
    cfg_scale,
    negative_prompt: prompts.negative,
    model: Graph.getModelMetadataField(modelConfig),
    qwen_image_component_source: params.qwenImageComponentSource,
    qwen_image_vae: params.qwenImageVaeModel,
    qwen_image_qwen_vl_encoder: params.qwenImageQwenVLEncoderModel,
    qwen_image_quantization: params.qwenImageQuantization,
    qwen_image_shift: params.qwenImageShift,
    steps,
  });
  g.addEdgeToMetadata(seed, 'value', 'seed');
  g.addEdgeToMetadata(positivePrompt, 'value', 'positive_prompt');

  let canvasOutput: Invocation<ImageOutputNodes> = l2i;

  if (pidMode !== 'off') {
    // Inpaint/outpaint are not wired for PiD yet - only txt2img and img2img are supported (Fit and Native).
    if (generationMode === 'inpaint' || generationMode === 'outpaint') {
      throw new UnsupportedGenerationModeError(t('toast.pidUnsupportedMode'));
    }
    // PiD decodes at 4x the generation resolution. "Scale Before Processing" (Canvas) would silently inflate
    // the generation size to the model optimal, blowing up the decode - require it off (scaled == original).
    const { originalSize, scaledSize } = getOriginalAndScaledSizesForTextToImage(state);
    if (scaledSize.width !== originalSize.width || scaledSize.height !== originalSize.height) {
      throw new UnsupportedGenerationModeError(t('toast.pidScaleBeforeProcessingOff'));
    }
  }

  if (generationMode === 'txt2img') {
    if (pidMode !== 'off') {
      // PiD replaces the VAE decode entirely - drop the unused l2i (and its edges). The Qwen-Image VAE (from the
      // model loader) is wired so the node reads its per-channel latents_mean / latents_std.
      g.deleteNode(l2i.id);
      canvasOutput = addPidDecode({
        g,
        state,
        mode: pidMode,
        denoise,
        decodeNodeType: 'qwen_image_pid_decode',
        vaeSource: modelLoader,
        positivePrompt,
        seed,
      });
    } else {
      canvasOutput = addTextToImage({
        g,
        state,
        denoise,
        l2i,
      });
    }
    g.upsertMetadata({ generation_mode: 'qwen_image_txt2img' });
  } else if (generationMode === 'img2img') {
    assert(manager !== null);
    const i2l = g.addNode({
      type: 'qwen_image_i2l',
      id: getPrefixedId('qwen_image_i2l'),
    });

    if (pidMode === 'native') {
      // PiD replaces the VAE decode. Native: the bbox is the 4x target - generate at bbox / 4, PiD decodes
      // straight back up to the bbox (no downscale), so the full result composites onto the canvas region.
      g.deleteNode(l2i.id);
      canvasOutput = await addPidImageToImageNative({
        g,
        state,
        manager,
        denoise,
        decodeNodeType: 'qwen_image_pid_decode',
        i2l,
        vaeSource: modelLoader,
        positivePrompt,
        seed,
      });
    } else if (pidMode === 'fit') {
      // PiD replaces the VAE decode. Fit: generate at the bbox, PiD decodes 4x, then downscale back to the bbox.
      g.deleteNode(l2i.id);
      const { originalSize } = getOriginalAndScaledSizesForOtherModes(state);
      const pidDecode = buildPidDecodeChain({
        g,
        state,
        denoise,
        decodeNodeType: 'qwen_image_pid_decode',
        vaeSource: modelLoader,
        positivePrompt,
        seed,
        mode: 'fit',
        fitSize: originalSize,
      });
      canvasOutput = await addImageToImage({
        g,
        state,
        manager,
        denoise,
        l2i: pidDecode,
        i2l,
        vaeSource: modelLoader,
      });
    } else {
      canvasOutput = await addImageToImage({
        g,
        state,
        manager,
        denoise,
        l2i,
        i2l,
        vaeSource: modelLoader,
      });
    }
    g.upsertMetadata({ generation_mode: 'qwen_image_img2img' });
  } else if (generationMode === 'inpaint') {
    assert(manager !== null);
    const i2l = g.addNode({
      type: 'qwen_image_i2l',
      id: getPrefixedId('qwen_image_i2l'),
    });

    canvasOutput = await addInpaint({
      g,
      state,
      manager,
      l2i,
      i2l,
      denoise,
      vaeSource: modelLoader,
      modelLoader,
      seed,
    });
    g.upsertMetadata({ generation_mode: 'qwen_image_inpaint' });
  } else if (generationMode === 'outpaint') {
    assert(manager !== null);
    const i2l = g.addNode({
      type: 'qwen_image_i2l',
      id: getPrefixedId('qwen_image_i2l'),
    });

    canvasOutput = await addOutpaint({
      g,
      state,
      manager,
      l2i,
      i2l,
      denoise,
      vaeSource: modelLoader,
      modelLoader,
      seed,
    });
    g.upsertMetadata({ generation_mode: 'qwen_image_outpaint' });
  } else {
    assert<Equals<typeof generationMode, never>>(false);
  }

  if (state.system.shouldUseNSFWChecker) {
    canvasOutput = addNSFWChecker(g, canvasOutput);
  }

  if (state.system.shouldUseWatermarker) {
    canvasOutput = addWatermarker(g, canvasOutput);
  }

  g.updateNode(canvasOutput, selectCanvasOutputFields(state));

  if (selectActiveTab(state) === 'canvas') {
    g.upsertMetadata(selectCanvasMetadata(state));
  }

  g.setMetadataReceivingNode(canvasOutput);

  return {
    g,
    seed,
    positivePrompt,
  };
};