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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio Hub: filter models by parameter count, context length and publisher (#13363)
Daniel Han814c430654a0
diff --git a/studio/frontend/src/features/hub/catalog/model-search-filters.tsx b/studio/frontend/src/features/hub/catalog/model-search-filters.tsxnew file mode 100644index 00000000000..9e9857998f5--- /dev/null+++ b/studio/frontend/src/features/hub/catalog/model-search-filters.tsx@@ -0,0 +1,178 @@+// 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 { Input } from "@/components/ui/input";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { FilterIcon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useId, useState } from "react";+import {+ type ModelSearchFilters,+ hasModelSearchFilters,+} from "../lib/model-search-filters";++export function ModelSearchFiltersControl({+ value,+ onChange,+ className,+}: {+ value: ModelSearchFilters;+ onChange: (value: ModelSearchFilters) => void;+ className?: string;+}) {+ const [open, setOpen] = useState(false);+ const [draft, setDraft] = useState(value);+ const id = useId();+ const invalid =+ (draft.minParams !== undefined &&+ draft.maxParams !== undefined &&+ draft.minParams > draft.maxParams) ||+ (draft.minContext !== undefined &&+ draft.maxContext !== undefined &&+ draft.minContext > draft.maxContext);+ return (+ <Popover+ open={open}+ onOpenChange={(next) => {+ if (next) {+ setDraft(value);+ }+ setOpen(next);+ }}+ >+ {/* Icon-sized so the Discover toolbar keeps its existing single-row layout. */}+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <PopoverTrigger asChild={true}>+ <button+ type="button"+ className={className}+ aria-label="Model size and publisher filters"+ >+ <HugeiconsIcon+ icon={FilterIcon}+ strokeWidth={1.75}+ className="size-4"+ />+ {hasModelSearchFilters(value) && (+ <span+ aria-hidden="true"+ className="absolute right-1.5 top-1.5 size-1.5 rounded-full bg-primary"+ />+ )}+ </button>+ </PopoverTrigger>+ </TooltipTrigger>+ <TooltipContent side="bottom" sideOffset={6}>+ More filters+ </TooltipContent>+ </Tooltip>+ <PopoverContent+ align="end"+ sideOffset={8}+ className="w-80 max-w-[calc(100vw-2rem)]"+ >+ <form+ className="flex flex-col gap-4"+ onSubmit={(event) => {+ event.preventDefault();+ if (invalid) {+ return;+ }+ onChange(draft);+ setOpen(false);+ }}+ >+ {(+ [+ ["Parameters (billions)", "minParams", "maxParams", 1e9],+ ["Context length (tokens)", "minContext", "maxContext", 1],+ ] as const+ ).map(([label, min, max, scale]) => (+ <fieldset key={min} className="space-y-2">+ <legend className="text-sm font-medium">{label}</legend>+ <div className="grid grid-cols-2 gap-2">+ {([min, max] as const).map((key, index) => (+ <label+ key={key}+ htmlFor={`${id}-${key}`}+ className="space-y-1 text-xs text-muted-foreground"+ >+ <span>{index === 0 ? "Minimum" : "Maximum"}</span>+ <Input+ id={`${id}-${key}`}+ aria-label={`${index === 0 ? "Minimum" : "Maximum"} ${label.toLowerCase()}`}+ type="number"+ min={0}+ step={scale === 1 ? 1 : "any"}+ placeholder="Any"+ value={draft[key] === undefined ? "" : draft[key] / scale}+ onChange={(event) =>+ setDraft({+ ...draft,+ [key]:+ event.target.value === ""+ ? undefined+ : Math.round(event.target.valueAsNumber * scale),+ })+ }+ />+ </label>+ ))}+ </div>+ </fieldset>+ ))}+ <label className="flex items-center gap-2 text-sm">+ <input+ type="checkbox"+ checked={draft.organizationsOnly ?? false}+ onChange={(event) =>+ setDraft({ ...draft, organizationsOnly: event.target.checked })+ }+ />+ Organizations only (hide personal accounts)+ </label>+ <p className="text-xs text-muted-foreground">+ Ranges include both limits. Models without the requested metadata+ are excluded. Context is the published limit, not your device's+ capacity.+ </p>+ {invalid && (+ <p role="alert" className="text-xs text-destructive">+ Minimum must not exceed maximum.+ </p>+ )}+ <div className="flex justify-end gap-2">+ <button+ type="button"+ className="rounded-full px-3 py-2 text-sm"+ onClick={() => {+ setDraft({});+ onChange({});+ setOpen(false);+ }}+ >+ Clear+ </button>+ <button+ type="submit"+ disabled={invalid}+ className="rounded-full bg-primary px-3 py-2 text-sm text-primary-foreground disabled:opacity-50"+ >+ Apply filters+ </button>+ </div>+ </form>+ </PopoverContent>+ </Popover>+ );+}diff --git a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx b/studio/frontend/src/features/hub/catalog/models-toolbar.tsxindex dd6a42b4ee9..1927545730d 100644--- a/studio/frontend/src/features/hub/catalog/models-toolbar.tsx+++ b/studio/frontend/src/features/hub/catalog/models-toolbar.tsx@@ -41,6 +41,8 @@ import type {ResourceTypeFilter,} from "../types";import { type HubOption, HubOptionMenu } from "./hub-option-menu";+import type { ModelSearchFilters } from "../lib/model-search-filters";+import { ModelSearchFiltersControl } from "./model-search-filters";import { RecentSearches } from "./recent-searches";// Widened so the format dropdown can carry the "Fine-tune ready" pseudo-option,@@ -78,7 +80,11 @@ export const ModelsToolbar = memo(function ModelsToolbar({onFreeUpSpace,onOpenFineTune,npuAvailable = false,+ searchFilters,+ onSearchFiltersChange,}: {+ searchFilters: ModelSearchFilters;+ onSearchFiltersChange: (value: ModelSearchFilters) => void;tab: ModelsTab;onTabChange: (tab: ModelsTab) => void;query: string;@@ -444,6 +450,17 @@ export const ModelsToolbar = memo(function ModelsToolbar({/>)}+ {isDiscover && !isDataset && !npuList && hubSource !== "modelscope" && (+ <ModelSearchFiltersControl+ value={searchFilters}+ onChange={onSearchFiltersChange}+ className={cn(+ triggerBase,+ "relative inline-flex size-9 shrink-0 items-center justify-center rounded-full p-0",+ )}+ />+ )}+{tab === "discover" && !npuList && (<HubOptionMenuvalue={sortBy}diff --git a/studio/frontend/src/features/hub/hooks/use-discover-search.ts b/studio/frontend/src/features/hub/hooks/use-discover-search.tsindex 900d1a0bd03..277ec3c14ba 100644--- a/studio/frontend/src/features/hub/hooks/use-discover-search.ts+++ b/studio/frontend/src/features/hub/hooks/use-discover-search.ts@@ -4,6 +4,7 @@import { useCallback, useEffect, useMemo, useRef } from "react";import { useHubName } from "@/lib/hf-endpoint";import { toast } from "@/lib/toast";+import type { ModelSearchFilters } from "../lib/model-search-filters";import {clearRemoteBackoff,hubAuthFailure,@@ -102,6 +103,7 @@ export function useDiscoverSearch({direction,channel,ownerScope,+ filters,}: {debouncedQuery: string;accessToken: string | undefined;@@ -111,6 +113,7 @@ export function useDiscoverSearch({direction: HfSortDirection;channel: HfModelSearchChannel | null;ownerScope: "unsloth" | "all";+ filters?: ModelSearchFilters;}): DiscoverSearch {const { phase, failure } = useHubAvailability();const hub = useHubName();@@ -134,6 +137,7 @@ export function useDiscoverSearch({enabled: canProbe && isDiscoverTab && !isDatasetMode,keepUnsupportedTags: true,channel,+ filters,});const datasetSearch = useHubDatasetSearch(debouncedQuery, {accessToken,diff --git a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts b/studio/frontend/src/features/hub/hooks/use-hub-model-search.tsindex 319b31c1273..020dd45c57b 100644--- a/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts+++ b/studio/frontend/src/features/hub/hooks/use-hub-model-search.ts@@ -4,7 +4,7 @@import { usePlatformStore } from "@/config/env";import { getHfEndpoint, useHfEndpoint } from "@/lib/hf-endpoint";import type { PipelineType } from "@huggingface/hub";-import { listModels } from "@huggingface/hub";+import { listModels, modelInfo } from "@huggingface/hub";import {startTransition,useCallback,@@ -27,6 +27,12 @@ import {type UnslothSupportStatus,classifyUnslothSupport,} from "../lib/unsloth-support";+import {+ filterModelListing,+ hasModelSearchFilters,+ parameterRange,+ type ModelSearchFilters,+} from "../lib/model-search-filters";import { pullBatch, useHubPaginatedSearch } from "./use-hub-paginated-search";// "gguf" is not in the @huggingface/hub expandable-key type, but the listing supports@@ -133,6 +139,7 @@ function makeSortFetch(sortBy: HfSortKey | undefined,direction: HfSortDirection,signal?: AbortSignal,+ parameterFilter = "",): typeof fetch {return (input, init) => {const rawUrl =@@ -142,6 +149,8 @@ function makeSortFetch(? input.toString(): input.url;const url = new URL(rawUrl);+ if (parameterFilter)+ url.searchParams.set("num_parameters", parameterFilter);if (sortBy && !url.searchParams.has("sort")) {url.searchParams.set("sort", sortBy);@@ -169,6 +178,7 @@ function makeMapModel() {const suffixLower = idSuffix.toLowerCase();return (raw: unknown): HfModelResult | null => {+ if (raw === null) return null;const m = raw as {name: string;downloads?: number;@@ -257,6 +267,8 @@ const UNSLOTH_PREFETCH = 20;const UNSLOTH_QUERY_PREFETCH = 3;/** With a publisher query, fewer unsloth results before the pinned publisher model. */const UNSLOTH_PINNED_PREFETCH = 4;+/** Rejected unsloth rows a filtered search scans before moving on to general results. */+const UNSLOTH_FILTER_REJECT_LIMIT = 40;/** Matches a valid "owner/repo" identifier (exactly two non-empty segments). */const PUBLISHER_RE = /^([^/\s]+)\/([^/\s]+)$/;@@ -276,6 +288,10 @@ function primeFromListing(}}+type ModelListingTransform = (+ iterator: AsyncGenerator<unknown>,+) => AsyncGenerator<unknown>;+/** Merged generator yielding unsloth-owned models first, then deduped general results. */async function* mergedModelIterator(query: string,@@ -285,6 +301,8 @@ async function* mergedModelIterator(sortBy: HfSortKey = "downloads",direction: HfSortDirection = "desc",signal?: AbortSignal,+ parameterFilter = "",+ filterPriority?: ModelListingTransform,): AsyncGenerator<unknown> {const tasks = normalizeTaskFilter(task);const common = {@@ -298,7 +316,7 @@ async function* mergedModelIterator(listModels({hubUrl: getHfEndpoint(),search: { query, owner: "unsloth", ...(task ? { task } : {}) },- fetch: makeSortFetch(sortBy, direction, taskSignal),+ fetch: makeSortFetch(sortBy, direction, taskSignal, parameterFilter),...common,}) as AsyncGenerator<unknown>,signal,@@ -309,7 +327,7 @@ async function* mergedModelIterator(listModels({hubUrl: getHfEndpoint(),search: { query, ...(task ? { task } : {}) },- fetch: makeSortFetch(sortBy, direction, taskSignal),+ fetch: makeSortFetch(sortBy, direction, taskSignal, parameterFilter),...common,}) as AsyncGenerator<unknown>,signal,@@ -335,7 +353,15 @@ async function* mergedModelIterator(// Phase 1: unsloth models firstconst seen = new Set<string>();let count = 0;- for await (const model of unslothIter) {+ let rejected = 0;+ for await (const model of filterPriority+ ? filterPriority(unslothIter)+ : unslothIter) {+ if (model === null) {+ yield null;+ if (++rejected >= UNSLOTH_FILTER_REJECT_LIMIT) break;+ continue;+ }const m = model as { name?: string };if (m.name) {seen.add(m.name);@@ -379,6 +405,7 @@ async function* priorityThenListingIterator(sortBy: HfSortKey = "downloads",direction: HfSortDirection = "desc",signal?: AbortSignal,+ parameterFilter = "",): AsyncGenerator<unknown> {const tasks = normalizeTaskFilter(task);const common = {@@ -414,7 +441,7 @@ async function* priorityThenListingIterator(listModels({hubUrl: getHfEndpoint(),search: { owner: "unsloth", ...(task ? { task } : {}) },- fetch: makeSortFetch(sortBy, direction, taskSignal),+ fetch: makeSortFetch(sortBy, direction, taskSignal, parameterFilter),...common,}) as AsyncGenerator<unknown>,signal,@@ -446,6 +473,7 @@ function createChannelIterator(sortDirection: HfSortDirection;accessToken?: string;signal: AbortSignal;+ parameterFilter?: string;},): AsyncGenerator<unknown> {const channelTags =@@ -459,7 +487,12 @@ function createChannelIterator(...(channelTags ? { tags: channelTags } : {}),},additionalFields: ALL_FIELDS,- fetch: makeSortFetch(opts.sortBy, opts.sortDirection, opts.signal),+ fetch: makeSortFetch(+ opts.sortBy,+ opts.sortDirection,+ opts.signal,+ opts.parameterFilter,+ ),sort: opts.sortBy,...(opts.accessToken? { credentials: { accessToken: opts.accessToken } }@@ -480,6 +513,8 @@ async function* channelUnslothFirstIterator(sortDirection: HfSortDirection;accessToken?: string;signal: AbortSignal;+ parameterFilter?: string;+ filterPriority?: ModelListingTransform;},): AsyncGenerator<unknown> {const queryString = opts.query || channel.query || undefined;@@ -496,12 +531,25 @@ async function* channelUnslothFirstIterator(...(channel.tags ? { tags: channel.tags } : {}),},additionalFields: ALL_FIELDS,- fetch: makeSortFetch(opts.sortBy, opts.sortDirection, opts.signal),+ fetch: makeSortFetch(+ opts.sortBy,+ opts.sortDirection,+ opts.signal,+ opts.parameterFilter,+ ),sort: opts.sortBy,...creds,}) as AsyncGenerator<unknown>;let count = 0;- for await (const model of unslothIter) {+ let rejected = 0;+ for await (const model of opts.filterPriority+ ? opts.filterPriority(unslothIter)+ : unslothIter) {+ if (model === null) {+ yield null;+ if (++rejected >= UNSLOTH_FILTER_REJECT_LIMIT) break;+ continue;+ }const name = (model as { name?: string }).name;if (name) seen.add(name);yield model;@@ -515,7 +563,12 @@ async function* channelUnslothFirstIterator(...(channel.tags ? { tags: channel.tags } : {}),},additionalFields: ALL_FIELDS,- fetch: makeSortFetch(opts.sortBy, opts.sortDirection, opts.signal),+ fetch: makeSortFetch(+ opts.sortBy,+ opts.sortDirection,+ opts.signal,+ opts.parameterFilter,+ ),sort: opts.sortBy,...creds,}) as AsyncGenerator<unknown>;@@ -602,6 +655,7 @@ export function useHubModelSearch(enabled?: boolean;keepUnsupportedTags?: boolean;channel?: HfModelSearchChannel | null;+ filters?: ModelSearchFilters;},) {const {@@ -616,6 +670,7 @@ export function useHubModelSearch(enabled = true,keepUnsupportedTags = false,channel = null,+ filters,} = options ?? {};const unslothOnly = ownerScope === "unsloth";@@ -643,8 +698,10 @@ export function useHubModelSearch(}, [query]);const hfEndpoint = useHfEndpoint();- const createIter = useCallback(- (signal: AbortSignal) => {+ const hasFilters = !!filters && hasModelSearchFilters(filters);+ const filterRange = filters ? parameterRange(filters) : "";+ const createListing = useCallback(+ (signal: AbortSignal, filterPriority?: ModelListingTransform) => {// Channel scoping bypasses the unsloth-merge iterator: a hard owner/tag filter shows that slice.if (channelOwner || channelTagsKey || channelQuery) {const channelTags = channelTagsKey@@ -664,6 +721,7 @@ export function useHubModelSearch(sortDirection,accessToken,signal,+ parameterFilter: filterRange,},);}@@ -677,6 +735,8 @@ export function useHubModelSearch(sortDirection,accessToken,signal,+ parameterFilter: filterRange,+ filterPriority,},);}@@ -693,6 +753,7 @@ export function useHubModelSearch(sortDirection,accessToken,signal,+ parameterFilter: filterRange,},);}@@ -706,8 +767,22 @@ export function useHubModelSearch(sortBy,sortDirection,signal,+ filterRange,) as AsyncGenerator<unknown>;}+ if (hasFilters && pinUnslothFirst && !unslothOnly) {+ return mergedModelIterator(+ "",+ task,+ accessToken,+ undefined,+ sortBy,+ sortDirection,+ signal,+ filterRange,+ filterPriority,+ );+ }return mergeTaskIterators(normalizeTaskFilter(task),(task, taskSignal) =>@@ -719,7 +794,12 @@ export function useHubModelSearch(...(task ? { task } : {}),},additionalFields: ALL_FIELDS,- fetch: makeSortFetch(sortBy, sortDirection, taskSignal),+ fetch: makeSortFetch(+ sortBy,+ sortDirection,+ taskSignal,+ filterRange,+ ),sort: sortBy,...(accessToken ? { credentials: { accessToken } } : {}),}) as AsyncGenerator<unknown>,@@ -732,7 +812,7 @@ export function useHubModelSearch(hubUrl: getHfEndpoint(),search: { query: searchQuery, owner: "unsloth" },additionalFields: ALL_FIELDS,- fetch: makeSortFetch(sortBy, sortDirection, signal),+ fetch: makeSortFetch(sortBy, sortDirection, signal, filterRange),sort: sortBy,...(accessToken ? { credentials: { accessToken } } : {}),}) as AsyncGenerator<unknown>;@@ -744,10 +824,12 @@ export function useHubModelSearch(searchQuery,undefined,accessToken,- pinnedId,+ hasFilters ? undefined : pinnedId,sortBy,sortDirection,signal,+ filterRange,+ filterPriority,) as AsyncGenerator<unknown>;},[@@ -764,7 +846,76 @@ export function useHubModelSearch(channelQuery,pinUnslothFirst,unslothOnly,+ hasFilters,+ filterRange,+ ],+ );++ const createIter = useCallback(+ (signal: AbortSignal) => {+ if (!filters || !hasFilters) return createListing(signal);+ const metadata = new Map<+ string,+ Promise<Record<string, unknown> | null>+ >();+ const requestJson = async (path: string) => {+ const response = await fetchWithTimeout(+ `${hfEndpoint}${path}`,+ {+ signal,+ ...(accessToken+ ? { headers: { Authorization: `Bearer ${accessToken}` } }+ : {}),+ },+ HF_SEARCH_TIMEOUT_MS,+ );+ if ([401, 403, 404].includes(response.status)) return null;+ if (!response.ok) {+ throw new Error(+ `Model filter metadata request failed (HTTP ${response.status})`,+ );+ }+ // One repo's malformed config.json must not abort the whole search.+ return response.json().catch(() => null);+ };+ const fetchJson = (path: string) => {+ let request = metadata.get(path);+ if (!request) {+ request = requestJson(path);+ metadata.set(path, request);+ }+ return request;+ };+ const filterPriority: ModelListingTransform = (iterator) =>+ filterModelListing(iterator, filters, fetchJson);+ const iterator = createListing(signal, filterPriority);+ const pinnedPromise =+ pinnedId &&+ !unslothOnly &&+ !channelOwner &&+ !channelTagsKey &&+ !channelQuery+ ? modelInfo({+ hubUrl: hfEndpoint,+ name: pinnedId,+ additionalFields: ALL_FIELDS,+ fetch: makeHfFetch(signal),+ ...(accessToken ? { credentials: { accessToken } } : {}),+ }).catch(() => null)+ : undefined;+ return filterModelListing(iterator, filters, fetchJson, pinnedPromise);+ },+ [+ createListing,+ filters,+ hasFilters,+ pinnedId,+ unslothOnly,+ channelOwner,+ channelTagsKey,+ channelQuery,hfEndpoint,+ accessToken,],);diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsxindex e295c5b186c..7a46403b000 100644--- a/studio/frontend/src/features/hub/hub-page.tsx+++ b/studio/frontend/src/features/hub/hub-page.tsx@@ -65,6 +65,10 @@ import {InventoryTypeFilterControl,ResultListHeader,} from "./catalog/models-table";+import {+ hasModelSearchFilters,+ type ModelSearchFilters,+} from "./lib/model-search-filters";import { ModelsToolbar } from "./catalog/models-toolbar";import { NpuCatalogList } from "./catalog/npu-catalog-list";import { OnDeviceFoldersDialog } from "./catalog/on-device-folders-dialog";@@ -143,6 +147,8 @@ import type {SelectedModelView,} from "./types";+const NO_SEARCH_FILTERS: ModelSearchFilters = {};+const MODELS_TAB_STORAGE_KEY = "unsloth.hub.modelsTab";const ALL_MODELS_VIEW_STORAGE_KEY = "unsloth.hub.allModelsView";const INVENTORY_SORT_STORAGE_KEY = "unsloth.hub.inventorySort";@@ -630,6 +636,14 @@ export function ModelsPage() {},[isDiscoverTab, urlSection, navigate],);+ const hubSource = useHubSource();+ const [storedSearchFilters, setSearchFilters] = useState<ModelSearchFilters>(+ {},+ );+ // The publisher and config.json lookups are Hugging Face endpoints.+ const searchFilters =+ hubSource === "modelscope" ? NO_SEARCH_FILTERS : storedSearchFilters;+ const hasSearchFilters = hasModelSearchFilters(searchFilters);const [capabilityFilter, setCapabilityFilter] =useState<CapabilityFilter>("all");const [allModelsView, setAllModelsViewState] = useState<AllModelsView>(@@ -668,6 +682,8 @@ export function ModelsPage() {const handleTabChange = useCallback((next: ModelsTab) => {setSortBrowseActive(false);+ // The filters control is Discover-only, so a hidden filter must not reapply on return.+ setSearchFilters({});setModelsTab(next);},[setModelsTab],@@ -679,6 +695,7 @@ export function ModelsPage() {setResourceType(next);setDownloadedFormat("all");setCapabilityFilter("all");+ setSearchFilters({});setSortBrowseActive(false);if (next === "models") {const preset = findChannel(DEFAULT_DISCOVER_CHANNEL);@@ -710,6 +727,7 @@ export function ModelsPage() {setDirection("desc");}setCapabilityFilter("all");+ setSearchFilters({});setSortBrowseActive(false);// Clear search: an active query outranks the section in `mode`, hiding the curated list.setQuery("");@@ -726,6 +744,7 @@ export function ModelsPage() {setSortBy(preset?.sort ?? "trendingScore");setDirection("desc");setCapabilityFilter("all");+ setSearchFilters({});setSortBrowseActive(false);void navigate({to: "/hub",@@ -738,6 +757,7 @@ export function ModelsPage() {setResourceType("models");setQuery("");setCapabilityFilter("all");+ setSearchFilters({});setDownloadedFormat("all");setDiscoverFormat(preset?.format ?? "recommended");setSortBy(preset?.sort ?? "trendingScore");@@ -818,7 +838,7 @@ export function ModelsPage() {? "search": urlSection != null? "channel-list"- : sortBrowseActive+ : sortBrowseActive || hasSearchFilters? "search": "feed": "search";@@ -833,7 +853,6 @@ export function ModelsPage() {return null;}, [isChannelListMode, isFeedMode, activeChannel]);- const hubSource = useHubSource();const requestedSort: HfSortKey =isFeedMode && liveListChannel ? liveListChannel.sort : sortBy;// ModelScope has no creation-date sort; its closest is last modified.@@ -892,12 +911,14 @@ export function ModelsPage() {direction: effectiveDirection,channel: listChannel,ownerScope,+ filters: searchFilters,});const cachedListEntry = useHubFeedStore((state) =>liveListChannel ? state.channels[liveListChannel.id] : undefined,);const visibleResults =+ !hasSearchFilters &&results.length === 0 &&liveListChannel &&isChannelEntryFresh(cachedListEntry, liveListChannel.id, tokenFingerprint)@@ -905,7 +926,7 @@ export function ModelsPage() {: results;useFeedWriteBack({- channelId: liveListChannel?.id ?? null,+ channelId: hasSearchFilters ? null : liveListChannel?.id ?? null,results,isLoading,accessToken: apiHfToken,@@ -1206,6 +1227,7 @@ export function ModelsPage() {resourceType,deferredFormatFilter,deferredCapabilityFilter,+ searchFilters,inventoryTypeFilter,effectiveSort,effectiveDirection,@@ -1217,6 +1239,7 @@ export function ModelsPage() {resourceType,deferredFormatFilter,deferredCapabilityFilter,+ searchFilters,inventoryTypeFilter,effectiveSort,effectiveDirection,@@ -1239,6 +1262,7 @@ export function ModelsPage() {setInventoryTypeFilter("all");}setCapabilityFilter("all");+ setSearchFilters({});}, [isDiscoverTab, urlSection, navigate]);const handleDiscoverFetchIntent = useCallback(() => {setDiscoverFetchIntent((value) => value + 1);@@ -1324,6 +1348,7 @@ export function ModelsPage() {setSortBy(preset?.sort ?? "trendingScore");setDirection("desc");setCapabilityFilter("all");+ setSearchFilters({});setSortBrowseActive(false);setQuery("");void navigate({@@ -1342,6 +1367,7 @@ export function ModelsPage() {if (next.trim() === "") {const preset = findChannel(DEFAULT_DISCOVER_CHANNEL);setCapabilityFilter("all");+ setSearchFilters({});setSortBrowseActive(false);if (preset) {setDiscoverFormat(preset.format);@@ -1436,6 +1462,7 @@ export function ModelsPage() {setSortBy(preset.sort);setDirection("desc");setCapabilityFilter("all");+ setSearchFilters({});}, [isModelDiscover, sectionChannelId, urlCapability]);const handleManageLocalFolders = useCallback(() => setFoldersDialogOpen(true),@@ -1494,6 +1521,7 @@ export function ModelsPage() {setResourceType("models");setDiscoverFormat("all");setCapabilityFilter("all");+ setSearchFilters({});setSortBrowseActive(false);// Base models come from other publishers, so search the whole Hub.setOwnerScope("all");@@ -1687,7 +1715,8 @@ export function ModelsPage() {manualFetchAvailable: discoverManualFetchAvailable,hasActiveFilters:!isFeedMode &&- (deferredFormatFilter !== "all" ||+ ((isModelDiscover && hasSearchFilters) ||+ deferredFormatFilter !== "all" ||deferredCapabilityFilter !== "all" ||(tab === "downloaded" && typeFilterActive)),typeFilterActive,@@ -1721,6 +1750,7 @@ export function ModelsPage() {discoverManualFetchAvailable,deferredFormatFilter,deferredCapabilityFilter,+ hasSearchFilters,inventoryTypeFilter,],);@@ -1925,6 +1955,8 @@ export function ModelsPage() {onResourceTypeChange={handleResourceTypeChange}formatFilter={formatFilter}onFormatFilterChange={setFormatFilter}+ searchFilters={searchFilters}+ onSearchFiltersChange={setSearchFilters}capabilityFilter={capabilityFilter}onCapabilityFilterChange={setCapabilityFilter}fitOnDeviceOnly={fitOnDeviceOnly}diff --git a/studio/frontend/src/features/hub/lib/model-search-filters.ts b/studio/frontend/src/features/hub/lib/model-search-filters.tsnew file mode 100644index 00000000000..d278ec2108d--- /dev/null+++ b/studio/frontend/src/features/hub/lib/model-search-filters.ts@@ -0,0 +1,176 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export interface ModelSearchFilters {+ minParams?: number;+ maxParams?: number;+ minContext?: number;+ maxContext?: number;+ organizationsOnly?: boolean;+}++export function hasModelSearchFilters(filters: ModelSearchFilters): boolean {+ return Object.values(filters).some(+ (value) => value !== undefined && value !== false,+ );+}++export function parameterRange(filters: ModelSearchFilters): string {+ return [+ filters.minParams === undefined+ ? ""+ : `min:${Math.round(filters.minParams)}`,+ filters.maxParams === undefined+ ? ""+ : `max:${Math.round(filters.maxParams)}`,+ ]+ .filter(Boolean)+ .join(",");+}++function positiveNumber(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value > 0+ ? value+ : undefined;+}++export function modelContextLength(+ config: Record<string, unknown>,+): number | undefined {+ for (const key of [+ "text_config",+ "llm_config",+ "language_config",+ "thinker_config",+ ]) {+ const nested = config[key];+ if (nested && typeof nested === "object") {+ const context = modelContextLength(nested as Record<string, unknown>);+ if (context !== undefined) {+ return context;+ }+ }+ }+ return (+ positiveNumber(config.max_position_embeddings) ??+ positiveNumber(config.n_positions) ??+ positiveNumber(config.max_seq_len) ??+ positiveNumber(config.seq_length) ??+ positiveNumber(config.max_seq_length) ??+ positiveNumber(config.max_sequence_length) ??+ positiveNumber(config.n_ctx) ??+ positiveNumber(config.context_length) ??+ positiveNumber(config.model_max_length)+ );+}++export function matchesRange(+ value: number | undefined,+ min?: number,+ max?: number,+): boolean {+ if (min === undefined && max === undefined) {+ return true;+ }+ const known = positiveNumber(value);+ return (+ known !== undefined &&+ (min === undefined || known >= min) &&+ (max === undefined || known <= max)+ );+}++type JsonFetch = (path: string) => Promise<Record<string, unknown> | null>;++interface ListingModel {+ name: string;+ safetensors?: { total?: number };+ gguf?: { total?: number; context_length?: number };+}++export async function* filterModelListing(+ iterator: AsyncGenerator<unknown>,+ filters: ModelSearchFilters,+ fetchJson: JsonFetch,+ pinnedModel?: Promise<unknown | null>,+): AsyncGenerator<unknown> {+ const owners = new Map<string, Promise<boolean>>();+ async function filter(raw: unknown): Promise<ListingModel | null> {+ if (raw === null) {+ return null;+ }+ const model = raw as ListingModel;+ if (+ !matchesRange(+ model.safetensors?.total ?? model.gguf?.total,+ filters.minParams,+ filters.maxParams,+ )+ ) {+ return null;+ }+ if (filters.organizationsOnly) {+ // isVerified would drop unverified labs such as Qwen; personal accounts 404 here.+ const owner = model.name.split("/")[0];+ let isOrganization = owners.get(owner);+ if (!isOrganization) {+ isOrganization = fetchJson(+ `/api/organizations/${encodeURIComponent(owner)}/overview`,+ ).then((data) => data !== null);+ owners.set(owner, isOrganization);+ }+ if (!(await isOrganization)) {+ return null;+ }+ }+ if (filters.minContext === undefined && filters.maxContext === undefined) {+ return model;+ }+ let contextLength = positiveNumber(model.gguf?.context_length);+ if (contextLength === undefined) {+ const path = model.name.split("/").map(encodeURIComponent).join("/");+ const config = await fetchJson(`/${path}/resolve/main/config.json`);+ if (config) {+ contextLength = modelContextLength(config);+ }+ }+ return matchesRange(contextLength, filters.minContext, filters.maxContext)+ ? model+ : null;+ }+ try {+ const pinned = await pinnedModel;+ const filteredPinned = pinned ? await filter(pinned) : null;+ const pinnedName = filteredPinned?.name;+ if (pinned) {+ yield filteredPinned;+ }+ while (true) {+ const batch: unknown[] = [];+ let done = false;+ for (let i = 0; i < 4; i++) {+ const next = await iterator.next();+ if (next.done) {+ done = true;+ break;+ }+ batch.push(next.value);+ }+ // preserve rejected rows so pagination's scan limit still bounds sparse searches.+ for (const model of await Promise.all(+ batch.map((raw) =>+ pinnedName && (raw as ListingModel | null)?.name === pinnedName+ ? null+ : filter(raw),+ ),+ )) {+ yield model;+ }+ if (done) {+ return;+ }+ }+ } finally {+ await iterator.return(undefined);+ }+}diff --git a/studio/frontend/tests/model-search-filters.test.ts b/studio/frontend/tests/model-search-filters.test.tsnew file mode 100644index 00000000000..f3a4def901d--- /dev/null+++ b/studio/frontend/tests/model-search-filters.test.ts@@ -0,0 +1,365 @@+// 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 assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import ts from "typescript";+import {+ filterModelListing,+ hasModelSearchFilters,+ matchesRange,+ modelContextLength,+ parameterRange,+} from "../src/features/hub/lib/model-search-filters.ts";++async function collect<T>(iterator: AsyncIterable<T>): Promise<T[]> {+ const result: T[] = [];+ for await (const value of iterator) {+ result.push(value);+ }+ return result;+}++async function* listing(models: unknown[]) {+ yield* models;+}+const noFetch = async () => {+ throw new Error("unexpected metadata request");+};++test("parameter ranges are inclusive and exclude unknown counts only when active", () => {+ assert.equal(+ parameterRange({ minParams: 2e9, maxParams: 8e9 }),+ "min:2000000000,max:8000000000",+ );+ assert.equal(parameterRange({ maxParams: 5e8 }), "max:500000000");+ assert.equal(parameterRange({ minParams: 4.1 * 1e9 }), "min:4100000000");+ assert.equal(matchesRange(undefined), true);+ for (const count of [2e9, 4e9, 8e9]) {+ assert.equal(matchesRange(count, 2e9, 8e9), true);+ }+ for (const count of [+ undefined,+ 0,+ Number.NaN,+ Number.POSITIVE_INFINITY,+ 1.9e9,+ 8.1e9,+ ]) {+ assert.equal(matchesRange(count, 2e9, 8e9), false);+ }+ assert.equal(hasModelSearchFilters({ organizationsOnly: false }), false);+ assert.equal(hasModelSearchFilters({ minParams: 0 }), true);+});++test("context comes from text configuration rather than vision position counts", () => {+ assert.equal(modelContextLength({ max_position_embeddings: 40960 }), 40960);+ assert.equal(+ modelContextLength({+ max_position_embeddings: 256,+ text_config: { max_position_embeddings: 131072 },+ }),+ 131072,+ );+ for (const field of ["n_positions", "max_seq_len", "seq_length"]) {+ assert.equal(modelContextLength({ [field]: 8192 }), 8192);+ }+ assert.equal(+ modelContextLength({+ max_position_embeddings: 32768,+ rope_scaling: { factor: 4 },+ }),+ 32768,+ );+ assert.equal(modelContextLength({ max_position_embeddings: -1 }), undefined);+});++test("combined filters use actual parameters, GGUF context, and organization owners", async () => {+ const rows = [+ { name: "verified/model", safetensors: { total: 4e9 } },+ {+ name: "verified/model-GGUF",+ gguf: { total: 4e9, context_length: 32768 },+ },+ { name: "community/model", safetensors: { total: 4e9 } },+ { name: "verified/7B-misleading", safetensors: { total: 12e9 } },+ { name: "verified/unknown" },+ { name: "verified/short", safetensors: { total: 2e9 } },+ ];+ const requests: string[] = [];+ const output = await collect(+ filterModelListing(+ listing(rows),+ {+ minParams: 2e9,+ maxParams: 8e9,+ minContext: 32768,+ maxContext: 131072,+ organizationsOnly: true,+ },+ async (path) => {+ requests.push(path);+ // Personal accounts 404 on the organization overview (fetchJson maps that to null).+ if (path.includes("/organizations/")) {+ return path.includes("/verified/") ? { isVerified: false } : null;+ }+ return {+ max_position_embeddings: path.includes("/short/") ? 8192 : 131072,+ };+ },+ ),+ );+ assert.deepEqual(+ output.filter(Boolean).map((m) => (m as { name: string }).name),+ ["verified/model", "verified/model-GGUF"],+ );+ assert.equal(output.length, rows.length);+ assert.equal(+ requests.filter((p) => p.includes("/organizations/verified/")).length,+ 1,+ );+ assert.equal(+ requests.some((p) => p.includes("model-GGUF/resolve")),+ false,+ );+});++test("unfiltered searches neither drop models nor fetch metadata", async () => {+ const rows = [+ { name: "user/unknown" },+ { name: "user/other", gguf: { total: 1 } },+ ];+ assert.deepEqual(+ await collect(filterModelListing(listing(rows), {}, noFetch)),+ rows,+ );+});++test("missing or inaccessible config is excluded while service errors propagate", async () => {+ const rows = [{ name: "user/gated", safetensors: { total: 2e9 } }];+ assert.deepEqual(+ await collect(+ filterModelListing(listing(rows), { minContext: 1 }, async () => null),+ ),+ [null],+ );+ await assert.rejects(+ collect(+ filterModelListing(listing(rows), { minContext: 1 }, async () => {+ throw new Error("HTTP 429");+ }),+ ),+ /HTTP 429/,+ );+});++test("a sparse result remains reachable beyond the pagination scan budget", async () => {+ const rows = Array.from({ length: 200 }, (_, i) => ({+ name: `user/${i}`,+ gguf: { total: i === 199 ? 4e9 : 70e9 },+ }));+ const iter = filterModelListing(listing(rows), { maxParams: 8e9 }, noFetch);+ for (let i = 0; i < 192; i++) {+ assert.equal((await iter.next()).value, null);+ }+ const rest = await collect(iter);+ assert.equal((rest.filter(Boolean)[0] as { name: string }).name, "user/199");+});++test("metadata work is bounded and cancellation closes the source iterator", async () => {+ let active = 0;+ let peak = 0;+ let closed = false;+ async function* source() {+ try {+ for (let i = 0; i < 20; i++) {+ yield { name: `user/${i}` };+ }+ } finally {+ closed = true;+ }+ }+ const iter = filterModelListing(source(), { minContext: 1 }, async () => {+ active++;+ peak = Math.max(peak, active);+ await new Promise((resolve) => setTimeout(resolve, 1));+ active--;+ return { n_positions: 4096 };+ });+ await iter.next();+ await iter.return(undefined);+ assert.equal(peak, 4);+ assert.equal(active, 0);+ assert.equal(closed, true);+});++test("context filters inspect supported language wrappers recursively", () => {+ for (const key of ["llm_config", "language_config", "thinker_config"]) {+ assert.equal(+ modelContextLength({+ [key]: { text_config: { max_position_embeddings: 32768 } },+ }),+ 32768,+ );+ }+ assert.equal(+ modelContextLength({+ llm_config: { max_position_embeddings: 32768 },+ max_position_embeddings: 256,+ }),+ 32768,+ );+});++test("an exact publisher match is filtered and pinned ahead of a sparse listing", async () => {+ const pinned = {+ name: "publisher/model",+ gguf: { total: 4e9, context_length: 32768 },+ };+ const rows = [+ ...Array.from({ length: 200 }, (_, i) => ({+ name: `user/${i}`,+ gguf: { total: 70e9 },+ })),+ pinned,+ ];+ const iter = filterModelListing(+ listing(rows),+ { maxParams: 8e9, minContext: 32768 },+ noFetch,+ Promise.resolve(pinned),+ );+ assert.deepEqual((await iter.next()).value, pinned);+ assert.equal((await collect(iter)).filter(Boolean).length, 0);+ const excluded = await collect(+ filterModelListing(+ listing([]),+ { maxParams: 2e9 },+ noFetch,+ Promise.resolve(pinned),+ ),+ );+ assert.deepEqual(excluded.filter(Boolean), []);+});++test("an incomplete pinned response does not hide a matching listing entry", async () => {+ const model = { name: "publisher/model-GGUF", gguf: { total: 4e9 } };+ const output = await collect(+ filterModelListing(+ listing([model]),+ { maxParams: 8e9 },+ noFetch,+ Promise.resolve({ name: model.name }),+ ),+ );+ assert.deepEqual(output.filter(Boolean), [model]);+});++test("rejected priority rows retain the pagination scan budget", async () => {+ const accepted = {+ name: "unsloth/match",+ gguf: { total: 4e9, context_length: 32768 },+ };+ const rows = await collect(+ filterModelListing(+ listing([null, null, accepted]),+ { minContext: 32768 },+ noFetch,+ Promise.resolve(accepted),+ ),+ );+ assert.deepEqual(rows, [accepted, null, null, null]);+});++test("context filters accept established config key aliases", async () => {+ for (const field of [+ "max_seq_length",+ "max_sequence_length",+ "n_ctx",+ "context_length",+ "model_max_length",+ ]) {+ const model = { name: "publisher/model" };+ const rows = await collect(+ filterModelListing(+ listing([model]),+ { minContext: 2048, maxContext: 2048 },+ async () => ({ [field]: 2048 }),+ ),+ );+ assert.deepEqual(rows, [model], field);+ assert.equal(modelContextLength({ [field]: 0 }), undefined);+ }+});++// Runs the production channel iterator with a stubbed listing, as hub-search-mixed-formats does.+function channelIterator(listings: Record<string, unknown[]>) {+ const source = readFileSync(+ new URL(+ "../src/features/hub/hooks/use-hub-model-search.ts",+ import.meta.url,+ ),+ "utf8",+ );+ const start = source.indexOf("async function* channelUnslothFirstIterator(");+ assert.notEqual(start, -1);+ const end = source.indexOf("\n}\n", start) + 2;+ const limit = Number(+ /const UNSLOTH_FILTER_REJECT_LIMIT = (\d+);/.exec(source)?.[1],+ );+ assert.ok(limit > 0);+ const listModels = ({ search }: { search: { owner?: string } }) =>+ listing(listings[search.owner ?? "all"] ?? []);+ const fn = new Function(+ "listModels",+ "getHfEndpoint",+ "ALL_FIELDS",+ "makeSortFetch",+ "UNSLOTH_CHANNEL_PREFETCH",+ "UNSLOTH_FILTER_REJECT_LIMIT",+ `${+ ts.transpileModule(source.slice(start, end), {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText+ }; return channelUnslothFirstIterator;`,+ )(+ listModels,+ () => "",+ [],+ () => undefined,+ 60,+ limit,+ );+ return { fn, limit };+}++test("rejected Unsloth rows stop delaying other publishers after a bounded scan", async () => {+ const unsloth = Array.from({ length: 200 }, (_, i) => ({+ name: `unsloth/short-${i}`,+ }));+ const { fn, limit } = channelIterator({+ unsloth,+ all: [{ name: "Qwen/match" }],+ });+ const rows = await collect(+ fn(+ {},+ {+ sortBy: "downloads",+ sortDirection: "desc",+ signal: new AbortController().signal,+ filterPriority: (it: AsyncGenerator<unknown>) =>+ (async function* () {+ for await (const row of it) {+ yield (row as { name: string }).name.startsWith("unsloth/")+ ? null+ : row;+ }+ })(),+ },+ ) as AsyncGenerator<unknown>,+ );+ assert.equal(rows.length, limit + 1);+ assert.deepEqual(rows.at(-1), { name: "Qwen/match" });+});