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
16 changes: 11 additions & 5 deletions docs/multi-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,8 +363,10 @@ On `hertz`:

For four hosts, use `--ranks 4` and start peer ranks 1, 2, and 3. Rank zero
admits each peer once, serves checkpoint metadata and selected byte ranges,
and coordinates preparation. Peers do not create full checkpoint shards.
Keep checkpoint source files unchanged during loading.
and coordinates preparation. During admission, rank zero sends the recipe's
`b12x_environment` settings so each peer applies them alongside its own local
`kernel_cache` before importing preparation libraries. Peers do not create full
checkpoint shards. Keep checkpoint source files unchanged during loading.

RoCEnante collectives give up on a peer after about 20 s, which suits serving.
While compiled forwards warm, the rank that compiled a forward meets its Triton
Expand Down Expand Up @@ -411,9 +413,13 @@ throughput separately for each peer. Cache hits skip bulk payload transfer.

Each rank loads its weights and prepares its graphs. Forward compilation is
shared across ranks, and compiled artifacts go to the ranks that need them.
Peers send export manifests; rank zero requests missing payload files,
assembles the core, signs it, and zstd-compresses executable resources. Temporary
staging is removed after use; reusable cached blobs remain.
`ForwardCache` keys each host's compiled-forward cache on execution-relevant
`B12X_*` settings and excludes host-local cache directories, worker counts,
RDMA device selectors, and logging flags, so distinct hosts share identical
relative cache keys. Peers send export manifests; rank zero requests missing
payload files, assembles the core, signs it, and zstd-compresses executable
resources. Temporary staging is removed after use; reusable cached blobs
remain.

GLM-5.3 Flash supports `--no-context-parallel` to replicate attention pages and
`--no-stream-overlap` to serialize concurrent branches. These are preparation
Expand Down
19 changes: 14 additions & 5 deletions ignition/cli/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ def _export_hosts(args):
rendezvous = HostRendezvous(args.rendezvous, args.ranks, identity=source_identity(),
topology=local_topology(local[0]),
checkpoint_fabric=_checkpoint_fabric(args),
checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value)
checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value,
b12x_environment=model.recipe.b12x_environment)
with phase(progress, "Wait for tensor-parallel hosts") as stage:
topologies = rendezvous.accept(report=stage.update)
gpus = tuple(topology_gpu(topology, index) for index, topology in enumerate(topologies))
Expand Down Expand Up @@ -415,7 +416,8 @@ def debug_serve(args) -> int:
rendezvous = HostRendezvous(args.rendezvous, args.ranks, identity=source_identity(),
topology=local_topology(local[0]),
checkpoint_fabric=_checkpoint_fabric(args),
checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value)
checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value,
b12x_environment=model.recipe.b12x_environment)
with phase(progress, "Wait for tensor-parallel hosts") as stage:
topologies = rendezvous.accept(report=stage.update)
gpus = tuple(topology_gpu(topology, index) for index, topology in enumerate(topologies))
Expand Down Expand Up @@ -542,12 +544,19 @@ def progress(message):
if not 0 <= args.gpu < len(host.gpus):
raise UsageError(f"--gpu {args.gpu} names a GPU this host does not have")
gpu = host.gpus[args.gpu]
environment.apply(configuration, (gpu,))
identity = source_identity()
control, executor = knock(args.rendezvous, args.rank, args.ranks, identity=identity,
topology=local_topology(gpu), report=progress)
control, executor, b12x_environment = knock(
args.rendezvous, args.rank, args.ranks, identity=identity,
topology=local_topology(gpu), report=progress)
try:
environment.apply(configuration, (gpu,), b12x_environment)
except BaseException:
control.close()
executor.close()
raise
serve_peer(control, executor, args.rank, args.ranks, hub_cache=hub_cache, progress=progress,
export_staging=configuration.directory("export_staging"), identity=identity,
core_cache=configuration.directory("core_cache"),
kernel_cache=configuration.directory("kernel_cache"),
checkpoint_token_file=configuration.get("preparation.checkpoint_token_file").value)
return 0
128 changes: 99 additions & 29 deletions ignition/preparation/aot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
import operator
import os
import pickle
import struct
import sys
import tempfile
import warnings
import zipfile
import zlib
from concurrent.futures import FIRST_COMPLETED, wait
from contextlib import ExitStack, contextmanager, nullcontext
Expand Down Expand Up @@ -42,6 +45,69 @@
_DEFERRED_BINDINGS = ContextVar("flare_deferred_bindings", default=False)
_CHECK_BINDINGS = ContextVar("flare_check_bindings", default=False)

_NON_EXECUTION_B12X_ENV = frozenset({
"B12X_COLLECTIVE_BARRIER_TIMEOUT",
"B12X_COMPILE_CACHE_DIR",
"B12X_COMPILE_DISK_CACHE",
"B12X_COMPILE_MEMORY_CACHE",
"B12X_COMPILE_MEMORY_CACHE_SIZE",
"B12X_COMPILE_SPEC_MEMO",
"B12X_COMPILE_WORKERS",
"B12X_PREPARATION_TRACE_DIR",
"B12X_PRINT_COMPILE_PROGRESS",
"B12X_ROCE_CACHE_DIR",
"B12X_ROCE_GID_INDEX",
"B12X_ROCE_HCA",
"B12X_TIMING",
"B12X_TIMING_THRESHOLD_MS",
})

_CORRUPT_ARTIFACT_ERRORS = (
EOFError,
pickle.UnpicklingError,
struct.error,
zlib.error,
zipfile.BadZipFile,
)


def _b12x_forward_env():
"""Return sorted execution-relevant B12X_* environment bindings for forward cache identity."""
return tuple(sorted(
(name, value)
for name, value in os.environ.items()
if name.startswith("B12X_")
and name not in _NON_EXECUTION_B12X_ENV
and not name.startswith("B12X_LOG_")
))


def _atomic_write_file(path, writer):
"""Write a binary file via a sibling temporary file, closing it before rename or cleanup."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
file = tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False)
temporary = Path(file.name)
try:
with file:
writer(file)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)


def _save_compiled_function(artifact, path):
"""Write a compiled forward archive via a sibling temporary file and atomic rename."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, suffix='.tmp', delete=False) as file:
temporary = Path(file.name)
try:
artifact.save_compiled_function(str(temporary))
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)


def _load_inductor(data, original, *, frozen=False):
runtime_patches.apply()
Expand Down Expand Up @@ -209,15 +275,7 @@ def build(code_parts, closure_args):
if path.is_file():
return pickle.loads(path.read_bytes())
result = original(code_parts, closure_args)
root.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=root, suffix='.tmp', delete=False) as file:
temporary = Path(file.name)
try:
pickle.dump(result, file)
file.close()
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
_atomic_write_file(path, lambda file: pickle.dump(result, file))
return result

token = _GUARD_TENSOR_MODE.set(torch._subclasses.FakeTensorMode())
Expand Down Expand Up @@ -809,10 +867,7 @@ def current(path, digest):
dist.broadcast_object_list(payload, src=ranks[index], group=group)
if path in missing:
target = _resolve_shared_path(root, path)
target.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=target.parent, suffix=".tmp", delete=False) as file:
file.write(payload[0])
os.replace(file.name, target)
_atomic_write_file(target, lambda file: file.write(payload[0]))
missing.discard(path)


