Skip to content

[HIP] [OPUS] [FlyDSL] Simplify AITER compiler worker fan-out to smooth-out regressions - #5164

Merged
zufayu merged 44 commits into
ROCm:mainfrom
Qubitium:wip/worker-aware-aot-limits
Oct 18, 2026
Merged

zufayu merged 44 commits into
ROCm:mainfrom
Qubitium:wip/worker-aware-aot-limits

Conversation

@Qubitium

@Qubitium Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Unify AITER's compiler-pool sizing and prevent nested builds from multiplying concurrency. CPU compilation and GPU-executing prebuilds use separate budgets.

Current behavior

  • CPU compilation: use the smaller of 80% of the CPU capacity allowed by affinity and readable cgroup quotas and effective available memory divided by the 1.5 GB worker estimate, with a one-worker minimum. Limits are recomputed at each policy call, not exported as automatic environment overrides. Cgroup memory accounting remains conservative; unreadable usage under a finite limit fails closed, with rate-limited diagnostics.
  • GPU execution: PA-Gluon uses visible GPUs × AITER_GPU_WORKERS_PER_DEVICE (default 8), capped by submitted work and AITER_MAX_JOBS. Workers are assigned round-robin to devices and allocate on their assigned GPU, rather than all using cuda:0. Discovery delegates to torch.cuda.device_count(), including amdsmi with HIP-runtime fallback on ROCm. Nonempty runs require a visible GPU.
  • Nested builds: AOT process-pool children limit nested AITER compilation to one job, using explicit Ninja -j, CMake/Make controls, and numerical-runtime thread hints. The wheel prebuild instead splits its total budget across at most five concurrent modules and their inner Ninja builds; the scoped ceiling is restored afterward.
  • Shared execution: five AOT drivers use one runner that discards compiler return values in the child while propagating failures. PA/ragged-PA share configuration enumeration. C++ helper builds share one bounded Make/Linux or Ninja/Windows launcher.
  • Source-checkout imports: cpp_extension.py imports the worker policy only when selecting Ninja concurrency, so importing it through a code generator does not require AITER to be installed first.
  • Tests and CI: focused tests/ modules run through pytest, including the shell-runner fallback; an empty pytest module fails. Existing CI prebuild ceilings are retained. Unused helpers, duplicate GPU discovery, and incidental tuner changes are removed.

Controls and compatibility

AITER_MAX_JOBS is an optional ceiling, not a bypass of the applicable CPU/memory or GPU budget. Invalid values select automatic sizing; non-positive values select one worker.

When it is unset, standalone build entrypoints adopt a valid positive legacy MAX_JOBS with a migration warning. Runtime JIT's Ninja launcher reads that legacy ceiling without changing the environment. Plain imports and generic policy calls do not consult MAX_JOBS; AITER never changes it.

The shared policy replaces the FlyDSL-specific worker/memory knobs. PA-Gluon's --num_processes is replaced by the GPU allowance and optional global ceiling. OPUS retains --jobs / -j as an additional ceiling.

Build parallelism is the canonical policy reference; installation and FlyDSL documentation link to it.

Validation

At f9634f10, after merging main through 6264f8f5:

  • CPU worker-policy/JIT-cache suites: 161 passed, 1 skipped (pandas unavailable), 55 subtests passed. Includes real process-pool serialization/error checks and the source-checkout code-generator import regression.
  • 11 additional tests pass with framework/backend stubs; all five AOT drivers retain their configuration counts. PA-Gluon coverage includes device assignment, allocation-device selection, no-GPU rejection, and two Make/Ninja command subtests.
  • Four mocked C++ build-path checks cover Make/Linux and Ninja/Windows at parent and nested worker limits. The shell runner executes the reviewer's 24-case reproduction and rejects an empty module.
  • Black, Ruff, shell syntax, and git diff --check pass.

Still outstanding: real GPU kernel execution, native Windows/HIP builds, and the large-core cold-prebuild comparison (wall time, peak RSS, active compiler count). Local checks ran on a CPU-only Linux host; no compilation-throughput improvement is claimed.

@Qubitium
Qubitium requested a review from a team September 1, 2026 02:36
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5164 --add-label <label>

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to opt this PR out.

@github-actions github-actions Bot changed the title Bound AITER worker and compiler fanout [HIP] [OPUS] [FlyDSL] Bound AITER worker and compiler fanout Sep 1, 2026

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

The problem this PR targets is real and worth solving. The findings below are all reproduced against 6c79b82 in a worktree; commands are included so you can re-run them.

Two are build-breaking.

Blocking

1. aiter/jit/utils/cpp_extension.py:29 — the new top-level import breaks every codegen subprocess, and the failure is swallowed.

The blob-gen scripts put AITER_CORE_DIR on sys.path, and in pip-install mode that resolves to aiter/jit/utils, not the repo root (gemm_moe_ck2stages_common.py:9-16). So:

$ python3 csrc/ck_gemm_moe_2stages_codegen/gen_instances.py --working_path /tmp/x
  File ".../aiter/jit/utils/chip_info.py", line 15, in <module>
    from cpp_extension import executable_path
  File ".../aiter/jit/utils/cpp_extension.py", line 29, in <module>
    from aiter_worker_limits import get_worker_count, get_worker_count_per_parent
ModuleNotFoundError: No module named 'aiter_worker_limits'

