Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

23.4 KB
Raw Blame
from __future__ import annotations
from typing import Callable
import os
import time
import torch

from ..modules.attn import prepare_for_attn
from ..modules.module import select_exec_device
from ..cache.recurrent_util import prepare_for_recurrence
from ..util.memory import (
    set_memory_fraction_reserve,
    set_memory_fraction_use,
    unset_memory_fraction,
    free_mem,
)
from ..util.progress import ProgressBar
from .config import Config
from abc import ABC, abstractmethod


class Model_LSMixin(ABC):

    def __init__(self):
        pass


    @abstractmethod
    def get_layer_instances(self, layer_idx) -> tuple:
        ...


    def _load_single(
        self,
        progressbar: bool,
        device: torch.device,
        config: Config,
        modules: list,
        verbose: bool,
        callback = None
    ):
        pin = config.infer_params.vision_pinned and getattr(self, "component", "text") == "vision"
        with ProgressBar(f"Loading" if progressbar else None, len(modules)) as progress:
            for idx, module in enumerate(modules):
                if callback: callback(idx, len(modules))
                defer = module.can_defer_load()
                if defer:
                    # Pinned modules leave the arena alone: their slab slices would keep whole
                    # blocks resident after the weights move to host memory
                    config.stc.begin_deferred_load(arena = not pin)
                module.load(torch.device("cpu") if module.caps.get("prefer_cpu") else device)
                if defer:
                    config.stc.end_deferred_load()
                if pin:
                    # After the deferred fills have landed: linear weights move to pinned host
                    # memory (zero-copy aliases), everything else stays put
                    module.pin_linears()
                for h in getattr(config, "moe_cpu_hosts", {}).values():
                    h.commit_module(module.key)
                progress.update(idx + 1)


    def default_load_shape_dtype(self, chunk_size):
        return (1, chunk_size), torch.long


    def default_load_params(self, chunk_size):
        return {"input_ids": torch.zeros((1, chunk_size), dtype = torch.long)}


    def _load_mapped(
        self,
        progressbar: bool,
        device_map,
        config: Config,
        modules: list,
        verbose: bool,
        callback = None,
        max_chunk_size: int = 2048,
    ):
        """Load every top-level module straight to the device the map assigns it.

        No autosplit measuring forwards: the boundary is explicit. The part0 reserve is a
        held device slab while its segment loads, then is dropped at the first part1 module
        (the freed block stays available to the workspace without changing the allocator's
        policy or the part1 segment's numerics). The caller releases whatever remains after
        the last component.
        """
        device_map.engage_budget()
        pin_all = config.infer_params.vision_pinned and getattr(self, "component", "text") == "vision"
        part0_released = not device_map.enabled
        with ProgressBar(f"Loading (split)" if progressbar else None, len(modules)) as progress:
            for idx, module in enumerate(modules):
                if callback: callback(idx, len(modules))
                dev = device_map.device_for(module)
                if not part0_released and dev == device_map.part1:
                    device_map.release_part0_budget()
                    part0_released = True
                defer = module.can_defer_load()
                if defer:
                    # Pinned modules leave the arena alone (see _load_single)
                    config.stc.begin_deferred_load(arena = not pin_all)
                module.load(dev, max_chunk_size = max_chunk_size)
                if defer:
                    config.stc.end_deferred_load()
                if pin_all:
                    module.pin_linears()
                for h in getattr(config, "moe_cpu_hosts", {}).values():
                    h.commit_module(module.key)
                progress.update(idx + 1)
            if callback: callback(len(modules), len(modules))
        config.stc.close()
        self.active_devices = [d.index for d in device_map.used_devices if d.type == "cuda"]
        self.output_device = modules[-1].device

        # The config reaches the drafter and the vision tower too: one bridge (and the
        # split-active marker that defuses graph capture) covers every component that
        # shares it.
        if device_map.enabled:
            from ..bridge import install_bridge
            bridge = install_bridge(config, part1 = device_map.part1, part0 = device_map.part0)
            if bridge is not None and verbose:
                print(f" -- split: {bridge.describe()}")


    def _load_autosplit(
        self,
        progressbar: bool,
        reserve_per_device: list[int] | None,
        use_per_device: list[int] | None,
        active_devices: list[int],
        max_chunk_size: int,
        max_output_size: int,
        max_output_factor: int,
        callback_sync: Callable[[int, int], None],
        generator: bool,
        config: Config,
        modules: list,
        verbose: bool,
        max_batch_size: int,
        cache_weakrefs: dict,
        autosplit_no_forward: bool,
    ):
        current_device_i = 0
        backup_shape, backup_dtype = self.default_load_shape_dtype(max_chunk_size)
        dummy_state = None
        prev_load_device = None
        touched_devices = []
        params = self.default_load_params(max_chunk_size)
        # The measuring forwards below exist to observe VRAM allocation; modules with CPU-side
        # compute (CPU-offloaded experts) can skip the host work when they see this flag
        params["autosplit_measure"] = True

        # Simulate cached/recurrent path while loading with cache
        cl = [m for m in self if m.caps.get("kv_cache")]
        if cl:
            c0 = cl[0].cache_layers[0] if len(cl[0].cache_layers) else None
            if c0:
                cache = cache_weakrefs[c0.cache_id]()
                params.update({
                    "attn_mode": "flash_attn",
                    "cache": cache,
                    "past_len": 0,
                    "batch_shape": (1, max_chunk_size),
                })
                prepare_for_attn(torch.zeros((1, max_chunk_size), dtype = torch.long), params)
                rl = self.get_recurrent_layers()   # not the raw caps: a KVWIN ring declared by a model without recurrent state slots does not count
                if rl:
                    prepare_for_recurrence(None, params, self)

        recurrent_states = params.get("recurrent_states")

        # Per device: the budget the memory fraction enforces, and the largest transient any
        # measuring forward has needed there. A module's forward only proves that ITS transient
        # still fits; every module already on the device needs its own at runtime, so a device
        # is closed when its remaining headroom no longer covers the largest one seen
        device_budget = {}
        max_transient = {}
        # Physical margin on top of the largest measured transient: the measure is per module,
        # while a real forward also carries what the caller keeps live around it (recurrent
        # test states, gathered embeddings, allocator slack), so a device packed to exactly one
        # transient of headroom fails on the first real chunk
        autosplit_margin = int(os.environ.get("EXL3_AUTOSPLIT_MARGIN_MB", 256)) << 20

        with ProgressBar(f"Loading (LS)" if progressbar else None, len(modules)) as progress:

            for idx, module in enumerate(modules):

                if callback_sync: callback_sync(idx, len(modules))
                if generator: yield idx, len(modules)

                # Narrow state to max_output_size for logit output layer. When a live dummy state
                # exists, refresh the backup from it: backup_shape still holds the state that
                # ENTERED the previous module, which can have a different rank (e.g. a
                # hyper-connection stream stack ahead of a final mixer)
                is_logits_layer = module.caps.get("logits_output")
                if is_logits_layer and not autosplit_no_forward:
                    if dummy_state is not None:
                        dummy_state = dummy_state[:, :max_output_size]
                        backup_shape = dummy_state.shape
                        backup_dtype = dummy_state.dtype
                    else:
                        b, c, *rest = backup_shape
                        backup_shape = (b, min(max_output_size, c), *rest)

                while True:
                    try:
                        # Select device
                        load_device = torch.device("cpu") if module.caps.get("prefer_cpu") else \
                            torch.device(active_devices[current_device_i])
                        x_device = torch.device("cpu") if module.caps.get("prefer_cpu") or module.caps.get("x_cpu") else \
                            torch.device(active_devices[current_device_i])

                        # Set VRAM limit if new device
                        if load_device != torch.device("cpu") and load_device != prev_load_device:
                            prev_load_device = load_device
                            i = active_devices[current_device_i]
                            touched_devices.append(i)
                            i = active_devices[current_device_i]
                            if reserve_per_device is not None:
                                device_budget[i] = set_memory_fraction_reserve(reserve_per_device[i], i)
                            elif use_per_device is not None:
                                device_budget[i] = set_memory_fraction_use(use_per_device[i], i)
                            else:
                                raise RuntimeError("Logic error")

                        # (Re)create or backup hidden state (metadata)
                        if dummy_state is None:
                            dummy_state = torch.zeros(backup_shape, dtype = backup_dtype, device = x_device)
                        else:
                            backup_shape = dummy_state.shape
                            backup_dtype = dummy_state.dtype

                        # Load module
                        defer = module.can_defer_load()
                        pin = config.infer_params.vision_pinned and \
                            getattr(self, "component", "text") == "vision"
                        if defer:
                            # Pinned modules leave the arena alone (see _load_single)
                            config.stc.begin_deferred_load(arena = not pin)
                        module.load(load_device, max_chunk_size = max_chunk_size)
                        if defer:
                            config.stc.end_deferred_load()
                        if pin:
                            # Before the measuring forward, so the VRAM accounting reflects the
                            # pinned (host-resident) weights
                            module.pin_linears()

                        # Forward dummy state through module. The forward runs the real cached
                        # attention path, so any dequant temporaries a quantized cache layer
                        # still needs are allocated (and accounted) here
                        if self.caps.get("autosplit_load_fwd", True) and not autosplit_no_forward:
                            measure = load_device.type == "cuda"
                            if measure:
                                torch.cuda.reset_peak_memory_stats(load_device)
                                alloc_before = torch.cuda.memory_allocated(load_device)
                            select_exec_device(module.device)
                            dummy_state = module.prepare_for_device(dummy_state, params)
                            dummy_state = module.forward(dummy_state, params)
                            for sm in module:
                                sm.autosplit_extra_measure(params)
                            if measure:
                                i = load_device.index
                                transient = max(0, torch.cuda.max_memory_allocated(load_device) - alloc_before)
                                # print(f"{module.key}: {transient,:}")

                                max_transient[i] = max(max_transient.get(i, 0), transient)
                                # Models with mixed layer type and dramatically different transient memory requirements
                                # per layer break the assumption that if layer n fits and subsequently layer n+1 also
                                # fits, then layer n will continue to work even with the weights of layer n+1 loaded
                                if torch.cuda.memory_allocated(load_device) + max_transient[i] > device_budget[i]:
                                    raise torch.cuda.OutOfMemoryError(
                                        f"autosplit: cuda:{i} has no headroom left for the largest "
                                        f"transient measured on it ({max_transient[i] >> 20} MiB)"
                                    )
                                # The same check against the device itself: a split budget at or
                                # above the card's size plans against VRAM the CUDA context, the
                                # loaded kernels and other processes hold (several hundred MiB),
                                # and a load that passes the budget check then fails on the first
                                # real forward. What the largest transient can still draw on is the
                                # free device memory plus the allocator's reserved-but-unallocated
                                # pool
                                free_now, _ = torch.cuda.mem_get_info(load_device)
                                reusable = free_now + torch.cuda.memory_reserved(load_device) - \
                                    torch.cuda.memory_allocated(load_device)
                                if reusable < max_transient[i] + autosplit_margin:
                                    raise torch.cuda.OutOfMemoryError(
                                        f"autosplit: cuda:{i} has {reusable >> 20} MiB of physical headroom "
                                        f"left, below the largest transient measured on it "
                                        f"({max_transient[i] >> 20} MiB) plus the {autosplit_margin >> 20} MiB "
                                        f"margin (EXL3_AUTOSPLIT_MARGIN_MB)"
                                    )

                        if os.environ.get("EXL3_LOAD_DIAG") and load_device.type == "cuda":
                            print(f"[loaddiag] {idx:3d} {module.key:48s} alloc {torch.cuda.memory_allocated(load_device)/2**30:7.3f}G "
                                  f"reserved {torch.cuda.memory_reserved(load_device)/2**30:7.3f}G peak {torch.cuda.max_memory_allocated(load_device)/2**30:7.3f}G", flush=True)
                        # Account for max_output_factor after last layer
                        extra_dummy_out_states = None
                        if is_logits_layer:
                            extra_dummy_out_states = [
                                torch.empty_like(dummy_state)
                                for _ in range(max_output_factor - 1)
                            ]

                        # Dereference extra dummy tensors
                        extra_dummy_out_states = None

                        # We're good. For CPU-offloaded MoE layers, wait for the worker process
                        # to finish loading this module's expert weights before advancing, so
                        # load progress stays honest and rollbacks can't outrun the child
                        for h in getattr(config, "moe_cpu_hosts", {}).values():
                            h.commit_module(module.key)
                        fail = False
                        progress.update(idx + 1)

                    # We're not good
                    except Exception as e:
                        config.stc.abort_deferred_load()
                        if e.__class__.__name__ == "OutOfMemoryError" or \
                            "CUDA out of memory" in str(e) or \
                            "HIP out of memory" in str(e):
                            # Exception object will hold references to tensors so we can't free them here
                            fail = True
                            if os.environ.get("EXL3_LOAD_DIAG"):
                                import gc, collections
                                agg = collections.defaultdict(lambda: [0, 0]); seen = set()
                                for o in gc.get_objects():
                                    try:
                                        if isinstance(o, torch.Tensor) and o.is_cuda:
                                            ptr = o.untyped_storage().data_ptr()
                                            if ptr in seen: continue
                                            seen.add(ptr)
                                            a = agg[(str(o.dtype), tuple(o.shape))]; a[0] += 1; a[1] += o.untyped_storage().nbytes()
                                    except Exception: pass
                                print(f"[loaddiag] OOM at {module.key}: live CUDA storages {sum(v[1] for v in agg.values())/2**30:.3f} GiB, allocated {torch.cuda.memory_allocated()/2**30:.3f}", flush=True)
                                for k, v in sorted(agg.items(), key=lambda kv: -kv[1][1])[:25]:
                                    print(f"[loaddiag]   {v[1]/2**20:10.1f} MiB  n={v[0]:5d}  {k[0]} {k[1]}", flush=True)
                        else:
                            raise

                    # Module failed to load with an OoM error, so advance to the next device if possible
                    if fail:
                        module.unload()
                        dummy_state = None
                        if "recurrent_states" in params:
                            for rs in params["recurrent_states"]:
                                rs.reset()

                        free_mem()
                        current_device_i += 1
                        if current_device_i >= len(active_devices):
                            raise RuntimeError("Insufficient VRAM in split for model and cache")
                        continue

                    # On to next module
                    break

            if callback_sync: callback_sync(len(modules), len(modules))
            if generator: yield len(modules), len(modules)

            dummy_state = None
            unset_memory_fraction(touched_devices)

        if recurrent_states is not None:
            for rs in recurrent_states:
                rs.free()

        config.stc.close()
        self.active_devices = active_devices

        # Python will not run anything in an async function without at least one yield statement
        if 'yield' in locals():
            yield


    def _name_embedding_target(self, x: torch.Tensor, params: dict):
        """A long chunk of token ids headed for a CPU-resident embedding: tell it the device of the module that consumes its output
        (Embedding.forward then uploads the rows pinned and asynchronously, see EXL3_PF_EMB_UPLOAD)."""
        if x.device.type == "cpu" and x.numel() >= 1024 and len(self.fwd_modules) > 1:
            dev = self.fwd_modules[1][0].device
            if dev is not None and torch.device(dev).type == "cuda":
                params["emb_next_device"] = dev


    def prefill_ls(
        self,
        x: torch.Tensor,
        params: dict,
    ):
        for h in getattr(self.config, "moe_cpu_hosts", {}).values():
            h.begin_pass()
        self._name_embedding_target(x, params)
        for module, instance, idx in self.fwd_modules:
            params["layer_instance"] = instance
            pf = (idx, instance) == self.last_kv_module_idx_instance
            params["prefill"] = pf
            select_exec_device(module.device)
            x = module.prepare_for_device(x, params)
            x = module.forward(x, params)
            if x is None:
                # EXL3_PF_SKIP: kv_only -- the last cache-writing module stopped after its K/V
                # write, so there is no state left to carry into the tail modules
                break
            if pf:
                break
        del params["prefill"]
        return None


    def forward_ls(
        self,
        x: torch.Tensor,
        params: dict,
        skip_first: bool = False,
    ):
        for h in getattr(self.config, "moe_cpu_hosts", {}).values():
            h.begin_pass()
        self._name_embedding_target(x, params)
        span = _FWD_SPAN and x.dim() >= 3 and x.shape[1] <= 8   # (batch, rows, ..): decode/verify only, not prefill chunks
        for module, instance, idx in (self.fwd_modules[1:] if skip_first else self.fwd_modules):
            params["layer_instance"] = instance
            if module.caps.get("logits_output"):
                # EXL3_PF_SKIP: skip_logits -- the caller discards the logits (the MTP prompt
                # prefill only needs the exported hidden states), so stop before the head
                if params.get("skip_logits"):
                    break
                if (num := params.get("last_tokens_only")):
                    x = x[..., -num:, :].contiguous()
            if span:
                x = _span_module(module, x, params)
                continue
            select_exec_device(module.device)
            x = module.prepare_for_device(x, params)
            x = module.forward(x, params)
        return x


