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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
from __future__ import annotations
from functools import cached_property
from typing import Callable
import torch
from .config import Config
from ..util import parse_int_list
from ..util.memory import free_mem
from .model_tp import Model_TPMixin
from .model_ls import Model_LSMixin
from ..util.tensor import g_tensor_cache
from ..cache.recurrent_util import advance_recurrent_states, prepare_for_recurrence
from . import cuda_graph as _cuda_graph
import os
class Model(Model_TPMixin, Model_LSMixin):
def __init__(
self,
config: Config,
**kwargs,
):
super().__init__()
self.config = config
self.modules = []
self.fwd_modules = []
self.caps = {
"supports_tp": True
}
self.active_devices = []
self.output_device = None
self.cache_weakrefs = {}
self._recurrent_state_cls = None
self.draft_verifier_params = {}
# Index of last layer that affects KV cache, used during prefill
self.last_kv_module_idx = None
self.last_kv_module_idx_instance = None
self.logit_layer_idx = None
self.first_block_idx = None
# Calibration options
self.calibration_all_experts = False
# Modules dict
self.modules_dict = None
# Check compatibility
self.check_compat()
def __iter__(self):
for module in self.modules:
yield from module
def find_module(self, key: str):
if self.modules_dict is None:
self.modules_dict = {module.key: module for module in self}
return self.modules_dict[key]
@cached_property
def _get_cache_layers(self):
return [m for m in self if m.caps.get("kv_cache")]
def get_cache_layers(self):
return self._get_cache_layers
@property
def split_active(self) -> bool:
"""True when this model was loaded through a contiguous layer split device map.
A graph must never span the bridge, and a whole-forward graph would. Per-segment
capture comes with the split graphs stage; until then split mode runs eager.
"""
return bool(getattr(self.config, "split_active", False))
@property
def recurrent_state_cls(self):
"""The job state class. A model with no recurrent state of its own (plain attention) whose attention modules declare
a KVWIN ring gets KVWinState: a job state that only carries the rings."""
c = self._recurrent_state_cls
if c is None and self.kvwin_ring_only():
from ..cache.kvwin import KVWinState
return KVWinState
return c
@recurrent_state_cls.setter
def recurrent_state_cls(self, value):
self._recurrent_state_cls = value
def kvwin_ring_only(self) -> bool:
"""True when the only recurrent layers are KVWIN rings (no GDN / SWA / conv state)."""
return self._recurrent_state_cls is None and bool(self._get_recurrent_layers)
@cached_property
def _get_recurrent_layers(self):
return [m for m in self if m.caps.get("recurrent_cache")]
def get_recurrent_layers(self):
return self._get_recurrent_layers
@cached_property
def _get_checkpoint_layers(self):
return [m for m in self._get_recurrent_layers if not getattr(getattr(m, "layer_state_cls", None), "kvwin", False)]
def get_checkpoint_layers(self):
"""Recurrent layers whose state shapes the checkpoint cadence (GDN / KDA / SWA / conv): the recurrent layers without the
KVWIN rings, which ride the job state but are not a state kind. Path eligibility checks (GDN no-tail, big tail, wide
prefill chunks) must see the same layers with the ring declared as without it."""
return self._get_checkpoint_layers
@cached_property
def _get_prefetch_layers(self):
# modules that stage input-dependent data (PLE n-gram rows) on a worker thread before the
# first layers are issued, so the gather overlaps block 0 instead of stalling at its layer
return [m for m in self if m.caps.get("prefetch_ids")]
def get_layer_instances(self, layer_idx):
if not self.config.layer_map:
return [(layer_idx, 0)]
return [
(layer_idx, instance)
for instance in range(self.config.layer_map.count(layer_idx))
]
def num_unmapped_layers(self):
indices = set()
for m in self.modules:
if m.layer_idx is not None:
assert m.layer_idx not in indices
indices.add(m.layer_idx)
assert len(indices) == max(indices) + 1
return len(indices)
def prepare_layer_map(self):
"""
Prepare list of (module, instance_num, original_idx) for mapped layers
"""
# Parse layer map string
if self.config.layer_map is None and self.config.layer_map_str:
self.config.layer_map = parse_int_list(
self.config.layer_map_str,
min_value = 0,
max_value = self.num_unmapped_layers() - 1
)
# No layer map
if not self.config.layer_map:
self.fwd_modules = [(m, 0, idx) for idx, m in enumerate(self.modules)]
self.last_kv_module_idx_instance = (self.last_kv_module_idx, 0)
return
# Isolate and enumerate indexed layers
prolog = []
inner = []
epilog = []
for m in self.modules:
if m.layer_idx is None:
if not inner:
prolog.append(m)
else:
epilog.append(m)
else:
assert len(inner) == m.layer_idx, "Inner layers are not in order"
assert not epilog, "Inner layers are not consecutive"
inner.append(m)
# Compile relayered list
relayered = []
inner_count = [0] * len(inner)
offset = 0
for idx, m in enumerate(prolog):
relayered.append((m, 0, idx + offset))
offset = len(prolog)
for idx in self.config.layer_map:
relayered.append((inner[idx], inner_count[idx], idx + offset))
inner_count[idx] += 1
offset = len(prolog) + len(inner)
for idx, m in enumerate(epilog):
relayered.append((m, 0, idx + offset))
self.fwd_modules = relayered
if self.last_kv_module_idx is not None:
self.last_kv_module_idx_instance = (
self.last_kv_module_idx,
inner_count[self.last_kv_module_idx - len(prolog)] - 1
)
@staticmethod
def from_config(
config: Config,
component: str = "text",
**kwargs
):
"""
Create model instance from config
:param config:
Config created with Config.from_directory()
:param component:
Which component model to load, for models with multiple component.
"""
assert component in config.model_classes, \
f"{config.architecture} does not define a '{component}' component model"
model = config.model_classes[component](config, **kwargs)
model.component = component
# Compile layer map after model is constructed (before any caches are attached)
model.prepare_layer_map()
return model
def prepare_inputs(self, input_ids: torch.Tensor, params: dict) -> torch.Tensor:
# Overridden by model arch class
raise NotImplementedError()
@torch.inference_mode
def prefill(self, input_ids: torch.Tensor, params: dict | None = None):
"""
Run prompt-prefill inference and update cache/recurrent state.
Inputs are first normalized by the architecture-specific prepare_inputs() hook. If the model is loaded in
tensor-parallel mode, execution is dispatched through prefill_tp(), which fans the work out to TP workers
and stops at the last module that affects K/V cache state. Otherwise the layer-split path prefill_ls() runs
directly in the current process. Both paths advance recurrent states after the forward work completes.
"""
if params is None:
params = {}
x = self.prepare_inputs(input_ids, params)
if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
prepare_for_recurrence(input_ids, params, self) # ring-only models: their prepare_inputs does not
if self.loaded_tp:
y = self.prefill_tp(x, params, self.last_kv_module_idx, self.modules)
advance_recurrent_states(input_ids, params, self)
return y
else:
for m in self._get_prefetch_layers:
m.prefetch(x, params)
y = self.prefill_ls(x, params)
advance_recurrent_states(input_ids, params, self)
return y
@torch.inference_mode
def forward(self, input_ids: torch.Tensor, params: dict | None = None):
"""
Run a normal model forward pass for generation or verification.
After architecture-specific input preparation, tensor-parallel models dispatch through forward_tp() so each
worker processes its shard and gathers outputs as needed. Non-TP models use the local layer-split forward
path forward_ls(). Recurrent state advancement is shared between the two modes and runs after the selected
forward path returns.
"""
if params is None:
params = {}
x = self.prepare_inputs(input_ids, params)
if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
prepare_for_recurrence(input_ids, params, self) # ring-only models: their prepare_inputs does not
if self.loaded_tp:
y = self.forward_tp(x, params, self.last_kv_module_idx, self.modules)
advance_recurrent_states(input_ids, params, self)
return y
else:
if _cuda_graph.CUDA_GRAPH_ENABLED and not self.split_active:
# opt-in whole-forward CUDA graph (decode only); None = declined, run eager below
y = _cuda_graph.maybe_forward(self, x, params)
if y is not None:
advance_recurrent_states(input_ids, params, self)
return y
for m in self._get_prefetch_layers:
m.prefetch(x, params)
y = self.forward_ls(x, params)
advance_recurrent_states(input_ids, params, self)
return y
def lag_table(self):
"""Device copy of the token embedding table for the lag-1 pipeline's eager path (None: not possible for this model)."""
t = self.__dict__.get("_lag_tbl", 0)
if t != 0:
return t
self._lag_tbl = None
try:
from ..modules import Embedding, NGramEmbedding
if self.split_active or self.loaded_tp or not torch.cuda.is_available() or self._get_prefetch_layers or getattr(self.config, "moe_cpu_hosts", None):
return None
if any(type(m).__name__ in ("PLE", "PerLayerEmbedding") or isinstance(m, NGramEmbedding) for m in self.modules):
return None
emb, inst0, _ = self.fwd_modules[0]
if not isinstance(emb, Embedding) or emb.embedding is None or emb.normalize or emb.multiplier != 1.0:
return None
w = emb.embedding.weight
if w.dtype not in (torch.half, torch.bfloat16):
return None
dev = self.fwd_modules[1][0].device
if dev is None or torch.device(dev).type != "cuda":
return None
if os.environ.get("EXL3_GPU_EMB", "host") == "0":
return None
if w.device.type == "cpu" and os.environ.get("EXL3_GPU_EMB", "host") == "host":
from .host_table import host_view
wg = host_view(w.detach(), dev)
if wg is None:
return None
probe = torch.arange(0, 8, dtype = torch.long).reshape(1, -1)
ref = emb.forward(probe, {"layer_instance": inst0})
got = wg.index_select(0, probe.to(wg.device).reshape(-1)).view(1, -1, wg.shape[1]).to(ref.dtype)
if got.shape != ref.shape or not torch.equal(got.cpu(), ref.cpu()):
return None
self._lag_tbl = (wg, ref.dtype)
return self._lag_tbl
need = w.numel() * w.element_size() if w.device.type == "cpu" else 0
free, _ = torch.cuda.mem_get_info(dev)
if free < need + (int(os.environ.get("EXL3_GPU_EMB_MARGIN_MB", "1536")) << 20):
return None
probe = torch.arange(0, 8, dtype = torch.long).reshape(1, -1)
ref = emb.forward(probe, {"layer_instance": inst0})
wg = w.detach() if w.device.type == "cuda" else w.detach().to(dev)
got = wg.index_select(0, probe.to(wg.device).reshape(-1)).view(1, -1, wg.shape[1]).to(ref.dtype)
if got.shape != ref.shape or not torch.equal(got.cpu(), ref.cpu()):
return None
if w.device.type == "cpu" and os.environ.get("EXL3_GPU_EMB_DROP", "1") == "1":
emb.embedding.weight = torch.nn.Parameter(wg, requires_grad = w.requires_grad) # single resident copy
self._lag_tbl = (wg, ref.dtype)
except Exception as ex:
print(f"[lag1] no device embedding table: {ex}", flush = True)
self._lag_tbl = None
return self._lag_tbl
@torch.inference_mode
def forward_dev(self, input_ids: torch.Tensor, params: dict):
"""forward() for a decode step whose ids are a device tensor (lag-1 pipeline). CUDA with the whole-forward graph: only the
graph can take them (its GPU embedding table), a decline returns None. Otherwise the eager layers run from a device-side
embedding gather (lag_table). Same arithmetic as forward(): the table rows are the rows Embedding.forward reads."""
if _cuda_graph.CUDA_GRAPH_ENABLED and (not torch.version.hip or _cuda_graph.HIP_GRAPH):
if self.split_active or self.loaded_tp or not torch.cuda.is_available():
return None
x = self.prepare_inputs(input_ids, params)
if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
prepare_for_recurrence(input_ids, params, self)
y = _cuda_graph.maybe_forward(self, x, params)
if y is not None:
advance_recurrent_states(input_ids, params, self)
return y
tbl = self.lag_table()
if tbl is None:
return None
x = self.prepare_inputs(input_ids, params)
if params.get("recurrent_states") is not None and "recurrent_slots" not in params:
prepare_for_recurrence(input_ids, params, self)
wg, dt = tbl
params["input_ids"] = input_ids
x = wg.index_select(0, input_ids.reshape(-1)).view(*input_ids.shape, wg.shape[1]).to(dt)
y = self.forward_ls(x, params, skip_first = True)
advance_recurrent_states(input_ids, params, self)
return y
def unload(self):
_cuda_graph.purge(self)
for module in self.modules:
module.unload()
# The loader's open slab blocks must not outlive the tensors sliced from them
self.config.stc.release_arena()
self.active_devices = []
self.unload_tp()
self.output_device = None
# Attached caches lose their layer tensors with the modules that allocated them
for ref in self.cache_weakrefs.values():
cache = ref()
if cache is not None:
cache.initialized = False
def load_gen(
self,
device: torch.device | str | int | None = None,
tp_output_device: torch.device | str | int | None = None,
reserve_per_device: list[float] | float | None = None,
use_per_device: list[float] | float | None = None,
device_map = None,
tensor_p: bool = False,
progressbar: bool = False,
max_chunk_size: int = 2048,
max_output_size: int = 32,
max_output_factor: int = 1,
callback: Callable[[int, int], None] | None = None,
generator: bool = True,
tp_dev_limits: dict | None = None,
tp_backend: str = "native",
verbose: bool = False,
max_batch_size: int = 1,
tp_options: dict | None = None,
autosplit_no_forward: bool = False,
):
"""
Load model, generator function. For regular function, call load() with the same arguments
:param device:
(optional) If specified, load to single device, e.g. "cuda:0"
:param device_map:
(optional) LayerDeviceMap from exllamav3.device_map. Assigns each top-level
module to a device (contiguous front layers plus optional endcaps) and streams
weights directly there. The caller releases the map's memory budget after the
last component (target, drafter, vision) has loaded.
:param tp_output_device:
(optional) If loading with tensor_p == True, device on which to gather output logits. Must be one of
the active devices in the split. Default is first device in split
:param reserve_per_device:
(optional) Amount of memory to reserve for any device. Either a value in GB to apply on all devices
or a list of floats giving an individual reserve per device. Negative reserve excludes device from
split. E.g.:
# reserve 4.5 GB on cuda:0, 1 GB on each cuda:1 and on cuda:2
model.load(reserve_per_device = [4.5, 1, 1])
# reserve 1 GB on cuda:0 and cuda:2, exclude cuda:1
model.load(reserve_per_device = [1, -1, 1])
The default reserve per device is 0.5 GB. This applies to devices not included in reserve_per_device
as well.
:param use_per_device:
(optional) Amount of memory to use per device.
Does not account for memory allocated by other processes or by the calling process up to the call
to model.load(), i.e. if cuda:0 currently has 3 GB in use and user_per_device = [12, ...], at the
end of loading cuda:0 will have up to 15 GB of VRAM allocated, using up to 15 GB during a forward
pass.
Devices not included in use_per_device, or included with a value of 0, will not be used, e.g.:
# use up to 23 GB on cuda:0 and cuda:2, do not load on cuda:1 and cuda:3 (if present)
model.load(use_per_device = [23, 0, 23])
:param tensor_p:
Load in tensor-parallel mode. By default, attempt to split model according to available VRAM.
Allocation can be overridden with use_per_device or modified by reserve_per_device.
:param max_chunk_size:
The maximum number of tokens to expect in a single forward pass. Informs the layer split only, and
makes no difference when loading on a single device.
:param max_output_size:
The maximum number of output tokens to expect in a single forward pass. Informs the estimate of the
size of the output logits. Values larger than max_chunk_size have no effect.
:param max_output_factor:
When estimating the memory footprint of the output layer, scale the size of the output tensor by
this factor. For instance, if the first thing you wish to do with a float16 output tensor is upcast
to float32, a value of 3 here would (attempt to) make sure the output layer always ends up on a
device where there is enough space for that.
:param progressbar:
Show rich progressbar while loading
:param callback:
If provided, called with (current_module, num_modules) for every module loaded. Don't specify a
callback function when using the
:param generator:
Always true when using the _gen function directly
:param tp_dev_limits:
(optional, TP only) Dictionary of module categories and max parallelism for each. Categories are
"mlp", "attn", "moe", "linear" (i.e. output layer). Example:
tp_dev_limits = {
"attn": 2, # Each attn layer uses at most two devices for tensor parallelism
"moe": 3, # etc.
}
:param tp_backend:
str, either "nccl" (default) or "native"
:param verbose:
bool, more info while loading including full TP split
:param max_batch_size:
Max batch size to account for when loading in autosplit mode (default: 1)
:param tp_options:
dict of optional values:
"moe_tensor_split": bool - use tensor split rather than expert parallelism for MoE layers
:param autosplit_no_forward:
For debug purposes, skip reference forward pass during autosplit load.
"""
free_mem()
# Route CPU-offloaded MoE layers to this component's own worker and budget (an MTP head
# shares the config but loads after the main model's worker has already started)
self.config.infer_params.moe_cpu_component = getattr(self, "component", "text")
assert not (bool(reserve_per_device) and bool(use_per_device)), \
"Cannot specify both memory usage and memory reserve."
assert max_chunk_size >= 1, "max_chunk_size must be positive"
assert max_output_size >= 1, "max_output_size must be positive"
assert max_output_factor >= 1, "max_output_factor must be positive"
# Explicit contiguous layer split. The map owns the per-device budget; the
# caller releases it after the last component (target/drafter/vision).
if device_map is not None:
assert device is None and not reserve_per_device and not use_per_device, \
"device_map cannot be combined with device/reserve_per_device/use_per_device."
assert not tensor_p, "device_map cannot be combined with tensor_p."
assert not os.environ.get("EXL3_LOAD_SPLIT"), \
"device_map cannot be combined with the legacy EXL3_LOAD_SPLIT budget"
self._load_mapped(progressbar, device_map, self.config, self.modules, verbose,
callback, max_chunk_size)
self.output_device = self.modules[-1].device
# Load to single device
elif device is not None:
assert not bool(reserve_per_device) and not bool(use_per_device), \
"Cannot specify reserve_per_device or use_per_device when loading to single device."
assert not tensor_p, \
"Cannot use tensor_p when loading to single device."
self._load_single(progressbar, device, self.config, self.modules, verbose, callback)
self.output_device = self.modules[-1].device
# Use/reserve
else:
rpd = reserve_per_device is not None
upd = use_per_device is not None
assert not (rpd and upd), \
"Cannot specify both reserve_per_device or use_per_device."
num_devices = torch.cuda.device_count()
if not upd:
if reserve_per_device is None:
reserve_per_device = [0.5] * num_devices
elif any(isinstance(reserve_per_device, t) for t in [float, int]):
reserve_per_device = [reserve_per_device] * num_devices
elif not isinstance(reserve_per_device, list):
raise ValueError("reserve_per_device must be float or list[float]")
while len(reserve_per_device) < num_devices:
reserve_per_device.append(0.5)
reserve_per_device = [int(x * 1024**3) for x in reserve_per_device]
active_devices = [
i for i in range(num_devices)
if i >= len(reserve_per_device) or reserve_per_device[i] >= 0
]
if upd:
if any(isinstance(use_per_device, t) for t in [float, int]):
use_per_device = [use_per_device] * num_devices
elif not isinstance(use_per_device, list):
raise ValueError("use_per_device must be float or list[float]")
use_per_device = [int(x * 1024**3) for x in use_per_device]
active_devices = [
i for i, x in enumerate(use_per_device)
if x > 0
]
# Split load
if not tensor_p:
yield from self._load_autosplit(
progressbar,
reserve_per_device,
use_per_device,
active_devices,
max_chunk_size,
max_output_size,
max_output_factor,
callback,
generator,
self.config,
self.modules,
verbose,
max_batch_size,
self.cache_weakrefs,
autosplit_no_forward,
)
self.output_device = self.modules[-1].device
# Tensor-P load:
else:
if not self.caps.get("supports_tp"):
raise NotImplementedError(f"Tensor-parallel is not currently implemented for {self.config.architecture}")
if self.config.layer_map:
raise NotImplementedError(f"Tensor-parallel is not currently implemented for relayered models.")
if tp_output_device is None:
tp_output_device = active_devices[0]
else:
assert torch.device(tp_output_device).index in active_devices, \
"Output device must be part of split."
if tp_options is None:
tp_options = {}
yield from self._load_tp(
progressbar,
reserve_per_device,
use_per_device,
active_devices,
max_chunk_size,
max_output_size,
max_output_factor,
callback,
generator,
tp_output_device,
self.config,
self.modules,
tp_dev_limits,
tp_backend,
verbose,
tp_options,
)
self.output_device = tp_output_device
free_mem()
# Drop the shards' clean pages from the OS page cache. On a unified-memory host (GB10)
# the page cache and the model weights are the *same* physical pool, so after an 87 GiB
# load the box is carrying that 87 GiB twice and torch.cuda.mem_get_info() -- which
# reports MemFree, not MemAvailable -- cannot see it. See
# SafetensorsCollection.drop_page_cache(). EXL3_KEEP_PAGE_CACHE=1 disables.
if os.environ.get("EXL3_KEEP_PAGE_CACHE", "0") != "1":
try:
n = self.config.stc.drop_page_cache()
if verbose and n:
print(f" -- Released {n / 1024 ** 3:.1f} GiB of shard page cache")
except Exception as e:
print(f" !! Could not drop shard page cache: {e}")
# Release all global shared tensors (refs still held by modules until model is unloaded)
g_tensor_cache.drop_all()
# Tiered experts (EXL3_EXPERT_BUDGET_GIB): the layers only registered their experts while loading; allocate
# the slot pools now, after the cache and every other allocation of the load
_st = getattr(self.config, "_expert_store", None)
if _st is not None:
_st.finalize()
# Mark every attached cache usable.
for ref in self.cache_weakrefs.values():
cache = ref()
if cache is not None:
cache.initialized = True
@torch.inference_mode
def load(self, *args, **kwargs):
"""
Load as a regular function, see arguments for load_gen().
"""
kwargs["generator"] = False
f = self.load_gen(*args, **kwargs)
for _ in f: pass
try:
from ..modules import moe_fused
moe_fused.report(self)
except Exception as e: # noqa: BLE001 (diagnostics must never break a load)
import sys
print(f"[moe_fused] WARNING fused-status report failed: {e!r}", file = sys.stderr)
# CPU-offloaded MoE experts: make sure the worker processes are up before the first
# forward (spawned during module loading when the offload count is exact, so the child's
# weight loading overlaps the parent's; started here otherwise). ensure_started is
# idempotent, so already-running workers of other components are unaffected
for host in getattr(self.config, "moe_cpu_hosts", {}).values():
host.ensure_started()
def get_load_metrics(self):
return self.config.stc.get_metrics()
def get_layout_tree(self, pre_indent: int) -> str:
def get_branch(module, b_indent) -> str:
nonlocal pre_indent
lines = [get_branch(m, b_indent + 4) for m in module.modules]
dedup_lines = []
count = 1
for i in range(len(lines)):
if i < len(lines) - 1 and lines[i] == lines[i + 1]:
count += 1
else:
pref = ""
if count > 1:
pref = f"[{count}x] "
count = 1
dedup_lines.append(lines[i].replace("[]", pref))
r = " " * (pre_indent + b_indent) + " - []" + module.get_name() + "\n"
r += "".join(dedup_lines)
return r
def compact_rle(s: list[str]) -> list[tuple[int, list[str]]]:
n = len(s)
if n == 0:
return []
dp = [(0, None)] + [(float('inf'), None)] * n
for i in range(1, n + 1):
for j in range(i - 1, -1, -1):
seg = s[j:i]
seg_len = len(seg)
p = _smallest_period(seg)
if p is not None:
k = seg_len // p
cost = dp[j][0] + p
if cost < dp[i][0]:
dp[i] = (cost, (j, k, s[j:j + p]))
result = []
pos = n
while pos > 0:
_, (j, k, pattern) = dp[pos]
result.append((k, pattern))
pos = j
result.reverse()
return result
def _smallest_period(seg: list[str]) -> int | None:
n = len(seg)
for p in range(1, n + 1):
if n % p == 0 and all(seg[i] == seg[i % p] for i in range(p, n)):
return p
return None
br = get_branch(self, 0).replace("[]", "").rstrip()
br = br.split("\n")
cbr = compact_rle(br)
br = []
for num, span in cbr:
if num == 1:
br += span
else:
br += [" " * span[0].index("- ") + f"- [{num}x]"]
br += [" " + s for s in span]
return "\n".join(br)
def get_storage_info(self):
from ..modules import Linear
def get_tensor_size(tensors):
return 8 * sum(t.element_size() * t.numel() for t in tensors.values())
sum_bits = 0
sum_numel = 0
head_bpw = 0
head_numel = 0
for module in self:
if module.key.endswith("lm_head"):
if module.device is not None:
head_bpw = get_tensor_size(module.get_tensors()) / module.weights_numel()
else:
head_bpw = sum(self.config.stc.get_tensor_sizes(module.key)) / module.weights_numel() * 8
head_numel = module.weights_numel()
elif isinstance(module, Linear):
if module.device is not None:
sum_bits += get_tensor_size(module.get_tensors())
else:
sum_bits += sum(self.config.stc.get_tensor_sizes(module.key)) * 8
sum_numel += module.weights_numel()
vram_bits = head_numel * head_bpw + sum_bits
return sum_bits / sum_numel, head_bpw, vram_bits
def get_name(self):
return self.__class__.__name__
@staticmethod
def get_additional_compiled_tensors(config: Config):
return {}
def default_chat_prompt(self, prompt: str, system_prompt: str = None) -> str:
"""
Convenience function for formatting a single chat request with the default template associated with the
model's architecture, to simplify example and test scripts. Doesn't consider the model's actual Jinja template.
"""
raise NotImplementedError()
def batch_recurrent_states(self):
raise NotImplementedError()
def check_compat(self):
"""
Decide if any model-specific requirements are met when creating Model
"""
pass