Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ignition/components/engram.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import triton.language as tl
from b12x.preparation import PreparedCall
from b12x.sequence import engram
from b12x.sequence.engram._kernels import hash_op, lookup_op
from b12x.sequence.engram import hash_op, lookup_op

from ignition.components.ngram_delivery import publish_advisory_requests, publish_requests
from ignition.components.readiness import PreparedReadinessWait, ReadinessTimings, wait_for_readiness
Expand Down
8 changes: 4 additions & 4 deletions ignition/preparation/collectives.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def _tuning_results(contributions):


def _selected_plan_catalog(requests):
from b12x.preparation.types import _CompositePlan
from b12x.preparation import is_composite_plan, plan_variants
from .tuning_shards import portable_declaration

by_name = {request.name: request for request in requests}
Expand All @@ -210,8 +210,8 @@ def identity(name):
entries = []

def selected(plan, key):
if isinstance(plan, _CompositePlan):
for count, child in plan.variants.items():
if is_composite_plan(plan):
for count, child in plan_variants(plan).items():
selected(child, (key, count))
else:
config = plan.selection.config
Expand Down Expand Up @@ -369,7 +369,7 @@ def share_selections(self, cache):
# The session's agreed records, which b12x's own cross-rank reconciliation sets, take
# precedence over the rank's file. Saving a newly tuned key reloads that file, so
# replacing only the loaded records would restore the rank's own choices.
cache._agreed_records = dict(records[0])
cache.set_agreed_records(records[0])

def agree_selections(self, selections):
"""Fail before compilation when ranks selected different kernels for the same request."""
Expand Down
22 changes: 13 additions & 9 deletions ignition/preparation/composition_tuning.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,17 @@

from b12x.preparation import (
CollectiveRequirement, FrozenMapping, Knob, MemoryRequirements,
PersistentMemory, Plan, PreparationSession, PreparedCall, TuningContract,
PersistentMemory, PreparationSession, PreparedCall, TuningContract,
custom_plan, is_composite_plan, plan_variants,
)


def plan_identity(plan):
"""Describe selected programs and their invocation without live resource handles."""
from b12x.preparation.types import _CompositePlan

if isinstance(plan, _CompositePlan):
if is_composite_plan(plan):
return dict(component=plan.component_id, version=plan.composite_semantic_version,
capacity=plan.capacity_metadata,
variants=tuple((count, plan_identity(child)) for count, child in plan.variants.items()))
variants=tuple((count, plan_identity(child)) for count, child in plan_variants(plan).items()))
if plan.selection is None or plan.prepared is None:
raise ValueError("composition identity requires prepared child plans")
contract, selection = plan.contract, plan.selection
Expand Down Expand Up @@ -169,10 +168,15 @@ def race_compositions(candidates, *, operation, geometry, numerics, workload, de
catalog={name: candidate.identity() for name, candidate in candidates.items()}))
borrowed = MemoryRequirements(persistent=(PersistentMemory(
("prepared-compositions", id(candidates)), resident_bytes, resident_bytes),))
plan = Plan(contract=_CONTRACT, query=query, _device=f"cuda:{session.device.ordinal}",
_compile_jobs=lambda config, device: (), _memory_requirements=lambda config, device: borrowed,
_materialize=lambda selection, device: candidates[selection.config["implementation"]],
_benchmark_call=lambda candidate: candidate.prepared_call())
plan = custom_plan(
contract=_CONTRACT,
query=query,
device=f"cuda:{session.device.ordinal}",
compile_jobs=lambda config, device: (),
memory_requirements=lambda config, device: borrowed,
materialize=lambda selection, device: candidates[selection.config["implementation"]],
benchmark_call=lambda candidate: candidate.prepared_call(),
)
request = plan.request(name=operation, prepare_call=lambda candidate: candidate.prepared_call(),
collective=CollectiveRequirement(operation, coordinator.ranks))
scope = (composition_race_session(session, coordinator=coordinator, cache_policy=cache_policy)
Expand Down
6 changes: 3 additions & 3 deletions ignition/preparation/core_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ def host_allocate(self, name, shape, dtype):
def device_allocate(self, name, shape, dtype, *, group, maximum, units=None):
"""Map a prefix of a stable virtual range for runtime-sized storage."""
import torch
from b12x.sequence._shared.disk_table import _tensor_from_pointer
from b12x.sequence import tensor_from_pointer as _tensor_from_pointer

units = shape[0] if units is None else units
unit_bytes = math.prod(shape[1:]) * dtype.itemsize
Expand Down Expand Up @@ -433,7 +433,7 @@ def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False):
"""`lock`, for a unified-memory GPU, keeps the region resident: registering host memory there
does not pin it, and a swapped-out page turns each GPU access into a fault."""
import torch
from b12x.sequence._shared.disk_table import _tensor_from_pointer
from b12x.sequence import tensor_from_pointer as _tensor_from_pointer

