Skip to content
Merged
5 changes: 3 additions & 2 deletions src/dstack/_internal/core/backends/base/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
238 changes: 146 additions & 92 deletions src/dstack/_internal/core/backends/base/offers.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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(
Expand All @@ -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).
Expand All @@ -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)
Expand All @@ -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")


Expand Down
15 changes: 5 additions & 10 deletions src/dstack/_internal/core/backends/gcp/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
Loading
Loading