Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

7.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import type { PersistedChatSettings } from "../api/chat-settings-api";
import type { PersistedInferenceParams } from "../types/runtime";
import { isExternalModelId } from "../external-providers";
import { normalizeModelIdentity } from "../../hub/lib/model-identity";
import {
  isOllamaManifestRef,
  resolveQwenThinkingParams,
} from "./qwen-sampling-table";

function isOpaqueModelRef(modelId: string): boolean {
  return isExternalModelId(modelId) || isOllamaManifestRef(modelId);
}

const LEGACY_QWEN_DEFAULTS = {
  temperature: 0.6,
  topP: 0.95,
  topK: 20,
  minP: 0.01,
  repetitionPenalty: 1.0,
  presencePenalty: 0.0,
} as const;

const LEGACY_GLOBAL_QWEN_DEFAULTS = {
  temperature: 0.6,
  topP: 0.95,
  minP: 0.01,
  presencePenalty: 0.0,
} as const;

const LEGACY_OPTIONAL_GLOBAL_QWEN_DEFAULTS = {
  topK: 20,
  repetitionPenalty: 1.0,
} as const;

/** Reads the shared resolver table; null when it gives no presencePenalty. */
function currentQwenDefaults(
  modelId: string,
  thinkingOn: boolean,
): PersistedInferenceParams | null {
  const resolved = resolveQwenThinkingParams(modelId, thinkingOn);
  if (resolved === null || resolved.presencePenalty === undefined) {
    return null;
  }
  return {
    temperature: resolved.temperature,
    topP: resolved.topP,
    topK: resolved.topK,
    minP: resolved.minP,
    presencePenalty: resolved.presencePenalty,
  };
}

export function isPresenceBumpQwen(modelId: string): boolean {
  return (
    resolveQwenThinkingParams(modelId, true)?.presencePenalty !== undefined
  );
}

function isLegacyQwenDefaultSnapshot(
  params: PersistedInferenceParams,
): boolean {
  return Object.entries(LEGACY_QWEN_DEFAULTS).every(
    ([key, value]) => params[key as keyof PersistedInferenceParams] === value,
  );
}

function isLegacyGlobalQwenDefaultSnapshot(
  params: PersistedInferenceParams | undefined,
): boolean {
  return (
    params !== undefined &&
    Object.entries(LEGACY_GLOBAL_QWEN_DEFAULTS).every(
      ([key, value]) => params[key as keyof PersistedInferenceParams] === value,
    ) &&
    Object.entries(LEGACY_OPTIONAL_GLOBAL_QWEN_DEFAULTS).every(
      ([key, value]) => {
        const stored = params[key as keyof PersistedInferenceParams];
        return stored === undefined || stored === value;
      },
    )
  );
}

function changedDefaults(
  legacy: PersistedInferenceParams,
  current: PersistedInferenceParams,
): PersistedInferenceParams {
  const changed: PersistedInferenceParams = {};
  for (const [key, value] of Object.entries(current)) {
    const field = key as keyof PersistedInferenceParams;
    if (legacy[field] !== value) {
      (changed as Record<string, unknown>)[key] = value;
    }
  }
  return changed;
}

function isBuiltInDefault(settings: PersistedChatSettings): boolean {
  return (
    (settings.activePreset === undefined ||
      settings.activePreset === "Default") &&
    (settings.activePresetSource === undefined ||
      settings.activePresetSource === "builtin-default")
  );
}

export type QwenDefaultsMigration = {
  settings: PersistedChatSettings;
  patch: PersistedChatSettings | null;
  migratedModelIds: string[];
};