The same command on origin/main gets past all imports. These scripts are launched from aiter/jit/core.py:997 as os.system(f"{PY} {blob_gen_cmd.format(blob_dir)}") — the return code is discarded — so on a clean from-source PREBUILD_KERNELS=1 pip install -e ., before aiter_worker_limits reaches site-packages via the new py_modules entry, the affected modules generate zero kernel instances and build silently empty. optCompilerConfig.json has 126 entries carrying a blob_gen_cmd; every one whose generator routes through chip_info is exposed. You hit this exact problem for build_co.py and added sys.path.insert(0, _REPO_ROOT) there — the cpp_extension path needs the same sweep (or the module needs to live somewhere already importable, see the note at the end).

2. aiter/aot/pa.py:101 — consuming the executor.map iterator turns all five AOT drivers into hard failures.

process_config ends at csrc/cpp_itfs/utils.py:320 return run_lib(func_name, folder) → :277 return getattr(lib, func_name), i.e. a ctypes _FuncPtr, which cannot be pickled back to the parent:

>>> list(ProcessPoolExecutor(1).map(lambda _: ctypes.CDLL(None).getpid, [0]))
ValueError: ctypes objects containing pointers cannot be pickled

Base never consumed the iterator, so the error was discarded and the prebuild "succeeded". After this PR python3 -m aiter.aot.pa aborts — and that is the exact command the PR adds at README.md:151. Same list(executor.map(...)) at pa_ragged.py:101, pa_v1.py:108, asm_mla_decode_fwd.py:50, and sampling.py:98-100. The new tests mock ProcessPoolExecutor, so they can't catch it. Simplest fix: have process_config return None (or the func_name string).

The policy cancels its own guarantees

3. aiter_worker_limits.py:209 — the auto-computed value is written into AITER_MAX_JOBS, which lines 197-206 then treat as an explicit expert override that bypasses both caps.

Live:

first  = get_worker_count()          # -> 204, and os.environ["AITER_MAX_JOBS"] == "204"
w._cpu_worker_cap = lambda: 2        # crush the CPU budget
second = get_worker_count()          # -> 204   (expected 2)

Base did the opposite: aiter/jit/core.py:621-643 recomputed cpu_count and psutil availability on every call and clamped down. Concretely, setup.py:412 calls get_worker_count() on an idle host → 204 is exported; the FlyDSL AOT phase then consumes tens of GB; every later JIT/ninja build in that process, and in every spawned child, reads 204 as "explicit" and skips the memory check entirely. Same in a long-lived vLLM/SGLang process, and a child under a tighter cpuset/cgroup skips its own caps. This structurally cancels the memory cap the PR exists to add. Suggest keeping the computed value in a module-level cache rather than in the environment, and exporting a different variable for children if propagation is the goal.

4. :108 — _cgroup_memory_directories() returns on the first matching mountinfo entry, so a cgroup v1 memory limit is silently dropped on hybrid hosts.

The loop return directories as soon as one mount's ancestry walk reaches mount_point. On a hybrid host where the cgroup2 unified mount is listed before the v1 memory mount, the v2 entry wins, _cgroup_memory_remaining_bytes() returns None, and _available_memory_bytes() falls back to host psutil availability. In docker run -m 32g on a large host that yields a memory budget in the thousands, so the CPU cap wins and ~100 compile workers run inside a 32 GB cgroup → container OOM-kill. This is precisely the container case the PR description says it fixes. Collect across all matching mounts and take the tightest bound.

5. :145 — the cgroup budget counts reclaimable page cache as used.

