diff --git a/ignition/components/engram.py b/ignition/components/engram.py index 0e224e534..e77df2e8b 100644 --- a/ignition/components/engram.py +++ b/ignition/components/engram.py @@ -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 diff --git a/ignition/preparation/collectives.py b/ignition/preparation/collectives.py index f70809979..76c165770 100644 --- a/ignition/preparation/collectives.py +++ b/ignition/preparation/collectives.py @@ -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} @@ -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 @@ -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.""" diff --git a/ignition/preparation/composition_tuning.py b/ignition/preparation/composition_tuning.py index aba66e0f9..e621ff3fc 100644 --- a/ignition/preparation/composition_tuning.py +++ b/ignition/preparation/composition_tuning.py @@ -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 @@ -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) diff --git a/ignition/preparation/core_storage.py b/ignition/preparation/core_storage.py index 85d222c8a..a3e13e826 100644 --- a/ignition/preparation/core_storage.py +++ b/ignition/preparation/core_storage.py @@ -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 @@ -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 @@ -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 diff --git a/ignition/preparation/forward_metadata.py b/ignition/preparation/forward_metadata.py index b700bd674..20920a516 100644 --- a/ignition/preparation/forward_metadata.py +++ b/ignition/preparation/forward_metadata.py @@ -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 @@ -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}') diff --git a/ignition/preparation/peer_storage.py b/ignition/preparation/peer_storage.py index aa3c68de6..1419a538d 100644 --- a/ignition/preparation/peer_storage.py +++ b/ignition/preparation/peer_storage.py @@ -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): diff --git a/ignition/preparation/persistent.py b/ignition/preparation/persistent.py index 6ee0a1f77..dbee10308 100644 --- a/ignition/preparation/persistent.py +++ b/ignition/preparation/persistent.py @@ -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") diff --git a/ignition/preparation/remote_weights.py b/ignition/preparation/remote_weights.py index 730b4271f..9df10a462 100644 --- a/ignition/preparation/remote_weights.py +++ b/ignition/preparation/remote_weights.py @@ -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 diff --git a/ignition/preparation/tuning.py b/ignition/preparation/tuning.py index 08c8dc637..4899b701e 100644 --- a/ignition/preparation/tuning.py +++ b/ignition/preparation/tuning.py @@ -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 @@ -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") @@ -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: @@ -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() @@ -331,7 +330,7 @@ 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: @@ -339,7 +338,7 @@ def _restore_benchmark_resources(self): except BaseException as error: failures.append(error) try: - self._synchronize() + self.synchronize() except BaseException as error: failures.append(error) if failures: @@ -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. @@ -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 @@ -444,7 +443,7 @@ 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 @@ -452,7 +451,7 @@ def tune(self, *, progress=None, show_progress=False, console=None): 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. @@ -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})) @@ -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) @@ -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, @@ -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 @@ -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 diff --git a/ignition/preparation/tuning_shards.py b/ignition/preparation/tuning_shards.py index 6f7dde1f8..3a49844ab 100644 --- a/ignition/preparation/tuning_shards.py +++ b/ignition/preparation/tuning_shards.py @@ -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): @@ -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 = {} @@ -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 ( @@ -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 @@ -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 diff --git a/ignition/preparation/virtual_storage.py b/ignition/preparation/virtual_storage.py index 57aa11220..33db68992 100644 --- a/ignition/preparation/virtual_storage.py +++ b/ignition/preparation/virtual_storage.py @@ -38,7 +38,7 @@ def _round(self, nbytes): def device_allocate(self, name, shape, dtype, *, group, maximum, units=None): """Reserve `maximum` units of address space and back the first `units`.""" 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 diff --git a/ignition/runtime_patches/__init__.py b/ignition/runtime_patches/__init__.py index 3fe688b30..e7bba8e88 100644 --- a/ignition/runtime_patches/__init__.py +++ b/ignition/runtime_patches/__init__.py @@ -116,8 +116,10 @@ def apply() -> None: try: for owner, name, replacement in replacements: setattr(owner, name, replacement) + workers.register_hooks() torch.compiler.config.cache_key_tag = cache_tag except Exception: + workers.unregister_hooks() for owner, name, original in originals: if original is _MISSING: if name in vars(owner): diff --git a/ignition/runtime_patches/triton.py b/ignition/runtime_patches/triton.py index 90337ee49..99ac1d625 100644 --- a/ignition/runtime_patches/triton.py +++ b/ignition/runtime_patches/triton.py @@ -18,13 +18,3 @@ def replacements(): from triton.runtime import build return ((build, "platform_key", platform_key),) - - -def initialize_b12x_worker(*args): - from b12x._lib.compile_pool import _initialize_worker - - from . import apply_triton - - # b12x uses spawn, so this process imports its original initializer. - apply_triton() - _initialize_worker(*args) diff --git a/ignition/runtime_patches/workers.py b/ignition/runtime_patches/workers.py index 9dcb06a2f..c2dd5c5e7 100644 --- a/ignition/runtime_patches/workers.py +++ b/ignition/runtime_patches/workers.py @@ -23,20 +23,28 @@ def initialize_inductor_worker(orig_ppid, close_fds=()): apply() +def register_hooks() -> None: + from b12x.preparation import register_worker_initializer + + register_worker_initializer(apply_triton) + + +def unregister_hooks() -> None: + from b12x.preparation import unregister_worker_initializer + + unregister_worker_initializer(apply_triton) + + def replacements(): - from b12x._lib import compile_pool from torch._inductor import async_compile, autotune_process, cpu_vec_isa, utils as inductor_utils from torch._inductor.compile_worker import subproc_pool, utils - from .triton import initialize_b12x_worker - patched_env = _replace( inductor_utils.python_subprocess_env, (("os.pathsep.join((torch_package_root, *sys.path))", "os.pathsep.join((*sys.path, torch_package_root))"),), ) return ( - (compile_pool, "_initialize_worker", initialize_b12x_worker), (subproc_pool, "SubprocPickler", CompilerPickler), (inductor_utils, "python_subprocess_env", patched_env), (subproc_pool, "python_subprocess_env", patched_env),