self.cuda, self.address, self.extent = cuda, address, extent
self.nbytes = math.prod(shape) * dtype.itemsize
Expand Down Expand Up @@ -491,7 +491,7 @@ class WindowsHostRegion:

def __init__(self, cuda, address, extent, shape, dtype, device, *, lock=False):
import torch
from b12x.sequence._shared.disk_table import _tensor_from_pointer
from b12x.sequence import tensor_from_pointer as _tensor_from_pointer

self.cuda, self.address = cuda, address
self.nbytes = math.prod(shape) * dtype.itemsize
Expand Down
15 changes: 10 additions & 5 deletions ignition/preparation/forward_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,15 @@ def reducer_override(self, value):
from triton.compiler import CompiledKernel
from cutlass.base_dsl.jit_executor import JitCompiledFunction
from cutlass.cute.runtime import _Tensor as CuTeRuntimeTensor
from b12x._lib.compile_plan import CompiledCuTeProgram, DeferredCuTeKernel, DeferredTritonKernel
from b12x.preparation import PreparationSession
from b12x.preparation import (
CompiledCuTeProgram,
DeferredCuTeKernel,
DeferredTritonKernel,
PreparationSession,
PreparedSlot,
PreparedState,
)
from b12x.preparation.device import DetectedDevice
from b12x.preparation.types import _PreparedSlot, _Prepared
from torch._dynamo.aot_compile_types import _deserialize_triton_kernel, _serialize_triton_kernel
from .device_binding import restore_device, restore_prepared_device
from .core_storage import CoreStorage
Expand All @@ -208,10 +213,10 @@ def reducer_override(self, value):
if user_attrs:
return _tensor, args, user_attrs, None, None, _set_state
return _tensor, args
if isinstance(value, _PreparedSlot):
if isinstance(value, PreparedSlot):
# Tracing needs selected layouts; normal plan pickling clears prepared state.
return _object, (type(value),), dict(vars(value)), None, None, _set_state
if isinstance(value, _Prepared):
if isinstance(value, PreparedState):
state = dict(vars(value))
for name in ('retained', 'owners', 'closers', 'users'):
state[name] = _Unavailable(f'b12x prepared {name}')
Expand Down
2 changes: 1 addition & 1 deletion ignition/preparation/peer_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# The forward pickler imports this module on Windows; descriptor passing is POSIX-only.
DupFd = None

from b12x.comm.pcie._cuda_ipc import CudaRTLibrary
from b12x.comm.pcie import CudaRTLibrary


class _Location(C.Structure):
Expand Down
2 changes: 1 addition & 1 deletion ignition/preparation/persistent.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def __init__(self, region, capacity, granularity):
self.closed = False

def empty(self, shape, stride, dtype, nbytes, alignment):
from b12x.sequence._shared.disk_table import _tensor_from_pointer
from b12x.sequence import tensor_from_pointer as _tensor_from_pointer

if self.closed:
raise RuntimeError("persistent tensor storage is closed")
Expand Down
2 changes: 1 addition & 1 deletion ignition/preparation/remote_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from contextlib import closing
import os

from b12x.loader._checkpoint import DirectWeightSession, TensorRange
from b12x.loader import DirectWeightSession, TensorRange

from .checkpoint_source import BLOCK_BYTES, row_extent, tensor_dtype

Expand Down
35 changes: 17 additions & 18 deletions ignition/preparation/tuning.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@
from b12x.preparation import (
AutotuneEffort, FrozenMapping, MemoryRequirements, PreparationDisplay, PreparationSession,
autotune_effort as b12x_autotune_effort,
declaration_key, iter_plans,
)
from b12x.preparation.session import _declaration_key, _plans_of
from b12x.preparation.types import _CompositePlan

from .scratch import ScratchArena
from .tuning_shards import component_key, local_components, materialization_key, portable_declaration
Expand Down Expand Up @@ -133,7 +132,7 @@ def __init__(self, *, device, checkpoint: str, workload_schema: str,
self.tuning_report = None

def _require_collecting(self):
self._check_thread()
self.check_thread()
if self._tune_status != "collecting":
raise RuntimeError("preparation declarations are closed after tuning begins")

Expand Down Expand Up @@ -297,7 +296,7 @@ def register_scratch(self, arena):
self._scratch_arena = arena

def benchmark_resource(self, key: Hashable, factory):
self._check_thread()
self.check_thread()
if self._tune_status != "tuning":
raise RuntimeError("shared benchmark resources exist only during candidate tuning")
if key not in self._benchmark_resources:
Expand All @@ -311,7 +310,7 @@ def benchmark_resource(self, key: Hashable, factory):

def release_benchmark_cache(self):
"""Drop cached fixtures; live trial calls and borrowed state retain their owners."""
self._check_thread()
self.check_thread()
if self._tune_status != "tuning":
raise RuntimeError("benchmark fixtures can only be retired during tuning")
self._benchmark_resources = {key: value for key, value in self._benchmark_resources.items()
Expand All @@ -331,15 +330,15 @@ def register_benchmark_resource(self, key: Hashable, resource, *, restore):
def _restore_benchmark_resources(self):
if not self._benchmark_restorers:
return
self._synchronize()
self.synchronize()
failures = []
for restore in self._benchmark_restorers.values():
try:
restore()
except BaseException as error:
failures.append(error)
try:
self._synchronize()
self.synchronize()
except BaseException as error:
failures.append(error)
if failures:
Expand All @@ -355,7 +354,7 @@ def _reserve_scratch(self, requests):
arena = self._scratch_arena
groups, keys, envelopes = {}, {}, {}
for request in requests:
key = _declaration_key(request.plan)
key = declaration_key(request.plan)
keys[id(request.plan)] = key
# Memory bounds are independent of execution order. Each subset must
# stand alone while the tuning batch retains its dependency graph.
Expand Down Expand Up @@ -414,7 +413,7 @@ def tune(self, *, progress=None, show_progress=False, console=None):
self._tune_status = "tuning"
results = []
try:
if self._stop.is_set():
if self.is_cancelled():
raise RuntimeError("full serving preparation requires enabled, uncancelled b12x tuning")
requests = tuple(self._recorded_requests.values())
partial_shards = False
Expand Down Expand Up @@ -444,15 +443,15 @@ def tune(self, *, progress=None, show_progress=False, console=None):
else:
partial_shards = True
if self._coordinator.spans_hosts:
self._coordinator.share_selections(self._selection_cache())
self._coordinator.share_selections(self.selection_cache())
scratch_arena = self._reserve_scratch(requests)
if partial_shards:
device = self.device
partial_shards = self._coordinator.same_on_every_rank((
getattr(device, "identity", None),
getattr(device, "max_shared_memory_per_block", None),
getattr(device, "max_shared_memory_per_multiprocessor", None),
getattr(self, "_scratch_limit", None),
self.scratch_limit,
)) and getattr(device, "identity", None) is not None
release_unused()
# Compiler pools share the memory and CPUs of ranks on this host only.
Expand Down Expand Up @@ -495,14 +494,14 @@ def update(status):
result = self._prepare_mixed_batch(batch, coordination, update)
if result is not None:
results.append(result)
if self._stop.is_set():
if self.is_cancelled():
raise RuntimeError("b12x tuning was cancelled before serving preparation completed")
if (self._coordinator is not None and len(self._coordinator.ranks) > 1
and not self._sharded and self._replica_coordinator is None):
configs, changed = self._coordinator.reconcile_selections(requests)
if changed:
for job in self._jobs(requests):
plans = {plan for request in job for plan in _plans_of(request)}
plans = {plan for request in job for plan in iter_plans(request)}
results.append(self._coordinator.prepare(self, job, progress=progress,
autotune=self.autotune,
selected_configs={plan: config for plan, config in configs.items() if plan in plans}))
Expand All @@ -522,7 +521,7 @@ def update(status):
if self._scratch_arena is not None:
if self._scratch_arena.nbytes != scratch_arena["candidate_reserved_bytes"]:
raise RuntimeError("candidate binding exceeded the planned scratch envelope")
self._synchronize()
self.synchronize()
selected = MemoryRequirements.sequential(request.plan.memory_requirements() for request in requests)
parallel = self._scratch_arena.parallel_nbytes(lambda plan:
plan.memory_requirements().scratch_nbytes)
Expand All @@ -537,7 +536,7 @@ def update(status):
reserved_bytes=self._scratch_arena.nbytes)
for callback in self._finalizers:
callback()
self._synchronize()
self.synchronize()
self.tuning_report = {
"workload_schema": self._workload_schema, "namespace": self.namespace.to_dict(),
"autotune_effort": self.autotune_effort,
Expand Down Expand Up @@ -630,12 +629,12 @@ def _clear_tuning_owners(self):
self._finalizers.clear()
self._recorded_requests.clear()

def _reclaim_programs(self):
def reclaim_programs(self):
terminal = self.state == "CLOSED"
if terminal:
# Include Ignition's tuning owners in b12x's terminal heap collection.
self._clear_tuning_owners()
super()._reclaim_programs()
super().reclaim_programs()
if terminal:
self._terminal_collected = True

Expand All @@ -653,7 +652,7 @@ def close(self):
gc.collect()
self._terminal_collected = True
self._restore_benchmark_resources()
self._synchronize()
self.synchronize()
if self._scratch_arena is not None:
self._scratch_arena._finalizers.clear()
self._scratch_arena = None
Expand Down
34 changes: 20 additions & 14 deletions ignition/preparation/tuning_shards.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,25 @@
from io import BytesIO
import pickle

from b12x.preparation import CandidateResourceIneligibleError

from b12x.preparation.session import _coalesce_requests, _declaration_key, _expand_requests, _plans_of
from b12x.preparation.types import _CompositePlan, _plan_scope
from b12x.preparation import (
CandidateResourceIneligibleError,
coalesce_requests,
declaration_key,
expand_requests,
is_composite_plan,
iter_plans,
plan_compile_jobs,
plan_memory_requirements,
plan_variants,
)


def portable_declaration(plan):
if isinstance(plan, _CompositePlan):
if is_composite_plan(plan):
return (plan.component_id, plan.composite_semantic_version, plan.capacity_metadata, plan.shared,
tuple((rows, portable_declaration(child)) for rows, child in plan.variants.items()))
tuple((rows, portable_declaration(child)) for rows, child in plan_variants(plan).items()))
# Placement does not specify a different kernel on equivalent devices.
return (*_declaration_key(plan)[:-1], getattr(plan, "shared", False))
return (*declaration_key(plan)[:-1], getattr(plan, "shared", False))


def local_components(requests):
Expand All @@ -35,8 +42,8 @@ def root(name):
if dependency not in links:
raise ValueError(f"unknown preparation dependency {dependency!r} for {name!r}")
links[root(name)] = root(dependency)
for plan in _plans_of(request):
other = aliases.setdefault(_declaration_key(plan), name)
for plan in iter_plans(request):
other = aliases.setdefault(declaration_key(plan), name)
links[root(name)] = root(other)

groups = {}
Expand All @@ -59,8 +66,8 @@ def materialization_key(session, group):
"""
digest = sha256()
owners = {}
expanded, _ = _expand_requests(group)
for equivalent in _coalesce_requests(expanded):
expanded, _ = expand_requests(group)
for equivalent in coalesce_requests(expanded):
plan = equivalent[0].plan
choice = plan.contract.configure(plan.query, device=session.device.identity, override=plan.override)
configs = (choice.pinned,) if choice.pinned is not None else (
Expand All @@ -80,8 +87,7 @@ def materialization_key(session, group):
continue
seen_plans.add(bound)
try:
with _plan_scope(bound):
memory = bound._memory_requirements(config, session.device)
memory = plan_memory_requirements(bound, config, session.device)
except CandidateResourceIneligibleError:
footprint.append(None)
continue
Expand All @@ -92,7 +98,7 @@ def materialization_key(session, group):
tuple((owners.setdefault(m.key, len(owners)), m.required_nbytes, m.resident_nbytes)
for m in memory.persistent),
))
jobs = () if None in footprint else tuple(plan._compile_jobs(config, session.device))
jobs = () if None in footprint else plan_compile_jobs(plan, config, session.device)
declaration = (payload, jobs, tuple(footprint))
# Compiler metadata is acyclic. Equal arguments can nonetheless
# have different object sharing across ranks; identity memoization
Expand Down
Loading
Loading