Remaining is limit - memory.current (v2) / limit - memory.usage_in_bytes (v1). Both counters include page cache and reclaimable slab, and memory.stat is never opened (grep confirms zero references). On this host memory.current is 1.354 TB, of which inactive_file + active_file + slab_reclaimable = 92.8%; only ~91 GB is anon. In a CI container with a finite memory.max that has just cloned the repo and hipified sources, limit - current is a few GB → max(1, avail // 1_500_000_000) gives 1-2 workers, and PREBUILD_THREAD_NUM, ninja -j, get_max_workers and every AOT pool all serialize silently, getting worse the longer the container runs. The correct bound is limit - (usage - reclaimable_file_and_slab).

6. :40 — the psutil failure path floors the budget at exactly one worker, and the except tuple is too narrow.

_host_available_memory_bytes() returns EST_WORKER_RSS_BYTES on failure, and 1_500_000_000 // 1_500_000_000 == 1, so get_worker_count() returns 1 and exports AITER_MAX_JOBS=1: a 128-core build silently goes from minutes to hours with no warning. Base failed open in both places — setup.py:41-43 except ImportError: max_num_jobs_memory = max_num_jobs_cores (comment: "psutil may not be available during metadata extraction") and flydsl/common.py:233 except Exception: return default_workers. Also, psutil.Error derives from Exception, not OSError:

psutil.AccessDenied.__mro__ == (AccessDenied, Error, Exception, BaseException, object)

so AccessDenied/ZombieProcess, and the NotImplementedError psutil raises on an unsupported platform, are all outside (ImportError, OSError, ValueError, KeyError) and propagate out of get_worker_count() into import aiter / pip install as a hard traceback. Fail open to the CPU budget and catch Exception.

7. :197 — an explicit AITER_MAX_JOBS bypasses every safety cap, and this PR sets it to 64 in five workflows.

Base clamped down: if max_processes > max_jobs: os.environ["MAX_JOBS"] = str(max_jobs), and _get_num_workers clamped against max(1, cpu_count*0.8). After the rename, all five of aiter-test.yaml:24, atom-test.yaml:260, vllm-disagg-ci-smoke-workflow.yaml:45, kimi-perf-downstream.yaml:96, kimi-downstream.yaml:112 set AITER_MAX_JOBS=64 unconditionally — what used to be a ceiling hint is now a cap bypass. On a smaller runner, or in a 32 GB memory cgroup, 64 × 1.5 GB estimated RSS = 96 GB → an OOM-killed build where the old code would have clamped. For a PR titled around bounding fanout, this removes the one bound that existed. Consider clamping an explicit value to the auto budget with a warning, rather than documenting it as an unsafe override.

8. :202 — a malformed or empty AITER_MAX_JOBS now raises on the runtime JIT path.

$ AITER_MAX_JOBS= python3 -c "import aiter_worker_limits as w; w.get_worker_count()"
ValueError: AITER_MAX_JOBS must be an integer, got ''
$ AITER_MAX_JOBS=auto ...
ValueError: AITER_MAX_JOBS must be an integer, got 'auto'

This is reached from aiter/jit/core.py:989 check_and_set_ninja_worker() inside build_module, so a stray value — a -e AITER_MAX_JOBS="${VAR}" passthrough where VAR is unset, or a shell AITER_MAX_JOBS= pip install -e . — turns the first JIT compile inside a running inference server into an uncaught traceback rather than a slightly-wrong worker count. Base explicitly tolerated it (core.py:639-640 except ValueError:, and the old _get_num_workers gated on .isdigit()). The same hard-fail was newly added for PREBUILD_THREAD_NUM. Note int() still accepts ' 8 ', '+8' and '8_0' (== 80), so the validation is loose in one direction and fatal in the other.

Fanout regressions

9. setup.py:370 — PREBUILD_THREAD_NUM loses its hard cap of 5, inverting the build shape.

Base:

prebuid_thread_num = 5
max_jobs = os.environ.get("MAX_JOBS")
if max_jobs is not None and max_jobs.isdigit() and int(max_jobs) > 0:
    prebuid_thread_num = min(prebuid_thread_num, int(max_jobs))
else:
    prebuid_thread_num = min(prebuid_thread_num, getMaxJobs())

Head: prebuild_thread_num = get_worker_count_for(len(all_opts_args_build)) — one slot per prebuilt module, which is on the order of a hundred. The shape goes from "5 modules × wide ninja" to "N modules × ninja -j1", because the nested budget is get_worker_count_per_parent(N) and floor-divides to 1. Under CI's AITER_MAX_JOBS=64 that's 64 × -j1 vs base 5 × -j12; on a 256-core host it's ~128 concurrent jobs against a 204 budget, leaving a third of the budget unused. Work-stealing exists only at module granularity and the nested -j is frozen for the whole build, so the tail is serial — the largest CK module compiles all its TUs at -j1 while everything else sits finished.

Worse, os.environ["PREBUILD_THREAD_NUM"] is never popped in setup.py's own process (verified), and run_pretune_modules (aiter/utility/pretune.py:362) is a plain sequential loop, so each pretune rebuild still divides by that stale count and gets -j1 on an otherwise idle machine.

10. aiter/utility/mp_tuner.py:27 — a compiler-fanout policy is installed as the GPU tuning pool's initializer, pinning JIT builds to -j1.

_init_task_start_times is the initializer= for both mp.Pool sites (:473-475, :651-653), and it calls configure_worker_subprocesses(), which does os.environ[_WORKER_ENV] = "1". But setup.py's get_exclude_ops() excludes every _tune module from the prebuild, so the .so doesn't exist and the first worker to call e.g. aiter.gemm_a8w8_tune (@compile_ops("module_gemm_a8w8_tune")) triggers build_module in-process; base_tuner._set_config_env_for_run_config additionally sets AITER_REBUILD, forcing rebuilds mid-tune. Those builds now run -j1 instead of ~0.8×ncpu — on a 256-core / 8-GPU box that's 8 total compile jobs instead of ~200. The right primitive already exists in that module: get_worker_count_per_parent(mp_num).

Two notes on the same function: the OMP/MKL/OPENBLAS=1 half is largely inert under spawn (torch and libgomp are imported before the initializer runs), which makes the dict misleading rather than harmful; and NINJAFLAGS is not an environment variable ninja reads — the string is absent from the ninja binary, which only knows NINJA_STATUS — so that entry is dead and the -j1 effect comes solely from AITER_MAX_JOBS. Also csrc/ck_gemm_moe_2stages_codegen/gemm_moe_tune.py builds its pool without any initializer, so the two tuners now behave differently.

11. csrc/cpp_itfs/pa_gluon_aot/pa_decode_gluon_aot_prebuild.py:808 — a GPU-resident process pool is now sized by a CPU/host-RAM compiler policy.

Base always passed args.num_processes (argparse default 32), so the effective value was min(cpu_count, 32, total) = 32 and the if num_processes is None branch was dead. Head is get_worker_count_for(total) → up to ~204 on a 256-core host. These children genuinely use the GPU: the module does torch.set_default_device("cuda") at line 30 and run_pa_gluon_test sets device = "cuda:0" at :167-168 and allocates KV-cache/block-table tensors there. The pool is spawn-based, so that's ~204 separate HIP contexts on cuda:0 (hundreds of MB each) plus per-test KV caches. GPU memory appears nowhere in aiter_worker_limits.py, and with --num_processes deleted the only remaining knob is the global AITER_MAX_JOBS, which also throttles unrelated compilation.

12. aiter/aot/flydsl/common.py:210 — FlyDSL AOT loses its 64-worker ceiling and its per-worker memory assumption drops from 2.0 GB to 1.5 GB.

Base had _DEFAULT_MAX_WORKERS = 64 and _DEFAULT_MEM_PER_WORKER_GB = 2.0, applied as min(_affinity_aware_cpu_count(), 64) then _memory_worker_cap(...). Head is get_worker_count_for(num_jobs) with EST_WORKER_RSS_BYTES = 1_500_000_000 and no absolute ceiling: on a 256-core host with 300 GB available that's 64 → ~200 workers. The base README row said "Each worker uses ~1.5-2.5 GB RSS"; at the 2.5 GB end 200 workers is 500 GB against 300 GB available. The AITER_FLYDSL_AOT_WORKERS / AITER_FLYDSL_AOT_MEM_PER_WORKER_GB escape hatches were deleted along with the ceiling. Killed workers cost a retry each at a 1200 s timeout, and _run_file_pool drops permanently-failed kernels as results[idx] = None, so a memory-pressured run can silently ship a build missing kernels.

13. csrc/opus_gemm/gen_co/build_co.py:481 — the deliberately conservative hipcc fanout is replaced by the global budget, and --jobs/-j is deleted.

The removed argparse help stated the rationale directly: each hipcc invocation takes ~1 core for ~3 s, a full sweep is thousands of entries, so the default (cpu_count()//8) was deliberately well under nproc. On a 256-core host that goes 32 → up to ~204 concurrent hipcc processes in a ThreadPoolExecutor whose workers each hold a subprocess. hipcc's peak RSS for opus template instantiation isn't the 1.5 GB AOT-Python-worker figure the budget is derived from, so the memory model under-counts exactly the workload most likely to OOM. build_co.py -j 8 is now an argparse "unrecognized arguments" error, and configure_worker_subprocesses isn't called here (threads, same process), so nothing bounds nested fanout either.

Compatibility and CI

14. Generic MAX_JOBS is now silently ignored, with no deprecation path.

The in-repo rename is complete and the surviving MAX_JOBS uses (e.g. .github/scripts/build_aiter_triton.sh:66) correctly build Triton — but external consumers can't be updated in lockstep. Verified in this workspace: /app/ATOM/docker/atom_release.dockerfile:78 builds aiter with MAX_JOBS=$MAX_JOBS PREBUILD_KERNELS=$PREBUILD_KERNELS ..., and /app/ATOM/docker/Dockerfile has the same ARG MAX_JOBS / ENV MAX_JOBS shape. After this PR those throttles silently evaporate on a shared or memory-limited builder and aiter takes 80% of all CPUs instead — the exact direction the PR intends to prevent, with no error to signal it. A one-line back-compat read ("if AITER_MAX_JOBS is unset and MAX_JOBS is set, use it as an upper bound and warn once") would preserve every existing deployment at no cost.

15. The black pre-check goes red, and the new tests/ tree never runs in CI.

.github/workflows/pre-checks.yaml:35 runs psf/black@stable; python3 -m black --check on the PR-touched files reports exactly:

would reformat aiter_worker_limits.py
would reformat setup.py
would reformat op_tests/opus/device/setup.py
would reformat tests/test_asm_mla_decode_aot.py
would reformat tests/test_worker_awareness.py
5 files would be reformatted, 2 files would be left unchanged.

Separately, tests/ has no __init__.py, no conftest.py, and no pytest pythonpath, so the entry points behave inconsistently:

command result
python3 -m pytest tests/test_worker_awareness.py 23 passed
pytest tests/test_worker_awareness.py collection ERROR
python3 tests/test_worker_awareness.py ModuleNotFoundError: No module named 'aiter_worker_limits'

The last one is the if __name__ == "__main__" entry point the file itself advertises. And no workflow runs this directory: aiter-test.yaml:22 pins AITER_TEST: "op_tests", and the only tests/ paths in the workflows are flash_attention_integration.yaml's tests/test_flash_attn_triton_amd.py, which does not exist in this repo (it belongs to a different checkout). So none of the new regression coverage that would catch findings #1-#8 actually executes. CONTRIBUTE.md:114/117/152 also still say tests live in op_tests/.

One structural suggestion

aiter_worker_limits.py sits at the repo root and ships as an unnamespaced top-level py_modules entry, but the repo already has aiter/jit/utils/ for exactly the "importable before the package exists" role — that's where cpp_extension.py and chip_info.py live, and it's already on sys.path in every context that broke in finding #1. Moving it there removes the two sys.path.insert(0, _REPO_ROOT) bandaids and the need for tests/test_worker_entrypoints.py.

Worth knowing while you decide: setup.py's module-scope from aiter_worker_limits import ... works only because pyproject.toml declares [build-system] requires with no build-backend key. PEP 517 then defaults to setuptools.build_meta:__legacy__, the one backend that injects the source directory into sys.path. Adding the conventional explicit build-backend = "setuptools.build_meta" line — something an unrelated packaging cleanup would plausibly do — would break pip install . on this import.

Finally, this PR bundles a real MLA ABI fix and the executor.map changes with a large policy refactor and CI renames across 28 commits. If the policy needs to be reverted after landing, the unrelated fixes go with it — worth splitting.

@valarLip

valarLip commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

Following up on my review with a scoping suggestion, since I think the goal here is reachable with far less surface area than 30 files.

What main already does

Lowering the fanout is already supported and already clamps downward:

# aiter/jit/core.py:621  check_and_set_ninja_worker()
if max_processes > max_jobs:            # user asked for too much -> clamp
    os.environ["MAX_JOBS"] = str(max_jobs)

So MAX_JOBS=32 pip install -e . works today, and downstream images already rely on it (e.g. ATOM/docker/atom_release.dockerfile:78).

What's actually broken in main

The memory term is effectively dead:

max_num_jobs_cores  = os.cpu_count() * 0.8                 # 256-core host -> 204
free_memory_gb      = psutil.virtual_memory().available    # 2889 GB on my box
max_num_jobs_memory = int(free_memory_gb / 0.5)            # -> 5779
max_jobs            = min(204, 5779)                       # -> 204; memory never binds

Two concrete defects:

  1. 0.5 GB per job is far too low. This PR itself uses EST_WORKER_RSS_BYTES = 1_500_000_000, and aiter/aot/flydsl/common.py used 2.0 GB with a README range of 1.5-2.5 GB. At 0.5 GB the memory term can only bind below ~102 GB available, so on any large builder the CPU term always wins.
  2. psutil.virtual_memory().available reports the host. Inside docker run -m 32g the cgroup limit is invisible, so the computed value is wrong in exactly the environment that OOMs. This is the part an operator cannot fix by picking a number — they'd have to know the right number per container.

The same computation is also duplicated verbatim in setup.py:31 getMaxJobs() and core.py:621 check_and_set_ninja_worker().

Suggested smaller scope

Both defects are fixable in roughly 15 lines, in one shared helper replacing those two copies:

  • raise the per-job estimate from 0.5 GB to ~1.5 GB
  • derive available memory as min(psutil.available, cgroup_limit - anon_usage), where anon_usage comes from memory.stat (i.e. memory.current minus inactive_file + active_file + slab_reclaimable); fall back to psutil when no finite cgroup limit is readable
  • keep the existing clamp-down semantics for MAX_JOBS

That gets container awareness and a realistic memory model, leaves MAX_JOBS behaving as it does today, and requires no changes in downstream images.

Why I'd suggest that over the current shape

From the review, the current implementation doesn't yet deliver the guarantee it's built for:

  • an explicit AITER_MAX_JOBS now bypasses both caps rather than clamping, and this PR's own CI sets it to 64 in five workflows
  • the auto-computed value is written back into AITER_MAX_JOBS, after which it is read as an explicit override, so the memory check is skipped for the rest of the process and in every child
  • the cgroup path counts reclaimable page cache as used, which collapses the budget toward 1 worker in any container that has done I/O
  • the outer-pool x inner-ninja product got worse, not better (128 x -j1 where main was 5 x -j12)

None of those are hard to fix individually, but the smaller version avoids most of them by construction. Happy to be wrong if there's a requirement I'm missing — is there a case where the per-site policies (FlyDSL's 64-worker ceiling, build_co.py's cpu_count()//8, pa_gluon's 32 GPU-resident processes) genuinely need to be unified under one number rather than just corrected in place?

Separately and independently of the scope question: the two build-breaking items in the review (the cpp_extension import that breaks blob-gen subprocesses, and the list(executor.map(...)) change that makes all five AOT drivers raise on an unpicklable ctypes pointer) are worth fixing regardless of which direction this goes.

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

@valarLip Thank you for the review! You brought up several bugs in the implementation. I will address them one by one as I read through them.

The policy cancels its own guarantees

3. aiter_worker_limits.py:209 — the auto-computed value is written into AITER_MAX_JOBS, which lines 197-206 then treat as an explicit expert override that bypasses both caps.

Live:

first  = get_worker_count()          # -> 204, and os.environ["AITER_MAX_JOBS"] == "204"
w._cpu_worker_cap = lambda: 2        # crush the CPU budget
second = get_worker_count()          # -> 204   (expected 2)

Base did the opposite: aiter/jit/core.py:621-643 recomputed cpu_count and psutil availability on every call and clamped down. Concretely, setup.py:412 calls get_worker_count() on an idle host → 204 is exported; the FlyDSL AOT phase then consumes tens of GB; every later JIT/ninja build in that process, and in every spawned child, reads 204 as "explicit" and skips the memory check entirely. Same in a long-lived vLLM/SGLang process, and a child under a tighter cpuset/cgroup skips its own caps. This structurally cancels the memory cap the PR exists to add. Suggest keeping the computed value in a module-level cache rather than in the environment, and exporting a different variable for children if propagation is the goal.

This is a state problem that is out of scope of this PR. We don't have (or need):

  1. Who is spawning (parent) who
  2. By how many children is the fan-out
  3. The width/depth is unknown.
  4. There is no process global tracker of fan-ed out workers alive/existed counter.

So this pr simplifies policy to:

  • Establish one bounded top-level aiter fanout budget.
  • Propagate that budget instead of independently recalculating it throughout the process tree.
  • For aiter controlled process-pool children, explicitly force nested compiler fanout to one.

The primary goal here is also not maximizing compiler throughput. It is preventing relatively short-lived aot jit compilation from creating unbounded fanout and ooming which is a much worser outcome and highly likely in base than slower but mostlly one-time compile before inference begines.

PR documents that overriding AITER_MAX_JOBS externally is unsafe.

@Qubitium

Qubitium commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author
  1. :145 — the cgroup budget counts reclaimable page cache as used.

Remaining is limit - memory.current (v2) / limit - memory.usage_in_bytes (v1). Both counters include page cache and > > reclaimable slab, and memory.stat is never opened (grep confirms zero references). On this host memory.current is > 1.354 TB, of which inactive_file + active_file + slab_reclaimable = 92.8%; only ~91 GB is anon. In a CI container with a > finite memory.max that has just cloned the repo and hipified sources, limit - current is a few GB → max(1, avail // > 1_500_000_000) gives 1-2 workers, and PREBUILD_THREAD_NUM, ninja -j, get_max_workers and every AOT pool all > serialize silently, getting worse the longer the container runs. The correct bound is limit - (usage - > reclaimable_file_and_slab).

Page cache/buffer are often not released by Linux kernel on time. We should be conservative here. On many systems, page/buffer can be over 40% of the os memory but more often than not, they are released when it is too late (swap triggered stalls).

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author
  1. :197 — an explicit AITER_MAX_JOBS bypasses every safety cap, and this PR sets it to 64 in five workflows.

Base clamped down: if max_processes > max_jobs: os.environ["MAX_JOBS"] = str(max_jobs), and _get_num_workers >clamped against max(1, cpu_count*0.8). After the rename, all five of aiter-test.yaml:24, atom-test.yaml:260, vllm->disagg-ci-smoke-workflow.yaml:45, kimi-perf-downstream.yaml:96, kimi-downstream.yaml:112 set >AITER_MAX_JOBS=64 unconditionally — what used to be a ceiling hint is now a cap bypass. On a smaller runner, or in a >32 GB memory cgroup, 64 × 1.5 GB estimated RSS = 96 GB → an OOM-killed build where the old code would have >clamped. For a PR titled around bounding fanout, this removes the one bound that existed. Consider clamping an >explicit value to the auto budget with a warning, rather than documenting it as an unsafe override.

I set the CI to 64 because that's was base value. Ci can override this value because I believe your CI is >= 128 cores so this is safe. Only override AIDER_MAX_JOBS when the env is known and pre-deiminated. PR has added doc warnigs about unsafe usage of AITER_MAX_JOBS

I will remove the CI static set 64 value that mirrors base.

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

#14 — “Generic MAX_JOBS is now silently ignored, with no deprecation path.”

This was by design. Compat code bloat should be avoided since this PR documents that this is a feature, not compat bug. AITER should not read or override parent (sglang/vllm) MAX_JOBS full-stop since since they may use it for their own aot/jit compilers outside of AITER scope and how MAX_JOBS is genearted is unknown. Aiter should avoid outside noise and do it's own thing.

@valarLip

valarLip commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

MAX_JOBS

it's not only aiter but also sgl/vllm, all are using “MAX_JOBS”, instead of SGLANG_MAX_JOBS or VLLM_MAX_JOBS, why aiter need AITER_MAX_JOBS ?

@Qubitium

Qubitium commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

#10 — “aiter/utility/mp_tuner.py:27 — a compiler-fanout policy is installed as the GPU tuning pool's initializer, pinning JIT builds to -j1.”

Also by design so trying to turn this potential fan-out:

8 GPU tuner processes
× 25 compiler workers each
= 200 compiler workers

into this

8 GPU tuner processes
× 1 compiler workers each
= 8 compiler workers

@valarLip

valarLip commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

#10 — “aiter/utility/mp_tuner.py:27 — a compiler-fanout policy is installed as the GPU tuning pool's initializer, pinning JIT builds to -j1.”

Also by design so trying to turn this potential fan-out:

8 GPU tuner processes × 25 compiler workers each = 200 compiler workers

into this

8 GPU tuner processes × 1 compiler workers each = 8 compiler workers

this is aiter's design to fanout to use more cpu core for speed up compile

@Qubitium

Qubitium commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

MAX_JOBS

it's not only aiter but also sgl/vllm, all are using “MAX_JOBS”, instead of SGLANG_MAX_JOBS or VLLM_MAX_JOBS, why aiter need AITER_MAX_JOBS ?

Agree that not using something global/universal like MAX_JOBS seems strange but aiter is a aot/jit compiler that sits inside a user-space program like sgalng/vllm that is thread-light, not thread-heavy like a compiler. Aiter is especially sensitive due to it's fan-out/threads so it needs dedicated control.

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

MAX_JOBS

it's not only aiter but also sgl/vllm, all are using “MAX_JOBS”, instead of SGLANG_MAX_JOBS or VLLM_MAX_JOBS, why aiter need AITER_MAX_JOBS ?

Agree that not using something global/universal like MAX_JOBS seems strange but aiter is a aot/jit compiler that sits inside a user-space program like sgalng/vllm that is thread-light, not thread-heavy like a compiler. Aiter is especially sensitive due to it's fan-out/threads so it needs dedicated control.

#10 — “aiter/utility/mp_tuner.py:27 — a compiler-fanout policy is installed as the GPU tuning pool's initializer, pinning JIT builds to -j1.”

Also by design so trying to turn this potential fan-out:
8 GPU tuner processes × 25 compiler workers each = 200 compiler workers
into this
8 GPU tuner processes × 1 compiler workers each = 8 compiler workers

this is aiter's design to fanout to use more cpu core for speed up compile

I fully understand this. But at what cost. 1TB model crashed because Aiter wanted one time faster 2s compile?

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

MAX_JOBS

it's not only aiter but also sgl/vllm, all are using “MAX_JOBS”, instead of SGLANG_MAX_JOBS or VLLM_MAX_JOBS, why aiter need AITER_MAX_JOBS ?

Agree that not using something global/universal like MAX_JOBS seems strange but aiter is a aot/jit compiler that sits inside a user-space program like sgalng/vllm that is thread-light, not thread-heavy like a compiler. Aiter is especially sensitive due to it's fan-out/threads so it needs dedicated control.

#10 — “aiter/utility/mp_tuner.py:27 — a compiler-fanout policy is installed as the GPU tuning pool's initializer, pinning JIT builds to -j1.”

Also by design so trying to turn this potential fan-out:
8 GPU tuner processes × 25 compiler workers each = 200 compiler workers
into this
8 GPU tuner processes × 1 compiler workers each = 8 compiler workers

this is aiter's design to fanout to use more cpu core for speed up compile

I fully understand this. But at what cost. 1TB model crashed because Aiter wanted one time faster 2s compile?

@valarLip Again, I understand the goal and would like to actually address the compilation performance goal end goal of Aiter but it not in the scope of this PR. First, we fix the out of bound thread growth in hostile envs. Then we design a progress global worker take/put token system (or something like it) so we can track show many threads/processes have spawned and in compile due to fan-out.

Btw, I have another PR wip that will address some of the AIIT compilation speed issues.

@Qubitium

Qubitium commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author
  1. :202 — a malformed or empty AITER_MAX_JOBS now raises on the runtime JIT path.

Skip

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

#13 — “csrc/opus_gemm/gen_co/build_co.py:481 — the deliberately conservative hipcc fanout is replaced by the global budget, and --jobs/-j is deleted.”

I think we need some telemtry on this. I am not sure if I hit OPUS so PR code may actually cause oom since it may give opus more threads and a looser 1.5GB guard than base's tigher 2GB assumption. I think this part is where some telemtry can happen to see what happens in the real world.

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

#13 — “csrc/opus_gemm/gen_co/build_co.py:481 — the deliberately conservative hipcc fanout is replaced by the global budget, and --jobs/-j is deleted.”

I think we need some telemtry on this. I am not sure if I hit OPUS so PR code may actually cause oom since it may give opus more threads and a looser 1.5GB guard than base's tigher 2GB assumption. I think this part is where some telemtry can happen to see what happens in the real world.

First telemetry is back. This PR is faster than base by 5x for test OPUS run on a 24 core VM withgfx1250 offline OPUS path

Second telemtry back:

image

Result, this PR does not enhance or regress OPUS compilation speed.

main’s old default launched 3 hipcc/clang chains, peaked at ~0.64 GiB aggregate sampled RSS, and took 86.6 s; the PR launched 19 chains, peaked at ~3.63 GiB, and took 14.8 s.
No OOM occurred. I’m doing one final PR run at 10 ms sampling to tighten the peak estimate rather than relying on the earlier 100 ms sample.

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

#6 — “:40 — the psutil failure path floors the budget at exactly one worker, and the except tuple is too narrow.”

Pushed more generic Exception catch.

If a syscall failed, it is more likely than not, it is catastraphic so we should stick to 1 thread for safety.

@Qubitium

Qubitium commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Suggested smaller scope

Both defects are fixable in roughly 15 lines, in one shared helper replacing those two copies:

  • raise the per-job estimate from 0.5 GB to ~1.5 GB
  • derive available memory as min(psutil.available, cgroup_limit - anon_usage), where anon_usage comes from memory.stat (i.e. memory.current minus inactive_file + active_file + slab_reclaimable); fall back to psutil when no finite cgroup limit is readable
  • keep the existing clamp-down semantics for MAX_JOBS

raise the per-job estimate from 0.5 GB to ~1.5 GB

This was already done by PR

  • derive available memory as min(psutil.available, cgroup_limit - anon_usage), where anon_usage comes from memory.stat (i.e. memory.current minus inactive_file + active_file + slab_reclaimable); fall back to psutil when no finite cgroup limit is readable

As stated in later comments, you cannot rely on Linux kernel to free those free able memory, in time. It's too late. You must count them as unrecoverable (as in unrecoveratable in time to cause swap stall). Once the oom triggers, kernel is in catch 22. It must honor alloc request or start killing user-space process which is just as bad as killing vllm/sglang in this production env (think ssh, shell, tmux).

keep the existing clamp-down semantics for MAX_JOBS

Also addressed. This is by design. This PR is designed to fix by ignoring incorrectly ctxed MAX_JOBS clamp, not use it. Parent (sglang/vllm) uses it in it's own ctx so Aiter should not.

@Qubitium

Qubitium commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Fanout regressions
9. setup.py:370 — PREBUILD_THREAD_NUM loses its hard cap of 5, inverting the build shape.

No regression found in telemetry. Actually I just removed unnecessary PREBUILD_THREAD_NUM micro-optimization. Tests show PR is just as good as base if not better. f1f3099

image

@Qubitium

Qubitium commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author
  1. aiter/aot/pa.py:101 — consuming the executor.map iterator turns all five AOT drivers into hard failures.

process_config ends at csrc/cpp_itfs/utils.py:320 return run_lib(func_name, folder) → :277 return getattr(lib, > func_name), i.e. a ctypes _FuncPtr, which cannot be pickled back to the parent:

Fixed. This bug was already in but hidden in base but revealed by PR by consuming the result of the workers. b61af1c

zhiding512
zhiding512 previously approved these changes Oct 13, 2026

@zhiding512 zhiding512 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@zufayu

zufayu commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

CI note: the failing Flash Attention job does not appear to be caused by this PR. It crashes on the glm47fp8-tp4 ... d=53 bwd_varlen case with the same read-only-page GPU fault seen on recent main runs on October 8 and 10. Since this PR does not touch Flash Attention, I do not think a code change is needed here; this check should be rerun or waived after the baseline issue is addressed. The remaining Standard and OPUS jobs are still queued or running.

@zufayu
zufayu dismissed valarLip’s stale review October 13, 2026 07:47

The requested changes have been addressed in subsequent commits, and the PR has since been re-reviewed and approved.

zufayu
zufayu previously approved these changes Oct 14, 2026
@zufayu

zufayu commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

The latest main now has a real merge conflict with this branch in aiter/jit/utils/cpp_extension.py after #5166 was merged. Please merge or rebase the current main and resolve it, preserving both #5166's rocPRIM diagnostic changes and this PR's worker-limit changes. The approvals will need to be refreshed after the push.

Preserve the shared worker budget alongside upstream ROCm header diagnostics and compiler selection helpers.

Validation: 186 focused tests and 79 subtests passed across worker policy, source entrypoints, AOT drivers, JIT cache transactions, and ROCm header diagnostics. Black, Ruff, shell syntax, and git diff --check passed.
@Qubitium
Qubitium dismissed stale reviews from zufayu and zhiding512 via 413caca October 14, 2026 02:53
@Qubitium
Qubitium requested a review from zufayu October 14, 2026 03:00
@zufayu

zufayu commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

CI is now blocked by the same deterministic failure in both the MI35X and MI300X Standard Test shard 1 jobs:

test_flydsl_aot_pool_honors_explicit_worker_budget patches AITER_FLYDSL_AOT_WORKERS=7 and expects common.get_max_workers(23) == 7, but this PR replaces the FlyDSL-specific worker knob with the unified AITER_MAX_JOBS policy. The test therefore gets the automatic budget of 23 and fails with AssertionError: 23 != 7.

Please update this test to use AITER_MAX_JOBS=7 (and adjust its wording if appropriate), then rerun CI. The separate Flash Attention MI35X GPU fault is the known failure reproducible on main.

@Qubitium

Copy link
Copy Markdown
Contributor Author

@zufayu Done. Need to wait for Ci to pass

Keep the focused regression suite's pytest dispatch alongside main's
FHMoE pytest entries in aiter_test.sh, and carry main's FlyDSL MoE
arch/clamp changes together with the shared worker budget.

Validation: 106 worker-policy/entrypoint tests and 6 subtests passed
(one affinity test is Linux-only); bash -n, py_compile, and
git diff --check pass.
zufayu
zufayu previously approved these changes Oct 16, 2026
@zufayu

zufayu commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

#6608 has now merged into main and fixes the GLM-4.7 benchmark head dimension (128 instead of the derived value 53). This appears to address the MI35X Flash Attention failure seen in the current CI run.

The current CI results on this PR predate that fix. When convenient, could you merge the latest main into this branch and trigger a fresh CI run? The approval may need to be refreshed after the branch update.

Conflict resolutions:
- aiter/aot/flydsl/gemm.py: keep upstream's MXFP8_ROW_SCALES_BY_W_SCALE_BLOCK
  rename and parse_csv rewrite; keep our adopt_legacy_max_jobs import and its
  call in __main__.
- aiter/jit/core.py: drop upstream's check_and_set_ninja_worker together with
  its threading import and _MAX_JOBS_LOCK/_LAST_AUTO_MAX_JOBS globals; the
  worker budget lives in aiter_worker_limits on this branch.
- aiter/jit/utils/cpp_extension.py: keep our _get_num_workers built on
  get_compile_worker_count(); upstream's MAX_JOBS/PREBUILD_THREAD_NUM body is
  superseded by the shared worker budget.
- op_tests/test_jit_cache_transaction.py: drop upstream's TestNinjaWorkerLimit,
  which exercised the removed check_and_set_ninja_worker, and rewrite its new
  worker-count test to the shared-budget contract (AITER_MAX_JOBS ceiling,
  legacy MAX_JOBS as a bounded ceiling, never zero workers).
@Qubitium

Copy link
Copy Markdown
Contributor Author

@zufayu The current Ci fail looking like has nothing to do with this PR. memory access issue during micro kernel bench may be related to bad kernel code

[272/380] glm47fp8-ep4 B=32 HQ=96 HK=8 sq=256 sk=256 d=53 fwd_varlen bf16 causal=True window=(1024,0) (0.2GB)
[273/380] glm47fp8-ep4 B=32 HQ=96 HK=8 sq=256 sk=256 d=53 bwd_varlen bf16 causal=True (0.4GB)
Memory access fault by GPU node-2 (Agent handle: 0xda4fb90) on address 0x7e891cae1000. Reason: Write access to a read-only page.
GPU coredump: execvp failed: No such file or directory
Failed to write segment data to pipe: Bad address
GPU coredump: handler exited with error (status: 1)
GPU core dump failed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants