diff --git a/src/dstack/_internal/core/backends/base/compute.py b/src/dstack/_internal/core/backends/base/compute.py index be0e089c5..da099343f 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 cad3b0b6b..206a56d0d 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 from uuid import UUID @@ -34,12 +33,14 @@ ] -# 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 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 } +""" +`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( @@ -132,44 +133,7 @@ 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: +def requirements_to_query_filter(req: Optional[Requirements]) -> gpuhunt.QueryFilter: q = gpuhunt.QueryFilter(allowed_flags=SUPPORTED_GPUHUNT_FLAGS) if req is None: return q @@ -186,10 +150,9 @@ 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: - # `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] + if res.disk: + 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 @@ -209,19 +172,136 @@ def requirements_to_query_filter( return q -InstanceOfferT = TypeVar("InstanceOfferT", InstanceOffer, InstanceOfferWithAvailability) +_Bounds = tuple[Optional[float], Optional[float]] +"""`(min, max)`, where `None` means unbounded.""" -def filter_offers_by_requirements( - offers: Iterable[InstanceOfferT], - requirements: Optional[Requirements], - ignore_disk: bool = False, -) -> Iterator[InstanceOfferT]: - query_filter = requirements_to_query_filter(requirements, ignore_disk=ignore_disk) - for offer in offers: - catalog_item = offer_to_catalog_item(offer) - if gpuhunt.matches(catalog_item, q=query_filter): - yield offer +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 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: + resources = requirements.resources + self._max_price = requirements.max_price + self._spot = requirements.spot + self._cpu_arch = resources.cpu.arch + 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._total_gpu_memory_mib_bounds: _Bounds = (None, None) + self._matches_no_gpus = True + if self._gpu_spec is not None: + 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[_Bounds] = 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: + 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._cpu_bounds): + return False + if not _is_within(resources.memory_mib, *self._memory_mib_bounds): + 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 + # 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) + + +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 + 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]]) -> _Bounds: + 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: 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( @@ -254,10 +334,12 @@ 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 range configurable disks are fitted to. + self._fixed_disk_mib_bounds = ( + _get_mib_bounds(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._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( @@ -269,7 +351,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). @@ -291,14 +373,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) @@ -311,29 +388,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) - if compute_capability is None: - return False - if compute_capability < gpu_spec.compute_capability: - return False - return True - - OfferKeyT = TypeVar("OfferKeyT") diff --git a/src/dstack/_internal/core/backends/gcp/compute.py b/src/dstack/_internal/core/backends/gcp/compute.py index 5877776df..13d3ebd3b 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/dstack/_internal/server/background/pipeline_tasks/fleets.py b/src/dstack/_internal/server/background/pipeline_tasks/fleets.py index 4904e7e3a..75b7e8a1c 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, @@ -627,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, @@ -647,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, - requirements=requirements, + offer_matcher=offer_matcher, ) diff --git a/src/dstack/_internal/server/services/instances.py b/src/dstack/_internal/server/services/instances.py index d08baf50f..734fc6373 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 922e70939..7a5a63d50 100644 --- a/src/tests/_internal/core/backends/base/test_offers.py +++ b/src/tests/_internal/core/backends/base/test_offers.py @@ -5,7 +5,7 @@ from dstack._internal.core.backends.base.offers import ( OfferDiskFitter, - filter_offers_by_requirements, + OfferMatcher, gpu_matches_gpu_spec, ) from dstack._internal.core.models.backends.base import BackendType @@ -22,6 +22,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: @@ -110,6 +113,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), @@ -138,65 +146,363 @@ 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"}) - ) - assert list(filter_offers_by_requirements([offer], requirements)) == [offer] +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 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 list(filter_offers_by_requirements([offer], requirements)) == [] +def matches(offer: InstanceOffer, requirements: Requirements, check_disk: bool = True) -> bool: + return OfferMatcher(requirements, check_disk=check_disk).matches(offer) - 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"}) + +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_ignore_disk_skips_disk_requirement(self): - 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) + + def test_gpu_name_implies_at_least_one_gpu(self): + assert not matches(CPU_ONLY, make_requirements({"gpu": "A100"})) + + 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, ignore_disk=True)) == [ - offer - ] + assert matches(offer, requirements) class TestOfferDiskFitter: diff --git a/src/tests/_internal/core/backends/gcp/test_compute.py b/src/tests/_internal/core/backends/gcp/test_compute.py index 341df09cc..9f6a161f6 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: