From e29d591d1ca8beb1717c93829b0a68315860faaa Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 14:13:01 +0500 Subject: [PATCH 01/11] Add OfferMatcher for matching offers against requirements --- .../_internal/core/backends/base/offers.py | 21 +- .../background/pipeline_tasks/fleets.py | 3 +- .../_internal/server/services/instances.py | 21 +- .../core/backends/base/test_offers.py | 404 ++++++++++++++++-- 4 files changed, 389 insertions(+), 60 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index cad3b0b6b6..77189acdd6 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -209,18 +209,31 @@ def requirements_to_query_filter( return q +class OfferMatcher: + """ + Matches offers against `requirements`. + + Create one per `requirements` and reuse it for all offers. + """ + + def __init__(self, requirements: Requirements, *, check_disk: bool = True) -> None: + self._query_filter = requirements_to_query_filter(requirements, ignore_disk=not check_disk) + + def matches(self, offer: InstanceOffer) -> bool: + return gpuhunt.matches(offer_to_catalog_item(offer), q=self._query_filter) + + InstanceOfferT = TypeVar("InstanceOfferT", InstanceOffer, InstanceOfferWithAvailability) def filter_offers_by_requirements( offers: Iterable[InstanceOfferT], - requirements: Optional[Requirements], + requirements: Requirements, ignore_disk: bool = False, ) -> Iterator[InstanceOfferT]: - query_filter = requirements_to_query_filter(requirements, ignore_disk=ignore_disk) + matcher = OfferMatcher(requirements, check_disk=not ignore_disk) for offer in offers: - catalog_item = offer_to_catalog_item(offer) - if gpuhunt.matches(catalog_item, q=query_filter): + if matcher.matches(offer): yield offer diff --git a/src/dstack/_internal/server/background/pipeline_tasks/fleets.py b/src/dstack/_internal/server/background/pipeline_tasks/fleets.py index 4904e7e3a2..43cdb6cbca 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/fleets.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/fleets.py @@ -8,6 +8,7 @@ from sqlalchemy.ext.asyncio.session import AsyncSession from sqlalchemy.orm import joinedload, load_only, selectinload +from dstack._internal.core.backends.base.offers import OfferMatcher from dstack._internal.core.models.fleets import ( FleetSpec, FleetStatus, @@ -659,7 +660,7 @@ def _instance_matches_fleet_spec(instance: InstanceModel, fleet_spec: FleetSpec) regions=profile.regions, instance_types=profile.instance_types, zones=profile.availability_zones, - requirements=requirements, + offer_matcher=OfferMatcher(requirements), ) diff --git a/src/dstack/_internal/server/services/instances.py b/src/dstack/_internal/server/services/instances.py index d08baf50fe..734fc63734 100644 --- a/src/dstack/_internal/server/services/instances.py +++ b/src/dstack/_internal/server/services/instances.py @@ -4,15 +4,11 @@ from datetime import datetime from typing import Dict, List, Literal, Optional, Sequence, Union -import gpuhunt from sqlalchemy import and_, exists, false, or_, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import contains_eager, joinedload, load_only -from dstack._internal.core.backends.base.offers import ( - offer_to_catalog_item, - requirements_to_query_filter, -) +from dstack._internal.core.backends.base.offers import OfferMatcher from dstack._internal.core.backends.features import BACKENDS_WITH_MULTINODE_SUPPORT from dstack._internal.core.errors import ResourceNotExistsError from dstack._internal.core.models.backends.base import BackendType @@ -567,7 +563,7 @@ def instance_matches_constraints( regions: Optional[List[str]] = None, instance_types: Optional[List[str]] = None, zones: Optional[List[str]] = None, - requirements: Optional[Requirements] = None, + offer_matcher: Optional[OfferMatcher] = None, ) -> bool: """Check if an instance matches the given provisioning constraints.""" jpd = get_instance_provisioning_data(instance) @@ -587,12 +583,11 @@ def instance_matches_constraints( ): return False - if requirements is not None: + if offer_matcher is not None: if instance.offer is None: return False offer = validate_json_extra_ignore(InstanceOffer, instance.offer) - catalog_item = offer_to_catalog_item(offer) - if not gpuhunt.matches(catalog_item, q=requirements_to_query_filter(requirements)): + if not offer_matcher.matches(offer): return False return True @@ -650,6 +645,7 @@ def filter_instances( regions = [r for r in regions if r == master_job_provisioning_data.region] instance_types = profile.instance_types + offer_matcher = OfferMatcher(requirements) if requirements is not None else None filtered_instances: List[InstanceModel] = [] for instance in instances: @@ -670,7 +666,7 @@ def filter_instances( regions=regions, instance_types=instance_types, zones=zones, - requirements=requirements, + offer_matcher=offer_matcher, ): continue if volumes_locations is not None: @@ -703,7 +699,7 @@ def get_shared_instances_with_offers( volumes: Optional[List[List[Volume]]] = None, ) -> list[tuple[InstanceModel, InstanceOfferWithAvailability]]: instances_with_offers: list[tuple[InstanceModel, InstanceOfferWithAvailability]] = [] - query_filter = requirements_to_query_filter(requirements) + offer_matcher = OfferMatcher(requirements) filtered_instances = filter_instances( instances=instances, profile=profile, @@ -724,8 +720,7 @@ def get_shared_instances_with_offers( min_blocks = total_blocks if multinode else 1 for blocks in range(min_blocks, total_blocks + 1): shared_offer = generate_shared_offer(offer, blocks, total_blocks) - catalog_item = offer_to_catalog_item(shared_offer) - if gpuhunt.matches(catalog_item, query_filter): + if offer_matcher.matches(shared_offer): if blocks <= idle_blocks: shared_offer.availability = InstanceAvailability.IDLE else: diff --git a/src/tests/_internal/core/backends/base/test_offers.py b/src/tests/_internal/core/backends/base/test_offers.py index 922e709394..5f7c911eab 100644 --- a/src/tests/_internal/core/backends/base/test_offers.py +++ b/src/tests/_internal/core/backends/base/test_offers.py @@ -5,6 +5,7 @@ from dstack._internal.core.backends.base.offers import ( OfferDiskFitter, + OfferMatcher, filter_offers_by_requirements, gpu_matches_gpu_spec, ) @@ -22,6 +23,9 @@ NVIDIA = gpuhunt.AcceleratorVendor.NVIDIA AMD = gpuhunt.AcceleratorVendor.AMD +GOOGLE = gpuhunt.AcceleratorVendor.GOOGLE +X86 = gpuhunt.CPUArchitecture.X86 +ARM = gpuhunt.CPUArchitecture.ARM def make_gpu(name: str = "A100", memory_gib: int = 80, vendor=NVIDIA) -> Gpu: @@ -138,62 +142,378 @@ def test_single_failing_constraint_rejects_gpu(self): assert not gpu_matches_gpu_spec(make_gpu(name="A100", memory_gib=24), spec) -class TestFilterOffersByRequirementsDiskSize: +def make_offer( + *, + price: float = 1.0, + spot: bool = False, + cpu_arch: Optional[gpuhunt.CPUArchitecture] = None, + cpus: int = 8, + memory_mib: int = 64 * 1024, + gpu_count: int = 0, + gpu_name: str = "A100", + gpu_memory_gib: int = 80, + gpu_vendor: gpuhunt.AcceleratorVendor = NVIDIA, + disk_gib: int = 100, +) -> InstanceOffer: """ - An offer with `disk.size_mib == 0` has an unknown disk size and must not be - filtered out by the disk size requirement. This exercises both the - `offer_to_catalog_item` mapping (`size_mib=0` -> `disk_size=None`) and - `gpuhunt.matches` (ignores disk bounds when `disk_size is None`). + Returns an offer that matches the default requirements unless overridden. """ - - def make_offer(self, disk_size_mib: int) -> InstanceOffer: - # cpus/memory are chosen to satisfy the default requirements so that only the - # disk size decides whether the offer is filtered out. - return InstanceOffer( - backend=BackendType.SLURM, - instance=InstanceType( - name="test-instance", - resources=Resources( - cpus=8, - memory_mib=64 * 1024, - gpus=[], - spot=False, - disk=Disk(size_mib=disk_size_mib), - ), + gpus = [make_gpu(name=gpu_name, memory_gib=gpu_memory_gib, vendor=gpu_vendor)] * gpu_count + return InstanceOffer( + backend=BackendType.AWS, + instance=InstanceType( + name="test-instance", + resources=Resources( + cpus=cpus, + memory_mib=memory_mib, + gpus=gpus, + spot=spot, + disk=Disk(size_mib=disk_gib * 1024), + cpu_arch=cpu_arch, ), - region="test-region", - price=1.0, - ) + ), + region="test-region", + price=price, + ) - def test_unknown_disk_size_ignores_disk_requirement(self): - # An offer with a real 0 GB disk would satisfy neither the min nor the max - # bound, so a match here proves the disk requirement is ignored entirely. - offer = self.make_offer(disk_size_mib=0) - requirements = Requirements( - resources=ResourcesSpec.model_validate({"disk": "100GB..200GB"}) + +def make_requirements( + resources: Optional[dict] = None, + *, + spot: Optional[bool] = None, + max_price: Optional[float] = None, +) -> Requirements: + return Requirements( + resources=ResourcesSpec.model_validate(resources or {}), + spot=spot, + max_price=max_price, + ) + + +def matches(offer: InstanceOffer, requirements: Requirements, check_disk: bool = True) -> bool: + return OfferMatcher(requirements, check_disk=check_disk).matches(offer) + + +CPU_ONLY = make_offer() +A100 = make_offer(gpu_count=1) + + +class TestOfferMatcher: + def test_default_requirements_match_cpu_and_gpu_offers(self): + requirements = make_requirements() + + assert matches(CPU_ONLY, requirements) + assert matches(A100, requirements) + + @pytest.mark.parametrize( + ["price", "max_price", "expected"], + [ + pytest.param(1.0, None, True, id="no-max-price"), + pytest.param(1.0, 2.0, True, id="below-max"), + pytest.param(1.0, 1.0, True, id="equal-to-max"), + pytest.param(2.0, 1.0, False, id="above-max"), + ], + ) + def test_max_price(self, price: float, max_price: Optional[float], expected: bool): + offer = make_offer(price=price) + + assert matches(offer, make_requirements(max_price=max_price)) is expected + + @pytest.mark.parametrize( + ["offer_spot", "required_spot", "expected"], + [ + pytest.param(False, None, True, id="any-on-demand"), + pytest.param(True, None, True, id="any-spot"), + pytest.param(True, True, True, id="spot-spot"), + pytest.param(False, False, True, id="on-demand-on-demand"), + pytest.param(False, True, False, id="spot-required-on-demand-offer"), + pytest.param(True, False, False, id="on-demand-required-spot-offer"), + ], + ) + def test_spot(self, offer_spot: bool, required_spot: Optional[bool], expected: bool): + offer = make_offer(spot=offer_spot) + + assert matches(offer, make_requirements(spot=required_spot)) is expected + + @pytest.mark.parametrize( + ["offer_arch", "required_arch", "expected"], + [ + pytest.param(None, None, True, id="any-unset"), + pytest.param(ARM, None, True, id="any-arm"), + pytest.param(X86, "x86", True, id="x86-x86"), + pytest.param(None, "x86", True, id="unset-offer-arch-is-x86"), + pytest.param(ARM, "arm", True, id="arm-arm"), + pytest.param(X86, "arm", False, id="arm-required-x86-offer"), + pytest.param(None, "arm", False, id="arm-required-unset-offer-arch"), + pytest.param(ARM, "x86", False, id="x86-required-arm-offer"), + ], + ) + def test_cpu_arch( + self, + offer_arch: Optional[gpuhunt.CPUArchitecture], + required_arch: Optional[str], + expected: bool, + ): + offer = make_offer(cpu_arch=offer_arch) + requirements = make_requirements({"cpu": {"arch": required_arch}}) + + assert matches(offer, requirements) is expected + + @pytest.mark.parametrize( + ["cpus", "required_cpus", "expected"], + [ + pytest.param(4, "4..16", True, id="equal-to-min"), + pytest.param(16, "4..16", True, id="equal-to-max"), + pytest.param(2, "4..16", False, id="below-min"), + pytest.param(32, "4..16", False, id="above-max"), + pytest.param(1, "..8", True, id="no-min"), + pytest.param(1, None, False, id="below-default-min"), + ], + ) + def test_cpu_count(self, cpus: int, required_cpus: Optional[str], expected: bool): + offer = make_offer(cpus=cpus) + resources = {} if required_cpus is None else {"cpu": required_cpus} + + assert matches(offer, make_requirements(resources)) is expected + + @pytest.mark.parametrize( + ["memory_mib", "required_memory", "expected"], + [ + pytest.param(16 * 1024, "16GB..64GB", True, id="equal-to-min"), + pytest.param(64 * 1024, "16GB..64GB", True, id="equal-to-max"), + pytest.param(8 * 1024, "16GB..64GB", False, id="below-min"), + pytest.param(128 * 1024, "16GB..64GB", False, id="above-max"), + pytest.param(512, "0.5GB..", True, id="fractional-equal-to-min"), + pytest.param(511, "0.5GB..", False, id="fractional-below-min"), + pytest.param(4 * 1024, None, False, id="below-default-min"), + ], + ) + def test_memory(self, memory_mib: int, required_memory: Optional[str], expected: bool): + offer = make_offer(memory_mib=memory_mib) + resources = {} if required_memory is None else {"memory": required_memory} + + assert matches(offer, make_requirements(resources)) is expected + + def test_no_gpu_spec_matches_cpu_and_gpu_offers(self): + requirements = make_requirements({"gpu": None}) + + assert matches(CPU_ONLY, requirements) + assert matches(A100, requirements) + + def test_zero_gpus_required_matches_only_cpu_offers(self): + requirements = make_requirements({"gpu": 0}) + + assert matches(CPU_ONLY, requirements) + assert not matches(A100, requirements) + + def test_at_least_one_gpu_required_matches_only_gpu_offers(self): + requirements = make_requirements({"gpu": "1.."}) + + assert not matches(CPU_ONLY, requirements) + assert matches(A100, requirements) + + @pytest.mark.parametrize( + ["gpu_count", "expected"], + [ + pytest.param(1, False, id="below-min"), + pytest.param(2, True, id="equal-to-min"), + pytest.param(4, True, id="equal-to-max"), + pytest.param(8, False, id="above-max"), + ], + ) + def test_gpu_count(self, gpu_count: int, expected: bool): + offer = make_offer(gpu_count=gpu_count) + + assert matches(offer, make_requirements({"gpu": "2..4"})) is expected + + def test_gpu_spec_applies_to_cpu_offers_if_min_count_is_zero_but_not_unset(self): + # With `count.min == 0`, GPU constraints are not checked for offers without GPUs. + # With `count.min` unset, they are: an offer without GPUs has no vendor or name + # and has 0 GPU memory. + assert matches(CPU_ONLY, make_requirements({"gpu": {"vendor": "nvidia", "count": "0.."}})) + assert not matches( + CPU_ONLY, make_requirements({"gpu": {"vendor": "nvidia", "count": "..8"}}) + ) + assert matches(CPU_ONLY, make_requirements({"gpu": {"memory": "24GB..", "count": "0.."}})) + assert not matches( + CPU_ONLY, make_requirements({"gpu": {"memory": "24GB..", "count": "..8"}}) ) + assert matches(CPU_ONLY, make_requirements({"gpu": {"count": "..8"}})) - assert list(filter_offers_by_requirements([offer], requirements)) == [offer] + def test_gpu_name_matches(self): + requirements = make_requirements({"gpu": "A100"}) - def test_known_disk_size_below_min_is_filtered_out(self): - # A non-zero disk size is still checked, so the requirement stays effective. - offer = self.make_offer(disk_size_mib=50 * 1024) - requirements = Requirements(resources=ResourcesSpec.model_validate({"disk": "100GB.."})) + assert matches(A100, requirements) + assert not matches(make_offer(gpu_count=1, gpu_name="H100"), requirements) - assert list(filter_offers_by_requirements([offer], requirements)) == [] + def test_gpu_name_implies_at_least_one_gpu(self): + assert not matches(CPU_ONLY, make_requirements({"gpu": "A100"})) - def test_known_disk_size_within_range_matches(self): - offer = self.make_offer(disk_size_mib=150 * 1024) - requirements = Requirements( - resources=ResourcesSpec.model_validate({"disk": "100GB..200GB"}) + def test_gpu_name_with_zero_min_count_matches_cpu_offers(self): + requirements = make_requirements({"gpu": {"name": ["A100"], "count": "0.."}}) + + assert matches(CPU_ONLY, requirements) + assert not matches(make_offer(gpu_count=1, gpu_name="H100"), requirements) + + def test_gpu_name_matches_any_in_list(self): + requirements = make_requirements({"gpu": "A100,H100"}) + + assert matches(A100, requirements) + assert matches(make_offer(gpu_count=1, gpu_name="H100"), requirements) + assert not matches(make_offer(gpu_count=1, gpu_name="T4"), requirements) + + @pytest.mark.parametrize( + ("offer_name", "required_name"), + [("A100", "a100"), ("a100", "A100")], + ) + def test_gpu_name_match_is_case_insensitive(self, offer_name: str, required_name: str): + offer = make_offer(gpu_count=1, gpu_name=offer_name) + + assert matches(offer, make_requirements({"gpu": required_name})) + + def test_empty_gpu_name_list_matches_no_gpu_offers(self): + requirements = make_requirements({"gpu": {"name": [], "count": "0.."}}) + + assert matches(CPU_ONLY, requirements) + assert not matches(A100, requirements) + + def test_gpu_vendor(self): + requirements = make_requirements({"gpu": "amd"}) + + assert matches(make_offer(gpu_count=1, gpu_name="MI300X", gpu_vendor=AMD), requirements) + assert not matches(A100, requirements) + assert not matches(CPU_ONLY, requirements) + + def test_tpu_vendor(self): + offer = make_offer(gpu_count=1, gpu_name="v5litepod-8", gpu_vendor=GOOGLE) + + assert matches(offer, make_requirements({"gpu": "tpu"})) + assert not matches(offer, make_requirements({"gpu": "nvidia"})) + + @pytest.mark.parametrize( + ["gpu_memory_gib", "expected"], + [ + pytest.param(40, True, id="equal-to-min"), + pytest.param(80, True, id="equal-to-max"), + pytest.param(24, False, id="below-min"), + pytest.param(141, False, id="above-max"), + ], + ) + def test_gpu_memory(self, gpu_memory_gib: int, expected: bool): + offer = make_offer(gpu_count=1, gpu_memory_gib=gpu_memory_gib) + + assert matches(offer, make_requirements({"gpu": "40GB..80GB"})) is expected + + def test_gpu_memory_is_per_gpu(self): + offer = make_offer(gpu_count=8, gpu_memory_gib=24) + + assert not matches(offer, make_requirements({"gpu": "40GB.."})) + + @pytest.mark.parametrize( + ["gpu_count", "expected"], + [ + pytest.param(1, False, id="below-min"), + pytest.param(2, True, id="equal-to-min"), + pytest.param(8, True, id="above-min"), + ], + ) + def test_gpu_total_memory(self, gpu_count: int, expected: bool): + offer = make_offer(gpu_count=gpu_count, gpu_memory_gib=80) + requirements = make_requirements({"gpu": {"total_memory": "160GB.."}}) + + assert matches(offer, requirements) is expected + + @pytest.mark.parametrize( + ["gpu_name", "gpu_vendor", "expected"], + [ + pytest.param("A100", NVIDIA, True, id="equal"), # 8.0 + pytest.param("H100", NVIDIA, True, id="higher"), # 9.0 + pytest.param("T4", NVIDIA, False, id="lower"), # 7.5 + pytest.param("a100", NVIDIA, True, id="name-case-insensitive"), + pytest.param("UnknownGPU", NVIDIA, False, id="unknown-name"), + pytest.param("MI300X", AMD, False, id="non-nvidia"), + ], + ) + def test_gpu_compute_capability( + self, gpu_name: str, gpu_vendor: gpuhunt.AcceleratorVendor, expected: bool + ): + offer = make_offer(gpu_count=1, gpu_name=gpu_name, gpu_vendor=gpu_vendor) + requirements = make_requirements({"gpu": {"compute_capability": "8.0"}}) + + assert matches(offer, requirements) is expected + + @pytest.mark.parametrize( + ["disk_gib", "required_disk", "check_disk", "expected"], + [ + pytest.param(150, "100GB..200GB", True, True, id="within-range"), + pytest.param(50, "100GB..", True, False, id="below-min"), + pytest.param(300, "..200GB", True, False, id="above-max"), + # A real 0 GB disk would fail the min bound, so a match proves that + # the requirement is ignored for offers with unknown disk size. + pytest.param(0, "100GB..200GB", True, True, id="unknown-size"), + pytest.param(50, None, True, False, id="below-default-min"), + pytest.param(50, "100GB..", False, True, id="check-disk-disabled"), + ], + ) + def test_disk( + self, disk_gib: int, required_disk: Optional[str], check_disk: bool, expected: bool + ): + offer = make_offer(disk_gib=disk_gib) + resources = {} if required_disk is None else {"disk": required_disk} + + assert matches(offer, make_requirements(resources), check_disk=check_disk) is expected + + def test_no_disk_spec_matches_any_disk(self): + offer = make_offer(disk_gib=1) + + assert matches(offer, Requirements(resources=ResourcesSpec(disk=None))) + + def test_all_constraints_match(self): + offer = make_offer( + price=10.0, + spot=True, + cpu_arch=X86, + cpus=96, + memory_mib=1024 * 1024, + gpu_count=8, + gpu_name="H100", + gpu_memory_gib=80, + disk_gib=500, + ) + requirements = make_requirements( + { + "cpu": "x86:64..", + "memory": "512GB..", + "gpu": { + "vendor": "nvidia", + "name": ["H100"], + "count": 8, + "memory": "80GB", + "total_memory": "640GB..", + "compute_capability": "9.0", + }, + "disk": "200GB..", + }, + spot=True, + max_price=20.0, ) - assert list(filter_offers_by_requirements([offer], requirements)) == [offer] + assert matches(offer, requirements) + + +class TestFilterOffersByRequirements: + def test_yields_matching_offers_in_order(self): + offers = [make_offer(cpus=16), make_offer(cpus=1), make_offer(cpus=8)] + + result = list(filter_offers_by_requirements(offers, make_requirements())) + + assert result == [offers[0], offers[2]] def test_ignore_disk_skips_disk_requirement(self): - offer = self.make_offer(disk_size_mib=50 * 1024) - requirements = Requirements(resources=ResourcesSpec.model_validate({"disk": "100GB.."})) + offer = make_offer(disk_gib=50) + requirements = make_requirements({"disk": "100GB.."}) + assert list(filter_offers_by_requirements([offer], requirements)) == [] assert list(filter_offers_by_requirements([offer], requirements, ignore_disk=True)) == [ offer ] From 68541a6fdc3d5d2c65f0e0d4b6e223e047c4f342 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 15:34:32 +0500 Subject: [PATCH 02/11] Match offers without converting them to gpuhunt catalog items --- .../_internal/core/backends/base/offers.py | 130 +++++++++++++++--- .../core/backends/base/test_offers.py | 5 + 2 files changed, 119 insertions(+), 16 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 77189acdd6..6b93b863c2 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -1,7 +1,7 @@ from abc import ABC, abstractmethod from collections.abc import Iterable, Iterator from dataclasses import asdict -from typing import Callable, Generic, List, Literal, Optional, TypeVar +from typing import Callable, Generic, List, Literal, Optional, TypeVar, Union from uuid import UUID import gpuhunt @@ -36,9 +36,10 @@ # NvidiaGPUInfo.name in KNOWN_NVIDIA_GPUS is not unique -- there are multiple variants # with the same name but different amount of memory, but Compute Capability of the variants -# is always the same, so it's safe to use 1:1 mapping +# is always the same, so it's safe to use 1:1 mapping. +# Keys are lowercase GPU names. NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP = { - gpu_info.name: gpu_info.compute_capability for gpu_info in gpuhunt.KNOWN_NVIDIA_GPUS + gpu_info.name.lower(): gpu_info.compute_capability for gpu_info in gpuhunt.KNOWN_NVIDIA_GPUS } @@ -214,13 +215,71 @@ class OfferMatcher: Matches offers against `requirements`. Create one per `requirements` and reuse it for all offers. + + GPU constraints are checked against the offer's first GPU. If `requirements` allow zero + GPUs, offers without GPUs match regardless of other GPU constraints. Otherwise, an offer + without GPUs is treated as having no GPU vendor, name, or compute capability, and 0 GPU + memory. The disk is not checked if the offer's disk size is unknown (`size_mib == 0`). """ def __init__(self, requirements: Requirements, *, check_disk: bool = True) -> None: - self._query_filter = requirements_to_query_filter(requirements, ignore_disk=not check_disk) + resources = requirements.resources + self._max_price = requirements.max_price + self._spot = requirements.spot + self._cpu_arch = resources.cpu.arch + self._min_cpus = resources.cpu.count.min + self._max_cpus = resources.cpu.count.max + self._min_memory_mib, self._max_memory_mib = _get_mib_bounds(resources.memory) + self._gpu_spec = resources.gpu + self._min_total_gpu_memory_mib: Optional[float] = None + self._max_total_gpu_memory_mib: Optional[float] = None + self._matches_no_gpus = True + if self._gpu_spec is not None: + self._min_total_gpu_memory_mib, self._max_total_gpu_memory_mib = _get_mib_bounds( + self._gpu_spec.total_memory + ) + self._matches_no_gpus = _gpu_spec_matches_no_gpus(self._gpu_spec) + self._disk_mib_bounds: Optional[tuple[Optional[float], Optional[float]]] = None + if check_disk and resources.disk is not None: + self._disk_mib_bounds = _get_mib_bounds(resources.disk.size) def matches(self, offer: InstanceOffer) -> bool: - return gpuhunt.matches(offer_to_catalog_item(offer), q=self._query_filter) + resources = offer.instance.resources + if self._max_price is not None and offer.price > self._max_price: + return False + if self._spot is not None and resources.spot != self._spot: + return False + if self._cpu_arch is not None: + cpu_arch = resources.cpu_arch or gpuhunt.CPUArchitecture.X86 + if cpu_arch != self._cpu_arch: + return False + if not _is_within(resources.cpus, self._min_cpus, self._max_cpus): + return False + if not _is_within(resources.memory_mib, self._min_memory_mib, self._max_memory_mib): + return False + if not self._matches_gpus(resources.gpus): + return False + if self._disk_mib_bounds is not None and not _disk_size_fits( + resources.disk.size_mib, *self._disk_mib_bounds + ): + return False + return True + + def _matches_gpus(self, gpus: list[Gpu]) -> bool: + gpu_spec = self._gpu_spec + if gpu_spec is None: + return True + if not gpus: + return self._matches_no_gpus + if not _is_within(len(gpus), gpu_spec.count.min, gpu_spec.count.max): + return False + if not gpu_matches_gpu_spec(gpus[0], gpu_spec): + return False + return _is_within( + len(gpus) * gpus[0].memory_mib, + self._min_total_gpu_memory_mib, + self._max_total_gpu_memory_mib, + ) InstanceOfferT = TypeVar("InstanceOfferT", InstanceOffer, InstanceOfferWithAvailability) @@ -237,6 +296,48 @@ def filter_offers_by_requirements( yield offer +def _gpu_spec_matches_no_gpus(gpu_spec: GPUSpec) -> bool: + if gpu_spec.count.min == 0: + return True + return ( + _is_within(0, gpu_spec.count.min, gpu_spec.count.max) + and gpu_spec.vendor is None + and gpu_spec.name is None + and gpu_spec.compute_capability is None + and _is_within(0, *_get_mib_bounds(gpu_spec.memory)) + and _is_within(0, *_get_mib_bounds(gpu_spec.total_memory)) + ) + + +def _get_mib_bounds( + memory_range: Optional[Range[Memory]], +) -> tuple[Optional[float], Optional[float]]: + if memory_range is None: + return None, None + min_mib = memory_range.min * 1024 if memory_range.min is not None else None + max_mib = memory_range.max * 1024 if memory_range.max is not None else None + return min_mib, max_mib + + +def _disk_size_fits( + disk_size_mib: int, min_mib: Optional[float], max_mib: Optional[float] +) -> bool: + if disk_size_mib == 0: + # Unknown disk size + return True + return _is_within(disk_size_mib, min_mib, max_mib) + + +def _is_within( + value: Union[int, float], min_value: Optional[float], max_value: Optional[float] +) -> bool: + if min_value is not None and value < min_value: + return False + if max_value is not None and value > max_value: + return False + return True + + def choose_disk_size_mib( catalog_item_disk_size_gib: Optional[float], requirements_disk_size: Optional[Range[Memory]], @@ -267,8 +368,10 @@ class OfferDiskFitter: def __init__(self, requirements: Requirements) -> None: disk_spec = requirements.resources.disk - # The range fixed disks are checked against, `None` if fixed disks are not checked. - self._fixed_disk_range = disk_spec.size if disk_spec is not None else None + # The bounds fixed disks are checked against, `None` if fixed disks are not checked. + self._fixed_disk_mib_bounds = ( + _get_mib_bounds(disk_spec.size) if disk_spec is not None else None + ) # The range configurable disks are fitted to. self._target_disk_range = disk_spec.size if disk_spec is not None else DEFAULT_DISK.size self._disk_by_range: dict[tuple[Optional[float], Optional[float]], Optional[Disk]] = {} @@ -282,7 +385,7 @@ def fit( Returns the offer with the fitted disk, or `None` if the offer doesn't fit. If `configurable_disk_size` is `None`, the offer's disk is fixed and is only checked - against `requirements`, the same way `filter_offers_by_requirements()` checks it. + against `requirements`, the same way `OfferMatcher` checks it. Otherwise, the disk is set to the smallest size within both `configurable_disk_size` and the required range (`DEFAULT_DISK` if `requirements` don't specify disk). @@ -304,14 +407,9 @@ def fit( return offer.model_copy(update={"instance": instance}) def _fixed_disk_fits(self, disk_size_mib: int) -> bool: - if self._fixed_disk_range is None or disk_size_mib == 0: + if self._fixed_disk_mib_bounds is None: return True - disk_size = disk_size_mib / 1024 - if self._fixed_disk_range.min is not None and disk_size < self._fixed_disk_range.min: - return False - if self._fixed_disk_range.max is not None and disk_size > self._fixed_disk_range.max: - return False - return True + return _disk_size_fits(disk_size_mib, *self._fixed_disk_mib_bounds) def _get_disk(self, configurable_disk_size: Range[Memory]) -> Optional[Disk]: key = (configurable_disk_size.min, configurable_disk_size.max) @@ -339,7 +437,7 @@ def gpu_matches_gpu_spec(gpu: Gpu, gpu_spec: GPUSpec) -> bool: if gpu_spec.compute_capability is not None: if gpu.vendor != gpuhunt.AcceleratorVendor.NVIDIA: return False - compute_capability = NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP.get(gpu.name) + compute_capability = NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP.get(gpu.name.lower()) if compute_capability is None: return False if compute_capability < gpu_spec.compute_capability: diff --git a/src/tests/_internal/core/backends/base/test_offers.py b/src/tests/_internal/core/backends/base/test_offers.py index 5f7c911eab..b7c65c44ce 100644 --- a/src/tests/_internal/core/backends/base/test_offers.py +++ b/src/tests/_internal/core/backends/base/test_offers.py @@ -114,6 +114,11 @@ def test_compute_capability_gpu_lower_than_required(self): make_gpu(name="A100"), GPUSpec.model_validate({"compute_capability": "9.0"}) ) + def test_compute_capability_lookup_is_case_insensitive(self): + assert gpu_matches_gpu_spec( + make_gpu(name="a100"), GPUSpec.model_validate({"compute_capability": "8.0"}) + ) + def test_compute_capability_non_nvidia_never_matches(self): assert not gpu_matches_gpu_spec( make_gpu(name="MI300X", vendor=AMD), From 08abfb8b4d166b5f3a87bfa8f15595cac10b33c7 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 15:34:32 +0500 Subject: [PATCH 03/11] Compare OfferMatcher with gpuhunt.matches() in tests --- .../base/test_offer_matcher_gpuhunt.py | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py diff --git a/src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py b/src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py new file mode 100644 index 0000000000..8d74df5761 --- /dev/null +++ b/src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py @@ -0,0 +1,143 @@ +import itertools +from typing import Optional + +import gpuhunt +import pytest + +from dstack._internal.core.backends.base.offers import ( + OfferMatcher, + offer_to_catalog_item, + requirements_to_query_filter, +) +from dstack._internal.core.models.backends.base import BackendType +from dstack._internal.core.models.instances import ( + Disk, + Gpu, + InstanceOffer, + InstanceType, + Resources, +) +from dstack._internal.core.models.resources import ResourcesSpec +from dstack._internal.core.models.runs import Requirements + +NVIDIA = gpuhunt.AcceleratorVendor.NVIDIA +AMD = gpuhunt.AcceleratorVendor.AMD +GOOGLE = gpuhunt.AcceleratorVendor.GOOGLE + +_GPU_CONFIGS: list[list[Gpu]] = [ + [], + [Gpu(name="A100", memory_mib=40 * 1024, vendor=NVIDIA)], + [Gpu(name="A100", memory_mib=80 * 1024, vendor=NVIDIA)] * 8, + [Gpu(name="a100", memory_mib=80 * 1024, vendor=NVIDIA)] * 2, + [Gpu(name="H100", memory_mib=80 * 1024, vendor=NVIDIA)] * 8, + [Gpu(name="T4", memory_mib=16 * 1024, vendor=NVIDIA)], + [Gpu(name="UnknownGPU", memory_mib=24 * 1024, vendor=NVIDIA)], + [Gpu(name="MI300X", memory_mib=192 * 1024, vendor=AMD)] * 8, + [Gpu(name="v5litepod-8", memory_mib=16 * 1024, vendor=GOOGLE)], +] + + +def _make_offers() -> list[InstanceOffer]: + offers = [] + for spot, cpu_arch, cpus, memory_mib, gpus, disk_gib, price in itertools.product( + [False, True], + [None, gpuhunt.CPUArchitecture.X86, gpuhunt.CPUArchitecture.ARM], + [1, 4, 96], + [512, 16 * 1024, 1024 * 1024], + _GPU_CONFIGS, + [0, 50, 500], + [0.5, 2.0], + ): + offers.append( + InstanceOffer( + backend=BackendType.AWS, + instance=InstanceType( + name="test-instance", + resources=Resources( + cpus=cpus, + memory_mib=memory_mib, + gpus=gpus, + spot=spot, + disk=Disk(size_mib=disk_gib * 1024), + cpu_arch=cpu_arch, + ), + ), + region="test-region", + price=price, + ) + ) + return offers + + +_OFFERS = _make_offers() + +_RESOURCES = [ + {}, + {"gpu": None}, + {"gpu": 0}, + {"gpu": "1.."}, + {"gpu": "..8"}, + {"gpu": "2..4"}, + {"gpu": "nvidia"}, + {"gpu": "nvidia:..8"}, + {"gpu": "nvidia:0.."}, + {"gpu": "amd"}, + {"gpu": "tpu"}, + {"gpu": "A100"}, + {"gpu": "a100:2.."}, + {"gpu": "A100,H100:8"}, + {"gpu": {"name": [], "count": "0.."}}, + {"gpu": {"name": [], "count": "..8"}}, + {"gpu": {"name": ["A100"], "count": "0.."}}, + {"gpu": "40GB.."}, + {"gpu": "24GB..80GB"}, + {"gpu": {"memory": "24GB..", "count": "0.."}}, + {"gpu": {"memory": "24GB..", "count": "..8"}}, + {"gpu": {"memory": "..16GB", "count": "..8"}}, + {"gpu": {"total_memory": "160GB.."}}, + {"gpu": {"total_memory": "..100GB", "count": "..8"}}, + {"gpu": {"total_memory": "1GB..", "count": "..8"}}, + {"gpu": {"compute_capability": "8.0"}}, + {"gpu": {"compute_capability": "9.0", "count": "0.."}}, + {"gpu": {"compute_capability": "7.5", "count": "..8"}}, + {"gpu": {"vendor": "nvidia", "name": ["A100"], "memory": "80GB", "count": 8}}, + {"cpu": "arm"}, + {"cpu": "x86:4.."}, + {"cpu": "..4"}, + {"cpu": "4..4"}, + {"memory": "0.5GB.."}, + {"memory": "..16GB"}, + {"memory": "1TB.."}, + {"disk": "100GB.."}, + {"disk": "..100GB"}, + {"disk": None}, + {"cpu": "..1", "memory": "..1GB", "gpu": 0, "disk": "..10GB"}, +] + +_REQUIREMENTS = [ + pytest.param( + Requirements( + resources=ResourcesSpec.model_validate(resources), spot=spot, max_price=price + ), + id=f"{resources}-spot={spot}-max_price={price}", + ) + for resources, spot, price in itertools.chain( + ((resources, None, None) for resources in _RESOURCES), + (({}, spot, None) for spot in [True, False]), + (({}, None, price) for price in [0.5, 1.0, 2.0]), + (({"gpu": "A100"}, False, 1.0),), + ) +] + + +@pytest.mark.parametrize("requirements", _REQUIREMENTS) +@pytest.mark.parametrize("check_disk", [True, False]) +def test_offer_matcher_matches_gpuhunt(requirements: Requirements, check_disk: bool): + matcher = OfferMatcher(requirements, check_disk=check_disk) + query_filter = requirements_to_query_filter(requirements, ignore_disk=not check_disk) + mismatches: list[tuple[InstanceOffer, Optional[bool]]] = [] + for offer in _OFFERS: + expected = gpuhunt.matches(offer_to_catalog_item(offer), q=query_filter) + if matcher.matches(offer) != expected: + mismatches.append((offer, expected)) + assert mismatches == [] From 6fb89ee5f8d5ab6b44cfdfdab2f6d315f4c8d7ea Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 15:43:20 +0500 Subject: [PATCH 04/11] Remove offer_to_catalog_item() --- .../_internal/core/backends/base/offers.py | 35 ----- .../base/test_offer_matcher_gpuhunt.py | 143 ------------------ 2 files changed, 178 deletions(-) delete mode 100644 src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 6b93b863c2..17f36a66e4 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -133,41 +133,6 @@ def catalog_item_to_offer( ) -def offer_to_catalog_item(offer: InstanceOffer) -> gpuhunt.CatalogItem: - cpu_arch = offer.instance.resources.cpu_arch - if cpu_arch is None: - cpu_arch = gpuhunt.CPUArchitecture.X86 - gpu_count = len(offer.instance.resources.gpus) - gpu_vendor = None - gpu_name = None - gpu_memory = None - if gpu_count > 0: - gpu = offer.instance.resources.gpus[0] - gpu_vendor = gpu.vendor - gpu_name = gpu.name - gpu_memory = gpu.memory_mib / 1024 - # Resources.disk.size_mib = 0 -> gpuhunt.CatalogItem.disk_size = None -> gpuhunt.matches() - # doesn't check disk size (gpuhunt.QueryFilter.{min_disk_size,max_disk_size} are ignored) - disk_size: Optional[float] = None - if (disk_size_mib := offer.instance.resources.disk.size_mib) != 0: - disk_size = disk_size_mib / 1024 - return gpuhunt.CatalogItem( - provider=offer.backend.value, - instance_name=offer.instance.name, - location=offer.region, - price=offer.price, - cpu_arch=cpu_arch, - cpu=offer.instance.resources.cpus, - memory=offer.instance.resources.memory_mib / 1024, - gpu_count=gpu_count, - gpu_vendor=gpu_vendor, - gpu_name=gpu_name, - gpu_memory=gpu_memory, - spot=offer.instance.resources.spot, - disk_size=disk_size, - ) - - def requirements_to_query_filter( req: Optional[Requirements], ignore_disk: bool = False ) -> gpuhunt.QueryFilter: diff --git a/src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py b/src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py deleted file mode 100644 index 8d74df5761..0000000000 --- a/src/tests/_internal/core/backends/base/test_offer_matcher_gpuhunt.py +++ /dev/null @@ -1,143 +0,0 @@ -import itertools -from typing import Optional - -import gpuhunt -import pytest - -from dstack._internal.core.backends.base.offers import ( - OfferMatcher, - offer_to_catalog_item, - requirements_to_query_filter, -) -from dstack._internal.core.models.backends.base import BackendType -from dstack._internal.core.models.instances import ( - Disk, - Gpu, - InstanceOffer, - InstanceType, - Resources, -) -from dstack._internal.core.models.resources import ResourcesSpec -from dstack._internal.core.models.runs import Requirements - -NVIDIA = gpuhunt.AcceleratorVendor.NVIDIA -AMD = gpuhunt.AcceleratorVendor.AMD -GOOGLE = gpuhunt.AcceleratorVendor.GOOGLE - -_GPU_CONFIGS: list[list[Gpu]] = [ - [], - [Gpu(name="A100", memory_mib=40 * 1024, vendor=NVIDIA)], - [Gpu(name="A100", memory_mib=80 * 1024, vendor=NVIDIA)] * 8, - [Gpu(name="a100", memory_mib=80 * 1024, vendor=NVIDIA)] * 2, - [Gpu(name="H100", memory_mib=80 * 1024, vendor=NVIDIA)] * 8, - [Gpu(name="T4", memory_mib=16 * 1024, vendor=NVIDIA)], - [Gpu(name="UnknownGPU", memory_mib=24 * 1024, vendor=NVIDIA)], - [Gpu(name="MI300X", memory_mib=192 * 1024, vendor=AMD)] * 8, - [Gpu(name="v5litepod-8", memory_mib=16 * 1024, vendor=GOOGLE)], -] - - -def _make_offers() -> list[InstanceOffer]: - offers = [] - for spot, cpu_arch, cpus, memory_mib, gpus, disk_gib, price in itertools.product( - [False, True], - [None, gpuhunt.CPUArchitecture.X86, gpuhunt.CPUArchitecture.ARM], - [1, 4, 96], - [512, 16 * 1024, 1024 * 1024], - _GPU_CONFIGS, - [0, 50, 500], - [0.5, 2.0], - ): - offers.append( - InstanceOffer( - backend=BackendType.AWS, - instance=InstanceType( - name="test-instance", - resources=Resources( - cpus=cpus, - memory_mib=memory_mib, - gpus=gpus, - spot=spot, - disk=Disk(size_mib=disk_gib * 1024), - cpu_arch=cpu_arch, - ), - ), - region="test-region", - price=price, - ) - ) - return offers - - -_OFFERS = _make_offers() - -_RESOURCES = [ - {}, - {"gpu": None}, - {"gpu": 0}, - {"gpu": "1.."}, - {"gpu": "..8"}, - {"gpu": "2..4"}, - {"gpu": "nvidia"}, - {"gpu": "nvidia:..8"}, - {"gpu": "nvidia:0.."}, - {"gpu": "amd"}, - {"gpu": "tpu"}, - {"gpu": "A100"}, - {"gpu": "a100:2.."}, - {"gpu": "A100,H100:8"}, - {"gpu": {"name": [], "count": "0.."}}, - {"gpu": {"name": [], "count": "..8"}}, - {"gpu": {"name": ["A100"], "count": "0.."}}, - {"gpu": "40GB.."}, - {"gpu": "24GB..80GB"}, - {"gpu": {"memory": "24GB..", "count": "0.."}}, - {"gpu": {"memory": "24GB..", "count": "..8"}}, - {"gpu": {"memory": "..16GB", "count": "..8"}}, - {"gpu": {"total_memory": "160GB.."}}, - {"gpu": {"total_memory": "..100GB", "count": "..8"}}, - {"gpu": {"total_memory": "1GB..", "count": "..8"}}, - {"gpu": {"compute_capability": "8.0"}}, - {"gpu": {"compute_capability": "9.0", "count": "0.."}}, - {"gpu": {"compute_capability": "7.5", "count": "..8"}}, - {"gpu": {"vendor": "nvidia", "name": ["A100"], "memory": "80GB", "count": 8}}, - {"cpu": "arm"}, - {"cpu": "x86:4.."}, - {"cpu": "..4"}, - {"cpu": "4..4"}, - {"memory": "0.5GB.."}, - {"memory": "..16GB"}, - {"memory": "1TB.."}, - {"disk": "100GB.."}, - {"disk": "..100GB"}, - {"disk": None}, - {"cpu": "..1", "memory": "..1GB", "gpu": 0, "disk": "..10GB"}, -] - -_REQUIREMENTS = [ - pytest.param( - Requirements( - resources=ResourcesSpec.model_validate(resources), spot=spot, max_price=price - ), - id=f"{resources}-spot={spot}-max_price={price}", - ) - for resources, spot, price in itertools.chain( - ((resources, None, None) for resources in _RESOURCES), - (({}, spot, None) for spot in [True, False]), - (({}, None, price) for price in [0.5, 1.0, 2.0]), - (({"gpu": "A100"}, False, 1.0),), - ) -] - - -@pytest.mark.parametrize("requirements", _REQUIREMENTS) -@pytest.mark.parametrize("check_disk", [True, False]) -def test_offer_matcher_matches_gpuhunt(requirements: Requirements, check_disk: bool): - matcher = OfferMatcher(requirements, check_disk=check_disk) - query_filter = requirements_to_query_filter(requirements, ignore_disk=not check_disk) - mismatches: list[tuple[InstanceOffer, Optional[bool]]] = [] - for offer in _OFFERS: - expected = gpuhunt.matches(offer_to_catalog_item(offer), q=query_filter) - if matcher.matches(offer) != expected: - mismatches.append((offer, expected)) - assert mismatches == [] From 911c0b928a2310c0714efcdcf4dba016e6f5c654 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 15:55:58 +0500 Subject: [PATCH 05/11] Remove filter_offers_by_requirements() --- .../_internal/core/backends/base/compute.py | 5 +++-- .../_internal/core/backends/base/offers.py | 15 --------------- .../core/backends/base/test_offers.py | 19 ------------------- 3 files changed, 3 insertions(+), 36 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/compute.py b/src/dstack/_internal/core/backends/base/compute.py index be0e089c51..da099343f3 100644 --- a/src/dstack/_internal/core/backends/base/compute.py +++ b/src/dstack/_internal/core/backends/base/compute.py @@ -23,8 +23,8 @@ from dstack._internal.core.backends.base.models import JobConfiguration from dstack._internal.core.backends.base.offers import ( OfferDiskFitter, + OfferMatcher, OfferModifier, - filter_offers_by_requirements, ) from dstack._internal.core.consts import ( DSTACK_RUNNER_HTTP_PORT, @@ -296,7 +296,8 @@ def get_offers( offers = self.__apply_modifiers( cached_offers, self.get_offers_modifiers(requirements, full_offers) ) - offers = filter_offers_by_requirements(offers, requirements, ignore_disk=True) + matcher = OfferMatcher(requirements, check_disk=False) + offers = (o for o in offers if matcher.matches(o)) offers = self.__fit_disk_size(offers, requirements) post_filter = self.get_offers_post_filter(requirements) if post_filter is not None: diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 17f36a66e4..573677a7d8 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -1,5 +1,4 @@ from abc import ABC, abstractmethod -from collections.abc import Iterable, Iterator from dataclasses import asdict from typing import Callable, Generic, List, Literal, Optional, TypeVar, Union from uuid import UUID @@ -247,20 +246,6 @@ def _matches_gpus(self, gpus: list[Gpu]) -> bool: ) -InstanceOfferT = TypeVar("InstanceOfferT", InstanceOffer, InstanceOfferWithAvailability) - - -def filter_offers_by_requirements( - offers: Iterable[InstanceOfferT], - requirements: Requirements, - ignore_disk: bool = False, -) -> Iterator[InstanceOfferT]: - matcher = OfferMatcher(requirements, check_disk=not ignore_disk) - for offer in offers: - if matcher.matches(offer): - yield offer - - def _gpu_spec_matches_no_gpus(gpu_spec: GPUSpec) -> bool: if gpu_spec.count.min == 0: return True diff --git a/src/tests/_internal/core/backends/base/test_offers.py b/src/tests/_internal/core/backends/base/test_offers.py index b7c65c44ce..7a5a63d50e 100644 --- a/src/tests/_internal/core/backends/base/test_offers.py +++ b/src/tests/_internal/core/backends/base/test_offers.py @@ -6,7 +6,6 @@ from dstack._internal.core.backends.base.offers import ( OfferDiskFitter, OfferMatcher, - filter_offers_by_requirements, gpu_matches_gpu_spec, ) from dstack._internal.core.models.backends.base import BackendType @@ -506,24 +505,6 @@ def test_all_constraints_match(self): assert matches(offer, requirements) -class TestFilterOffersByRequirements: - def test_yields_matching_offers_in_order(self): - offers = [make_offer(cpus=16), make_offer(cpus=1), make_offer(cpus=8)] - - result = list(filter_offers_by_requirements(offers, make_requirements())) - - assert result == [offers[0], offers[2]] - - def test_ignore_disk_skips_disk_requirement(self): - offer = make_offer(disk_gib=50) - requirements = make_requirements({"disk": "100GB.."}) - - assert list(filter_offers_by_requirements([offer], requirements)) == [] - assert list(filter_offers_by_requirements([offer], requirements, ignore_disk=True)) == [ - offer - ] - - class TestOfferDiskFitter: def test_sets_min_disk_size_within_configurable_and_required_ranges(self): offer = get_instance_offer_with_availability(gpu_count=1, disk_gib=100) From 39c3f88e003405fd7df0cfbc28e373fd53883ec1 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 15:56:53 +0500 Subject: [PATCH 06/11] Speed up GCP reserved-only offers filter --- .../_internal/core/backends/gcp/compute.py | 15 ++++------- .../core/backends/gcp/test_compute.py | 26 +++++++++++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/dstack/_internal/core/backends/gcp/compute.py b/src/dstack/_internal/core/backends/gcp/compute.py index 5877776dfe..13d3ebd3bf 100644 --- a/src/dstack/_internal/core/backends/gcp/compute.py +++ b/src/dstack/_internal/core/backends/gcp/compute.py @@ -72,7 +72,6 @@ ) from dstack._internal.core.models.common import ( CoreModel, - validate_extra_ignore, validate_json_extra_ignore, ) from dstack._internal.core.models.gateways import ( @@ -114,10 +113,6 @@ DEFAULT_GATEWAY_INSTANCE_TYPE = "e2-medium" -class GCPOfferBackendData(CoreModel): - is_dws_calendar_mode: bool = False - - class GCPVolumeDiskBackendData(CoreModel): type: Literal["disk"] = "disk" disk_type: str @@ -276,11 +271,11 @@ def get_offers_post_filter( def reserved_offers_filter(offer: InstanceOfferWithAvailability) -> bool: """Remove reserved-only offers""" - if validate_extra_ignore( - GCPOfferBackendData, offer.backend_data - ).is_dws_calendar_mode: - return False - return True + # The filter runs for every offer that matches the requirements, often tens + # of thousands per query, so it reads the flag from `backend_data` (gpuhunt's + # `provider_data`) directly. Validating `backend_data` into a model is ~20x + # slower per offer. + return not offer.backend_data.get("is_dws_calendar_mode", False) return reserved_offers_filter diff --git a/src/tests/_internal/core/backends/gcp/test_compute.py b/src/tests/_internal/core/backends/gcp/test_compute.py index 341df09cc6..9f6a161f61 100644 --- a/src/tests/_internal/core/backends/gcp/test_compute.py +++ b/src/tests/_internal/core/backends/gcp/test_compute.py @@ -14,6 +14,9 @@ from dstack._internal.core.errors import ComputeError from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.backends.orphans import ListedResourceGroup, OwnerType +from dstack._internal.core.models.resources import ResourcesSpec +from dstack._internal.core.models.runs import Requirements +from dstack._internal.server.testing.common import get_instance_offer_with_availability PROJECT_ID = "test-project" PROVIDER_REF = "abc123def456" @@ -79,6 +82,29 @@ def test_returns_tpu_offers_only_if_enabled(self, mocker, tpu_config): assert [offer.instance.name for offer in offers] == expected_names +class TestGetOffersPostFilter: + def test_removes_reserved_only_offers_without_reservation(self, mocker): + compute = _get_compute(mocker, regions=["us-central1"]) + offer = get_instance_offer_with_availability(backend=BackendType.GCP) + reserved_only_offer = offer.model_copy( + update={"backend_data": {"is_dws_calendar_mode": True}} + ) + regular_offer = offer.model_copy(update={"backend_data": {"is_dws_calendar_mode": False}}) + + post_filter = compute.get_offers_post_filter(Requirements(resources=ResourcesSpec())) + + assert post_filter is not None + assert not post_filter(reserved_only_offer) + assert post_filter(regular_offer) + assert post_filter(offer) + + def test_keeps_all_offers_with_reservation(self, mocker): + compute = _get_compute(mocker, regions=["us-central1"]) + requirements = Requirements(resources=ResourcesSpec(), reservation="test-reservation") + + assert compute.get_offers_post_filter(requirements) is None + + def _get_vm( name: str, provider_ref: Optional[str] = PROVIDER_REF, status: str = "RUNNING" ) -> compute_v1.Instance: From ce23ac34c1b48d63c26cc1aadefb94dbe7b883b2 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 16:07:57 +0500 Subject: [PATCH 07/11] Simplify OfferMatcher --- .../_internal/core/backends/base/offers.py | 53 ++++++++----------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 573677a7d8..53d20b92be 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -1,6 +1,6 @@ from abc import ABC, abstractmethod from dataclasses import asdict -from typing import Callable, Generic, List, Literal, Optional, TypeVar, Union +from typing import Callable, Generic, List, Literal, Optional, TypeVar from uuid import UUID import gpuhunt @@ -132,9 +132,7 @@ def catalog_item_to_offer( ) -def requirements_to_query_filter( - req: Optional[Requirements], ignore_disk: bool = False -) -> gpuhunt.QueryFilter: +def requirements_to_query_filter(req: Optional[Requirements]) -> gpuhunt.QueryFilter: q = gpuhunt.QueryFilter(allowed_flags=SUPPORTED_GPUHUNT_FLAGS) if req is None: return q @@ -151,7 +149,7 @@ def requirements_to_query_filter( if res.memory: q.min_memory = res.memory.min q.max_memory = res.memory.max - if res.disk and not ignore_disk: + if res.disk: # `QueryFilter` disk size bounds are typed as `int` until the next gpuhunt release q.min_disk_size = res.disk.size.min # pyright: ignore[reportAttributeAccessIssue] q.max_disk_size = res.disk.size.max # pyright: ignore[reportAttributeAccessIssue] @@ -174,16 +172,21 @@ def requirements_to_query_filter( return q +# `(min, max)`, where `None` means unbounded. +_Bounds = tuple[Optional[float], Optional[float]] + + class OfferMatcher: """ Matches offers against `requirements`. Create one per `requirements` and reuse it for all offers. - GPU constraints are checked against the offer's first GPU. If `requirements` allow zero - GPUs, offers without GPUs match regardless of other GPU constraints. Otherwise, an offer - without GPUs is treated as having no GPU vendor, name, or compute capability, and 0 GPU - memory. The disk is not checked if the offer's disk size is unknown (`size_mib == 0`). + GPU constraints are checked against the offer's first GPU. If the minimum required GPU + count is 0, offers without GPUs match regardless of other GPU constraints. Otherwise, an + offer without GPUs is treated as having no GPU vendor, name, or compute capability, and + 0 GPU memory, so e.g. `gpu: nvidia:..8` doesn't match it. The disk is not checked if + the offer's disk size is unknown (`size_mib == 0`). """ def __init__(self, requirements: Requirements, *, check_disk: bool = True) -> None: @@ -191,19 +194,15 @@ def __init__(self, requirements: Requirements, *, check_disk: bool = True) -> No self._max_price = requirements.max_price self._spot = requirements.spot self._cpu_arch = resources.cpu.arch - self._min_cpus = resources.cpu.count.min - self._max_cpus = resources.cpu.count.max - self._min_memory_mib, self._max_memory_mib = _get_mib_bounds(resources.memory) + self._cpu_bounds: _Bounds = (resources.cpu.count.min, resources.cpu.count.max) + self._memory_mib_bounds = _get_mib_bounds(resources.memory) self._gpu_spec = resources.gpu - self._min_total_gpu_memory_mib: Optional[float] = None - self._max_total_gpu_memory_mib: Optional[float] = None + self._total_gpu_memory_mib_bounds: _Bounds = (None, None) self._matches_no_gpus = True if self._gpu_spec is not None: - self._min_total_gpu_memory_mib, self._max_total_gpu_memory_mib = _get_mib_bounds( - self._gpu_spec.total_memory - ) + self._total_gpu_memory_mib_bounds = _get_mib_bounds(self._gpu_spec.total_memory) self._matches_no_gpus = _gpu_spec_matches_no_gpus(self._gpu_spec) - self._disk_mib_bounds: Optional[tuple[Optional[float], Optional[float]]] = None + self._disk_mib_bounds: Optional[_Bounds] = None if check_disk and resources.disk is not None: self._disk_mib_bounds = _get_mib_bounds(resources.disk.size) @@ -217,9 +216,9 @@ def matches(self, offer: InstanceOffer) -> bool: cpu_arch = resources.cpu_arch or gpuhunt.CPUArchitecture.X86 if cpu_arch != self._cpu_arch: return False - if not _is_within(resources.cpus, self._min_cpus, self._max_cpus): + if not _is_within(resources.cpus, *self._cpu_bounds): return False - if not _is_within(resources.memory_mib, self._min_memory_mib, self._max_memory_mib): + if not _is_within(resources.memory_mib, *self._memory_mib_bounds): return False if not self._matches_gpus(resources.gpus): return False @@ -239,11 +238,7 @@ def _matches_gpus(self, gpus: list[Gpu]) -> bool: return False if not gpu_matches_gpu_spec(gpus[0], gpu_spec): return False - return _is_within( - len(gpus) * gpus[0].memory_mib, - self._min_total_gpu_memory_mib, - self._max_total_gpu_memory_mib, - ) + return _is_within(len(gpus) * gpus[0].memory_mib, *self._total_gpu_memory_mib_bounds) def _gpu_spec_matches_no_gpus(gpu_spec: GPUSpec) -> bool: @@ -259,9 +254,7 @@ def _gpu_spec_matches_no_gpus(gpu_spec: GPUSpec) -> bool: ) -def _get_mib_bounds( - memory_range: Optional[Range[Memory]], -) -> tuple[Optional[float], Optional[float]]: +def _get_mib_bounds(memory_range: Optional[Range[Memory]]) -> _Bounds: if memory_range is None: return None, None min_mib = memory_range.min * 1024 if memory_range.min is not None else None @@ -278,9 +271,7 @@ def _disk_size_fits( return _is_within(disk_size_mib, min_mib, max_mib) -def _is_within( - value: Union[int, float], min_value: Optional[float], max_value: Optional[float] -) -> bool: +def _is_within(value: float, min_value: Optional[float], max_value: Optional[float]) -> bool: if min_value is not None and value < min_value: return False if max_value is not None and value > max_value: From 83fbb09fda9533302abf566e03a857c4f6287eb1 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 16:09:16 +0500 Subject: [PATCH 08/11] Use docstrings for offer matching constants and attributes --- .../_internal/core/backends/base/offers.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 53d20b92be..984d610182 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -33,13 +33,15 @@ ] -# NvidiaGPUInfo.name in KNOWN_NVIDIA_GPUS is not unique -- there are multiple variants -# with the same name but different amount of memory, but Compute Capability of the variants -# is always the same, so it's safe to use 1:1 mapping. -# Keys are lowercase GPU names. NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP = { gpu_info.name.lower(): gpu_info.compute_capability for gpu_info in gpuhunt.KNOWN_NVIDIA_GPUS } +"""Keys are lowercase GPU names. + +`NvidiaGPUInfo.name` in `KNOWN_NVIDIA_GPUS` is not unique -- there are multiple variants with +the same name but different amount of memory, but Compute Capability of the variants is always +the same, so it's safe to use 1:1 mapping. +""" def get_catalog_offers( @@ -172,8 +174,8 @@ def requirements_to_query_filter(req: Optional[Requirements]) -> gpuhunt.QueryFi return q -# `(min, max)`, where `None` means unbounded. _Bounds = tuple[Optional[float], Optional[float]] +"""`(min, max)`, where `None` means unbounded.""" class OfferMatcher: @@ -309,12 +311,12 @@ class OfferDiskFitter: def __init__(self, requirements: Requirements) -> None: disk_spec = requirements.resources.disk - # The bounds fixed disks are checked against, `None` if fixed disks are not checked. self._fixed_disk_mib_bounds = ( _get_mib_bounds(disk_spec.size) if disk_spec is not None else None ) - # The range configurable disks are fitted to. + """The bounds fixed disks are checked against, `None` if fixed disks are not checked.""" self._target_disk_range = disk_spec.size if disk_spec is not None else DEFAULT_DISK.size + """The range configurable disks are fitted to.""" self._disk_by_range: dict[tuple[Optional[float], Optional[float]], Optional[Disk]] = {} def fit( From 9149ee14a7c2e22669918871ac912126a01bef43 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 16:11:40 +0500 Subject: [PATCH 09/11] Drop stale type ignores --- src/dstack/_internal/core/backends/base/offers.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 984d610182..747194667c 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -152,9 +152,8 @@ def requirements_to_query_filter(req: Optional[Requirements]) -> gpuhunt.QueryFi q.min_memory = res.memory.min q.max_memory = res.memory.max if res.disk: - # `QueryFilter` disk size bounds are typed as `int` until the next gpuhunt release - q.min_disk_size = res.disk.size.min # pyright: ignore[reportAttributeAccessIssue] - q.max_disk_size = res.disk.size.max # pyright: ignore[reportAttributeAccessIssue] + q.min_disk_size = res.disk.size.min + q.max_disk_size = res.disk.size.max if res.gpu: q.gpu_vendor = res.gpu.vendor From 1b7be41917389f21477b267898819140624c8483 Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 16:16:48 +0500 Subject: [PATCH 10/11] Move gpu_matches_gpu_spec() next to OfferMatcher --- .../_internal/core/backends/base/offers.py | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 747194667c..979ce8a72a 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -36,8 +36,7 @@ NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP = { gpu_info.name.lower(): gpu_info.compute_capability for gpu_info in gpuhunt.KNOWN_NVIDIA_GPUS } -"""Keys are lowercase GPU names. - +""" `NvidiaGPUInfo.name` in `KNOWN_NVIDIA_GPUS` is not unique -- there are multiple variants with the same name but different amount of memory, but Compute Capability of the variants is always the same, so it's safe to use 1:1 mapping. @@ -242,6 +241,29 @@ def _matches_gpus(self, gpus: list[Gpu]) -> bool: return _is_within(len(gpus) * gpus[0].memory_mib, *self._total_gpu_memory_mib_bounds) +def gpu_matches_gpu_spec(gpu: Gpu, gpu_spec: GPUSpec) -> bool: + if gpu_spec.vendor is not None and gpu.vendor != gpu_spec.vendor: + return False + if gpu_spec.name is not None and gpu.name.lower() not in map(str.lower, gpu_spec.name): + return False + if gpu_spec.memory is not None: + min_memory_gib = gpu_spec.memory.min + if min_memory_gib is not None and gpu.memory_mib < min_memory_gib * 1024: + return False + max_memory_gib = gpu_spec.memory.max + if max_memory_gib is not None and gpu.memory_mib > max_memory_gib * 1024: + return False + if gpu_spec.compute_capability is not None: + if gpu.vendor != gpuhunt.AcceleratorVendor.NVIDIA: + return False + compute_capability = NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP.get(gpu.name.lower()) + if compute_capability is None: + return False + if compute_capability < gpu_spec.compute_capability: + return False + return True + + def _gpu_spec_matches_no_gpus(gpu_spec: GPUSpec) -> bool: if gpu_spec.count.min == 0: return True @@ -364,29 +386,6 @@ def _get_disk(self, configurable_disk_size: Range[Memory]) -> Optional[Disk]: return self._disk_by_range[key] -def gpu_matches_gpu_spec(gpu: Gpu, gpu_spec: GPUSpec) -> bool: - if gpu_spec.vendor is not None and gpu.vendor != gpu_spec.vendor: - return False - if gpu_spec.name is not None and gpu.name.lower() not in map(str.lower, gpu_spec.name): - return False - if gpu_spec.memory is not None: - min_memory_gib = gpu_spec.memory.min - if min_memory_gib is not None and gpu.memory_mib < min_memory_gib * 1024: - return False - max_memory_gib = gpu_spec.memory.max - if max_memory_gib is not None and gpu.memory_mib > max_memory_gib * 1024: - return False - if gpu_spec.compute_capability is not None: - if gpu.vendor != gpuhunt.AcceleratorVendor.NVIDIA: - return False - compute_capability = NVIDIA_GPU_NAME_TO_COMPUTE_CAPABILITY_MAP.get(gpu.name.lower()) - if compute_capability is None: - return False - if compute_capability < gpu_spec.compute_capability: - return False - return True - - OfferKeyT = TypeVar("OfferKeyT") From 456e962ddf7905e34a73a509bf54c4cab1982eaf Mon Sep 17 00:00:00 2001 From: Victor Skvortsov Date: Wed, 25 Nov 2026 16:40:42 +0500 Subject: [PATCH 11/11] Build one OfferMatcher per fleet when checking instances against the spec --- src/dstack/_internal/core/backends/base/offers.py | 2 ++ .../server/background/pipeline_tasks/fleets.py | 10 ++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/dstack/_internal/core/backends/base/offers.py b/src/dstack/_internal/core/backends/base/offers.py index 979ce8a72a..206a56d0db 100644 --- a/src/dstack/_internal/core/backends/base/offers.py +++ b/src/dstack/_internal/core/backends/base/offers.py @@ -236,6 +236,8 @@ def _matches_gpus(self, gpus: list[Gpu]) -> bool: return self._matches_no_gpus if not _is_within(len(gpus), gpu_spec.count.min, gpu_spec.count.max): return False + # Assumes all GPUs are the same. On hosts with mixed GPUs (e.g. SSH or Kubernetes), + # the other GPUs are not checked and total memory is estimated from the first one. if not gpu_matches_gpu_spec(gpus[0], gpu_spec): return False return _is_within(len(gpus) * gpus[0].memory_mib, *self._total_gpu_memory_mib_bounds) diff --git a/src/dstack/_internal/server/background/pipeline_tasks/fleets.py b/src/dstack/_internal/server/background/pipeline_tasks/fleets.py index 43cdb6cbca..75b7e8a1cc 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/fleets.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/fleets.py @@ -628,10 +628,11 @@ def _terminate_instances_not_matching_fleet_spec( fleet_spec: FleetSpec, ) -> dict[uuid.UUID, _InstanceUpdateMap]: updates: dict[uuid.UUID, _InstanceUpdateMap] = {} + offer_matcher = OfferMatcher(get_fleet_requirements(fleet_spec)) for instance in instances: if not _can_terminate_spec_mismatched_instance(instance): continue - if not _instance_matches_fleet_spec(instance, fleet_spec): + if not _instance_matches_fleet_spec(instance, fleet_spec, offer_matcher): updates[instance.id] = { "status": InstanceStatus.TERMINATING, "termination_reason": InstanceTerminationReason.FLEET_SPEC_MISMATCH, @@ -648,19 +649,20 @@ def _can_terminate_spec_mismatched_instance(instance: InstanceModel) -> bool: return instance.status in (InstanceStatus.IDLE, InstanceStatus.PROVISIONING) -def _instance_matches_fleet_spec(instance: InstanceModel, fleet_spec: FleetSpec) -> bool: +def _instance_matches_fleet_spec( + instance: InstanceModel, fleet_spec: FleetSpec, offer_matcher: OfferMatcher +) -> bool: if instance.offer is None: # Not yet provisioned — will be provisioned using the current (updated) spec. return True profile = fleet_spec.merged_profile - requirements = get_fleet_requirements(fleet_spec) return instance_matches_constraints( instance, backend_types=profile.backends, regions=profile.regions, instance_types=profile.instance_types, zones=profile.availability_zones, - offer_matcher=OfferMatcher(requirements), + offer_matcher=offer_matcher, )