function migrateStoredModelDefaults(
  stored: Record<string, PersistedInferenceParams> | undefined,
  activeCheckpoint: string,
  currentDefaults: PersistedInferenceParams,
): {
  migratedModelIds: string[];
  migratedByModel: Record<string, PersistedInferenceParams>;
  patchByModel: Record<string, PersistedInferenceParams>;
} {
  const migratedModelIds: string[] = [];
  const migratedByModel: Record<string, PersistedInferenceParams> = {};
  const patchByModel: Record<string, PersistedInferenceParams> = {};
  const storedEntries = Object.entries(stored ?? {});
  // normalizeModelIdentity, not toLowerCase: POSIX paths are case-sensitive.
  const activeIdentity = normalizeModelIdentity(activeCheckpoint);
  const activeIsOpaque = isOpaqueModelRef(activeCheckpoint);
  // Only a sole alias: with two spellings one may hold the user's own sampling.
  const aliases = activeIsOpaque
    ? []
    : storedEntries.filter(
        ([modelId]) =>
          !isOpaqueModelRef(modelId) &&
          normalizeModelIdentity(modelId) === activeIdentity,
      );
  const activeStoredId =
    storedEntries.find(([modelId]) => modelId === activeCheckpoint)?.[0] ??
    (aliases.length === 1 ? aliases[0][0] : undefined);
  for (const [modelId, entry] of storedEntries) {
    const isActiveCheckpoint = modelId === activeStoredId;
    if (
      isActiveCheckpoint &&
      isPresenceBumpQwen(modelId) &&
      isLegacyQwenDefaultSnapshot(entry)
    ) {
      const normalizedModelId = activeCheckpoint;
      const migratedEntry = { ...entry, ...currentDefaults };
      migratedModelIds.push(normalizedModelId);
      migratedByModel[normalizedModelId] = migratedEntry;
      patchByModel[normalizedModelId] =
        modelId === normalizedModelId
          ? changedDefaults(entry, currentDefaults)
          : migratedEntry;
      if (modelId !== normalizedModelId) {
        // The server merge only sets keys, so the old spelling survives unless overwritten.
        migratedByModel[modelId] = migratedEntry;
        patchByModel[modelId] = changedDefaults(entry, currentDefaults);
      }
    } else {
      migratedByModel[modelId] = entry;
    }
  }
  return { migratedModelIds, migratedByModel, patchByModel };
}

/** Upgrade the old generic-Qwen snapshot only on an exact match of every sampling field. */
export function migrateLegacyQwenDefaults(
  settings: PersistedChatSettings,
  activeCheckpoint: string,
  thinkingOn: boolean,
  globalBelongsToActiveCheckpoint = false,
  migrateOwnedGlobalAlongsideModelMemory = false,
): QwenDefaultsMigration {
  const storedRaw = settings.inferenceParamsByModel;
  const stored =
    storedRaw !== undefined && Object.keys(storedRaw).length > 0
      ? storedRaw
      : undefined;
  if (!isBuiltInDefault(settings)) {
    return { settings, patch: null, migratedModelIds: [] };
  }

  const currentDefaults = currentQwenDefaults(activeCheckpoint, thinkingOn);
  if (currentDefaults === null) {
    return { settings, patch: null, migratedModelIds: [] };
  }
  const currentGlobalDefaults: PersistedInferenceParams = {
    temperature: currentDefaults.temperature,
    topP: currentDefaults.topP,
    minP: currentDefaults.minP,
    presencePenalty: currentDefaults.presencePenalty,
  };

  const { migratedModelIds, migratedByModel, patchByModel } =
    migrateStoredModelDefaults(stored, activeCheckpoint, currentDefaults);

  const migrateGlobal =
    (stored === undefined || migrateOwnedGlobalAlongsideModelMemory) &&
    globalBelongsToActiveCheckpoint &&
    isPresenceBumpQwen(activeCheckpoint) &&
    isLegacyGlobalQwenDefaultSnapshot(settings.inferenceParams);
  const globalChanges = migrateGlobal
    ? changedDefaults(settings.inferenceParams ?? {}, currentGlobalDefaults)
    : null;
  // An already-current global yields {}, which is truthy and would send an empty patch.
  const globalPatch =
    globalChanges && Object.keys(globalChanges).length > 0
      ? globalChanges
      : null;

  if (migratedModelIds.length === 0 && !globalPatch) {
    return { settings, patch: null, migratedModelIds };
  }

  return {
    settings: {
      ...settings,
      ...(stored ? { inferenceParamsByModel: migratedByModel } : {}),
      ...(migrateGlobal
        ? {
            inferenceParams: {
              ...settings.inferenceParams,
              ...currentGlobalDefaults,
            },
          }
        : {}),
    },
    patch: {
      ...(migratedModelIds.length > 0
        ? { inferenceParamsByModel: patchByModel }
        : {}),
      ...(globalPatch ? { inferenceParams: globalPatch } : {}),
    },
    migratedModelIds,
  };
}