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.

9.1 KB
Raw Blame
import type { AnyModelDefaultSettings, ModelConfig, ModelTaxonomyType } from '@features/models/core/types';
import type { ModelSchedulerPolicy, SchedulerChoice } from '@features/models/ui/ModelsUiContext';
import type { TFunction } from 'i18next';

import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '@features/models/core/schemas';

export type DefaultSettingsModel = Pick<
  ModelConfig,
  'base' | 'default_settings' | 'format' | 'key' | 'name' | 'submodels' | 'type' | 'variant'
>;

const CONTROL_ADAPTER_TYPES = new Set(['controlnet', 't2i_adapter', 'control_lora']);

export const supportsDefaultSettings = (model: Pick<ModelConfig, 'type'>): boolean =>
  model.type === 'main' || model.type === 'lora' || CONTROL_ADAPTER_TYPES.has(model.type);

const PREPROCESSORS = [
  'canny_edge_detection',
  'color_map',
  'content_shuffle',
  'depth_anything_depth_estimation',
  'dw_openpose_detection',
  'hed_edge_detection',
  'lineart_anime_edge_detection',
  'lineart_edge_detection',
  'mediapipe_face_detection',
  'mlsd_detection',
  'normal_map',
  'pidi_edge_detection',
  'tile',
];

/** How the section renders a field's value; the component maps kind -> widget. */
export type DefaultSettingsControl =
  | { kind: 'number'; max?: number; min?: number; step?: number }
  | { kind: 'select'; options: readonly string[] }
  | { kind: 'combobox'; options: readonly SchedulerChoice[] }
  | {
      kind: 'model';
      modelTypes: readonly ModelTaxonomyType[];
      /**
       * Candidates are the VAEs Generate accepts for the edited model, which can be of another base. Until Generate's
       * rules arrive none is offered, though a stored one stays visible and clearable.
       */
      generateVaeRule: boolean;
      /** Placeholder shown for the backend's 'default' sentinel. */
      placeholderKey: string;
    };

export interface FieldSpec {
  key: keyof AnyModelDefaultSettings;
  labelKey: string;
  /** Omitted for a boolean default, where the row's own enable switch already expresses both states. */
  control?: DefaultSettingsControl;
  /** Value used when the toggle is switched on; also previewed while off. */
  defaultValue: unknown;
  /** Translation key for what applies while the toggle is off. */
  inheritLabelKey: string;
  /** The rules this row's choices come from are still loading or failed: it shows, disabled, without them. */
  pending?: 'loading' | 'unavailable';
}

/** Generate's rules for a main model's scheduler, or why they are not here yet. */
export type SchedulerFieldRules = ModelSchedulerPolicy | 'loading' | 'unavailable';

/**
 * Only fp8_storage=true changes backend behavior; the row toggle covers it without a redundant body switch. Mirror
 * backend exclusions.
 */
const FP8_STORAGE_FIELD: FieldSpec = {
  defaultValue: true,
  inheritLabelKey: 'models.defaultFieldInherited.fp8Storage',
  key: 'fp8_storage',
  labelKey: 'models.defaultFields.fp8Storage',
};

const VAE_FIELD: FieldSpec = {
  control: { kind: 'model', modelTypes: ['vae'], generateVaeRule: true, placeholderKey: 'models.defaultVae' },
  // The backend sentinel for "the compatible default VAE" — what legacy writes when the toggle is on but no specific
  // model is picked.
  defaultValue: 'default',
  inheritLabelKey: 'models.defaultFieldInherited.vae',
  key: 'vae',
  labelKey: 'models.defaultFields.vae',
};

/** Main-model fields after the VAE and scheduler rows. */
const MAIN_FIELDS: FieldSpec[] = [
  {
    control: { kind: 'number', max: 10000, min: 1 },
    defaultValue: 30,
    inheritLabelKey: 'models.defaultFieldInherited.steps',
    key: 'steps',
    labelKey: 'models.defaultFields.steps',
  },
  {
    control: { kind: 'number', max: 200, min: 1, step: 0.5 },
    defaultValue: 7,
    inheritLabelKey: 'models.defaultFieldInherited.cfgScale',
    key: 'cfg_scale',
    labelKey: 'models.defaultFields.cfgScale',
  },
  {
    control: { kind: 'number', max: 0.99, min: 0, step: 0.05 },
    defaultValue: 0,
    inheritLabelKey: 'models.defaultFieldInherited.cfgRescale',
    key: 'cfg_rescale_multiplier',
    labelKey: 'models.defaultFields.cfgRescale',
  },
  {
    control: { kind: 'number', max: 20, min: 1, step: 0.5 },
    defaultValue: 4,
    inheritLabelKey: 'models.defaultFieldInherited.guidance',
    key: 'guidance',
    labelKey: 'models.defaultFields.guidance',
  },
  {
    control: { kind: 'number', max: 8192, min: 64, step: 8 },
    defaultValue: 1024,
    inheritLabelKey: 'models.defaultFieldInherited.width',
    key: 'width',
    labelKey: 'models.defaultFields.width',
  },
  {
    control: { kind: 'number', max: 8192, min: 64, step: 8 },
    defaultValue: 1024,
    inheritLabelKey: 'models.defaultFieldInherited.height',
    key: 'height',
    labelKey: 'models.defaultFields.height',
  },
  {
    control: { kind: 'select', options: ['fp16', 'fp32'] },
    defaultValue: 'fp16',
    inheritLabelKey: 'models.defaultFieldInherited.vaePrecision',
    key: 'vae_precision',
    labelKey: 'models.defaultFields.vaePrecision',
  },
];