Expand All @@ -832,8 +887,9 @@ def __init__(self, *, namespace, device, root=None, headroom_bytes=0, options=No
self.options = MappingProxyType(_compile_options(options))
properties = torch.cuda.get_device_properties(device)
options = {name: value for name, value in self.options.items() if name != 'compile_threads'}
key = hashlib.sha256(pickle.dumps((namespace, options, torch_key(), runtime_patches.identity(),
properties.name, properties.major, properties.minor, properties.multi_processor_count)))
key = hashlib.sha256(pickle.dumps((namespace, options, _b12x_forward_env(), torch_key(),
runtime_patches.identity(), properties.name, properties.major, properties.minor,
properties.multi_processor_count)))
for source in (Path(__file__).resolve().parents[1], Path(flashinfer.__file__).resolve().parent):
for path in sorted(source.rglob('*.py')):
if source.name == 'ignition' and (path.name == '__main__.py'
Expand Down Expand Up @@ -1119,14 +1175,7 @@ def _prepare_ranks(self, functions, signatures, coordinator, *, progress, materi
name, variant, forward = work[index]
path = self._path(forward, name=f"{name}.{variant}", signature=signatures[name])
job = jobs / f"{path.stem}.forward"
with tempfile.NamedTemporaryFile(dir=jobs, suffix='.tmp', delete=False) as file:
temporary = Path(file.name)
try:
pickle.dump((dumps(forward), str(path)), file)
file.close()
os.replace(temporary, job)
finally:
temporary.unlink(missing_ok=True)
_atomic_write_file(job, lambda file: pickle.dump((dumps(forward), str(path)), file))
sent.append((borrower, str(job)))
# The borrower compiles it before every rank gathers the outcome below.
paths[name, variant] = path.relative_to(self.root).as_posix(), True
Expand Down Expand Up @@ -1260,7 +1309,7 @@ def finish():
rel_path, _ = paths[name, variant]
local_path = _resolve_shared_path(self.root, rel_path)
if compilers[name, variant] == share:
bound.artifact.save_compiled_function(str(local_path))
_save_compiled_function(bound.artifact, local_path)
published.append(rel_path)
if stream:
selected[name] = DeferredCompiledForward(
Expand Down Expand Up @@ -1306,9 +1355,30 @@ def _allocation_sizes(self, path):
return sizes

def _load(self, forward, path, *, required=False, before_run=None):
with bind_device(self.device, freeze_tuning=self.options.get(
'triton.autotune_at_compile_time', False)), path.open('rb') as file:
artifact = torch.compiler.load_compiled_function(file)
path = Path(path)
try:
file = path.open('rb')
except FileNotFoundError:
if required:
raise
return None
try:
with file, bind_device(self.device, freeze_tuning=self.options.get(
'triton.autotune_at_compile_time', False)):
artifact = torch.compiler.load_compiled_function(file)
except _CORRUPT_ARTIFACT_ERRORS as error:
if required:
raise
warnings.warn(
f"discarding corrupt compiled forward cache entry {path}: {type(error).__name__}: {error}",
RuntimeWarning,
stacklevel=2,
)
try:
path.unlink(missing_ok=True)
except OSError:
pass
return None
# Bound forwards remain live for the complete catalog. Collect young
# deserialization temporaries here; scan the retained heap once at each
# preparation phase boundary instead of once per restored forward.
Expand Down Expand Up @@ -1382,7 +1452,7 @@ def report(operation):
source_identity=self.root.name)
path.parent.mkdir(parents=True, exist_ok=True)
if not hasattr(bound.artifact._artifacts.compiled_fn.artifact, '_flare_graph'):
bound.artifact.save_compiled_function(str(path))
_save_compiled_function(bound.artifact, path)
cached = bound.cache_hit
bound = self._load(bound.owner, path, required=True, before_run=before_run)
bound.cache_hit = cached
Expand All @@ -1391,5 +1461,5 @@ def report(operation):
selections.warm(bound, warmup, before_run=before_run)
selections.freeze(bound)
report("saving compiled forward")
bound.artifact.save_compiled_function(str(path))
_save_compiled_function(bound.artifact, path)
return bound
67 changes: 45 additions & 22 deletions ignition/preparation/collectives.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,17 +209,18 @@ def identity(name):

entries = []

def selected(plan, key):
def selected(plan, key, name, variant=()):
if is_composite_plan(plan):
for count, child in plan_variants(plan).items():
selected(child, (key, count))
selected(child, (key, count), name, (*variant, count))
else:
config = plan.selection.config
entries.append((plan, key, plan.contract.config_payload(config), config))
entries.append((plan, key, (name, variant, plan.component_id),
plan.contract.config_payload(config), config))

for request in requests:
if request.collective is None:
selected(request.plan, identity(request.name))
selected(request.plan, identity(request.name), request.name)
return entries


Expand Down Expand Up @@ -395,32 +396,54 @@ def agree_selections(self, selections):
f"{differing[:3]}; preparing again adopts rank zero's tuning decisions")

def reconcile_selections(self, requests):
"""Choose one actual configuration for matching declarations across ranks.
"""Choose one actual configuration for matching requests or declarations across ranks.

Unsharded remainder components in unequal catalogs (or catalogs on
heterogeneous hardware) still need matching scratch layouts before
compiled forwards are shared.
compiled forwards are shared. Matching by request name first ensures
rank-divergent declarations for the same request adopt rank zero's
configuration, while portable declaration matching covers shared plans
whose request names differ across ranks.
"""
entries = _selected_plan_catalog(requests)
local = {}
for _, key, payload, config in entries:
local.setdefault(key, {}).setdefault(payload, config)
local = [(decl_key, name_key, payload, config)
for _, decl_key, name_key, payload, config in entries]
gathered = [None] * len(self.ranks)
dist.all_gather_object(gathered, local, group=self.group)
chosen, participants = {}, {}
for catalog in gathered:
for key, values in catalog.items():
chosen.setdefault(key, next(iter(values.items())))
participants[key] = participants.get(key, 0) + 1
common = {key for key, count in participants.items() if count > 1}
changed = any(payload != chosen[key][0]
for catalog in gathered for key, values in catalog.items() if key in common
for payload in values)
chosen_decl, decl_participants = {}, {}
chosen_name, name_participants = {}, {}
for rank_entries in gathered:
seen_decl, seen_name = set(), set()
for decl_key, name_key, payload, config in rank_entries:
chosen_decl.setdefault(decl_key, (payload, config))
if decl_key not in seen_decl:
seen_decl.add(decl_key)
decl_participants[decl_key] = decl_participants.get(decl_key, 0) + 1
chosen_name.setdefault(name_key, (payload, config))
if name_key not in seen_name:
seen_name.add(name_key)
name_participants[name_key] = name_participants.get(name_key, 0) + 1
common_decl = {key for key, count in decl_participants.items() if count > 1}
common_name = {key for key, count in name_participants.items() if count > 1}

def target_for(decl_key, name_key):
if name_key in common_name:
return chosen_name[name_key]
if decl_key in common_decl:
return chosen_decl[decl_key]
return None

changed = any(
(target := target_for(decl_key, name_key)) is not None and payload != target[0]
for rank_entries in gathered
for decl_key, name_key, payload, _ in rank_entries
)
configs = {}
for plan, key, payload, _ in entries:
if key in common and payload != chosen[key][0]:
config = chosen[key][1]
if plan in configs and plan.contract.config_payload(configs[plan]) != chosen[key][0]:
for plan, decl_key, name_key, payload, _ in entries:
target = target_for(decl_key, name_key)
if target is not None and payload != target[0]:
target_payload, config = target
if plan in configs and plan.contract.config_payload(configs[plan]) != target_payload:
raise ValueError("one plan has conflicting rank-shared configurations")
configs[plan] = config
return configs, changed
Expand Down
Loading
Loading