# EXL3_FWD_SPAN=1 (diagnostic, off by default): decode/verify forwards (<= 8 rows) time every module with a
# device sync on both sides and print the ones over EXL3_FWD_SPAN_MS (default 150). A sampler thread dumps the
# main thread's Python stack every 250 ms once a module has run past 400 ms, naming the op of a one-time stall.
_FWD_SPAN = os.environ.get("EXL3_FWD_SPAN") == "1"
_FWD_SPAN_MS = float(os.environ.get("EXL3_FWD_SPAN_MS", "150"))
_span_state = {"t0": None, "name": "", "main": None}


def _span_sampler():
    import sys, traceback
    last = None
    while True:
        time.sleep(0.25)
        t0 = _span_state["t0"]
        if t0 is None or time.perf_counter() - t0 < 0.4:
            continue
        fr = sys._current_frames().get(_span_state["main"])
        if fr is None:
            continue
        st = traceback.extract_stack(fr)[-14:]
        key = (t0, tuple((f.filename, f.lineno) for f in st))
        if key == last:
            continue
        last = key
        print(f"span-stack: {_span_state['name']} +{(time.perf_counter() - t0) * 1e3:.0f} ms", flush=True)
        for f in st:
            print(f"span-stack:    {f.filename.split('/')[-1]}:{f.lineno} {f.name}: {(f.line or '')[:100]}", flush=True)


def _span_module(module, x, params):
    import threading
    if _span_state["main"] is None:
        _span_state["main"] = threading.get_ident()
        threading.Thread(target = _span_sampler, daemon = True).start()
    torch.cuda.synchronize()
    _span_state["name"] = f"{module.key}[{params.get('layer_instance')}]"
    t0 = _span_state["t0"] = time.perf_counter()
    select_exec_device(module.device)
    x = module.prepare_for_device(x, params)
    x = module.forward(x, params)
    torch.cuda.synchronize()
    ms = (time.perf_counter() - t0) * 1e3
    _span_state["t0"] = None
    if ms >= _FWD_SPAN_MS:
        print(f"span: {_span_state['name']} {type(module).__name__} {ms:.1f} ms rows={x.shape[1] if x.dim() > 2 else 0}", flush=True)
    return x