const SCHEDULER_FIELD = {
  inheritLabelKey: 'models.defaultFieldInherited.scheduler',
  key: 'scheduler',
  labelKey: 'models.defaultFields.scheduler',
} as const;

/** Generate's options and default for the base; see {@link getFieldsForModel}. */
const getSchedulerField = (rules: SchedulerFieldRules, stored: string | null): FieldSpec =>
  typeof rules === 'string'
    ? {
        ...SCHEDULER_FIELD,
        // Without the rules, only a stored value can be named; it stays visible.
        control: { kind: 'combobox', options: stored === null ? [] : [{ label: stored, value: stored }] },
        defaultValue: stored,
        pending: rules,
      }
    : { ...SCHEDULER_FIELD, control: { kind: 'combobox', options: rules.options }, defaultValue: rules.defaultValue };

const LORA_FIELDS: FieldSpec[] = [
  {
    control: { kind: 'number', max: 10, min: -10, step: 0.05 },
    defaultValue: 0.75,
    inheritLabelKey: 'models.defaultFieldInherited.weight',
    key: 'weight',
    labelKey: 'models.defaultFields.weight',
  },
  {
    control: { kind: 'number', max: 10, min: -10, step: 0.05 },
    defaultValue: -1,
    inheritLabelKey: 'models.defaultFieldInherited.weightMin',
    key: 'weight_min',
    labelKey: 'models.defaultFields.weightMin',
  },
  {
    control: { kind: 'number', max: 10, min: -10, step: 0.05 },
    defaultValue: 2,
    inheritLabelKey: 'models.defaultFieldInherited.weightMax',
    key: 'weight_max',
    labelKey: 'models.defaultFields.weightMax',
  },
];

const CONTROL_ADAPTER_FIELDS: FieldSpec[] = [
  {
    control: { kind: 'select', options: PREPROCESSORS },
    defaultValue: 'canny_edge_detection',
    inheritLabelKey: 'models.defaultFieldInherited.preprocessor',
    key: 'preprocessor',
    labelKey: 'models.defaultFields.preprocessor',
  },
];

/**
 * `fp8StorageSupported` is the backend's answer (see `data/fp8StorageSupportStore`), not a rule applied here: it
 * depends on the model's type, its format and whether its loader implements the cast, which this module cannot see.
 *
 * `schedulerRules` is Generate's rule set for a main model's base. Where the base's graph ignores the scheduler the row
 * is left out, as Generate hides it, unless a stored value needs a row to be cleared. While the rules load or after
 * they fail the row shows disabled, so it neither jumps in later nor silently disappears.
 */
export const getFieldsForModel = (
  model: Pick<ModelConfig, 'default_settings' | 'type'>,
  fp8StorageSupported: boolean,
  schedulerRules: SchedulerFieldRules | null
): FieldSpec[] => {
  const fp8Fields = fp8StorageSupported ? [FP8_STORAGE_FIELD] : [];

  if (model.type === 'main') {
    const storedScheduler = model.default_settings?.scheduler ?? null;
    const schedulerFields =
      schedulerRules &&
      (typeof schedulerRules === 'string' || schedulerRules.appliesToGraph || storedScheduler !== null)
        ? [getSchedulerField(schedulerRules, storedScheduler)]
        : [];
    return [VAE_FIELD, ...schedulerFields, ...MAIN_FIELDS, ...fp8Fields];
  }

  if (model.type === 'lora') {
    return LORA_FIELDS;
  }

  return [...CONTROL_ADAPTER_FIELDS, ...fp8Fields];
};

export const validateDefaults = (
  model: Pick<ModelConfig, 'type'>,
  settings: AnyModelDefaultSettings,
  t: TFunction
): string | null => {
  if (model.type === 'main') {
    const result = mainDefaultSettingsSchema.safeParse({
      cfgRescaleMultiplier: settings.cfg_rescale_multiplier ?? null,
      cfgScale: settings.cfg_scale ?? null,
      components: settings.components ?? null,
      guidance: settings.guidance ?? null,
      height: settings.height ?? null,
      scheduler: settings.scheduler ?? null,
      steps: settings.steps ?? null,
      vae: settings.vae ?? null,
      vaePrecision: settings.vae_precision ?? null,
      width: settings.width ?? null,
    });

    return result.success ? null : (result.error.issues[0]?.message ?? t('models.invalidDefaultSettings'));
  }

  if (model.type === 'lora') {
    const result = loraDefaultSettingsSchema.safeParse({
      weight: settings.weight ?? null,
      weightMax: settings.weight_max ?? null,
      weightMin: settings.weight_min ?? null,
    });

    return result.success ? null : (result.error.issues[0]?.message ?? t('models.invalidDefaultSettings'));
  }

  return null;
};