Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub 716d1cfac8 feat(orchestrator): optional length-weighted GRPO baseline (#3789)
Adds `length_weighted_baseline: bool = False` to `GRPOAlgoConfig`.

When enabled, the GRPO group baseline is the token-length-weighted mean
reward `b = sum_i(L_i * r_i) / sum_i(L_i)` instead of the plain mean.
`L_i` is the number of trainable (mask-True, policy-sampled) tokens of
rollout `i`, summed across all turns. Advantage is `r_i - b`. The
baseline is applied after the length penalty, same as the plain mean.
There is no fallback for a group with zero trainable tokens: then every
trace has `L_i = 0`, so `assign_advantages` writes no tokens, and no
metric, annotation or sample reads the (NaN) baseline.

Why: with token-level loss normalization, long rollouts carry more
gradient weight. A length-weighted baseline makes the per-token
advantage zero-mean across the group's tokens instead of across
rollouts.

- `routing.py`: pulls the trainable-node selection out of
`assign_advantages` into `trainable_nodes(trace)`, so `L_i` counts
exactly the tokens that receive the advantage.
- `echo` inherits the option because it subclasses GRPO.
- With the flag off, results are bit-identical to today: same `rewards -
rewards.mean()` computation.
- No breaking changes.

## Validation
- `pytest tests/unit/orchestrator tests/unit/test_configs.py -m "not
gpu"`: 301 passed. Includes the new
`test_grpo_length_weighted_baseline`, which covers the flag alone and
the flag combined with the length penalty (ordering).
- `ruff check .` and `ruff format --check .`: clean.
- GPU and integration tests were not run (no GPU on this machine).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in GRPO baseline change with default off; touches advantage math
only on the orchestrator scoring path, with targeted unit tests.
> 
> **Overview**
> Adds an opt-in **`length_weighted_baseline`** flag on GRPO-family
config (`GRPOAlgoConfig`, inherited by `echo`). When enabled, the group
baseline becomes the trainable-token-weighted mean of
(length-penalty-)shaped rewards instead of a plain rollout mean, so
advantages are **zero-mean per token** rather than per rollout—aligned
with token-normalized RL loss when long completions dominate gradient
mass.
> 
> **`GRPOAlgorithm.score_group`** now computes `shaped_rewards` first,
then either `mean(shaped_rewards)` or `sum(L_i * r_i) / sum(L_i)` with
`L_i` counting mask-True policy tokens across turns.
**`routing.trainable_nodes`** is extracted so `L_i` matches the tokens
that receive broadcast advantages via `assign_advantages`. Default
`false` preserves the existing centered-mean behavior.
> 
> Docs describe the math and ordering (after length penalty). Unit tests
cover the flag alone and combined with linear length penalty.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8f8d988d4957d02e61f28dfe0e46b1af3fefab7d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 14:00:33 -07:00
faresobeidandGitHub 87766fda3c refactor(launcher): share local launch-and-monitor code between rl and sft (#3792)
Unifies the local launch-and-monitor code in `rl_local` and `sft_local`.
Before this PR, both repeated the same machinery: Popen → log file →
monitor thread → error queue → SIGTERM/Ctrl-C/exception cleanup, GPU
partitioning from `CUDA_VISIBLE_DEVICES`, and the trainer torchrun
command. Each copy had small differences, which made the two launchers
drift.

## Design
`utils/process.py` already holds the launcher primitives
(`monitor_process`, `cleanup_processes`, env defaults). This PR adds
three small pieces there:
- `ProcessGroup`: a context manager. `start(name, cmd, env, log_path)`
starts a process with its log file and monitor thread. `wait(*names)`
blocks until the named processes exit and fails fast (exit 1) on the
first error from any process. SIGTERM, Ctrl-C, exceptions and normal
exit all clean up every process. The messages and ordering are the same
as the old inline code.
- `partition_gpus(num_infer, num_train)`: splits the physical GPUs into
inference GPUs followed by trainer GPUs, and raises the same
`ValueError` as before.
- `torchrun_cmd(module, config_path, nproc, log_dir, ranks_filter)`: the
shared single-node trainer command.

`rl_local` and `sft_local` keep their own commands and env dicts
unchanged. Only the plumbing moves. Net: −126 lines.

`inference.py` is not changed. Its only subprocess is the vllm-router.
The router inherits stdout (no log file), and its watcher SIGTERMs the
inference process itself. That does not fit the start/monitor/fail-fast
pattern, and forcing it in would change behavior. `eval.py` env servers
are also unmonitored on purpose, so they stay as they are. SLURM
rendering is not touched.

## Behavior
Behavior is the same: commands, env vars (including key order), log
paths, start order, kill order, exit codes and info/warning/error logs.
Two small differences:
- rl `--log-level debug` "command" lines now read `Inference command:
...` / `Train env server <name> command: ...` / `Trainer command: ...`
instead of `... start command: ...`.
- The rl wait loop is now the sft one: it checks errors before it checks
completion. Before, if the trainer failed *after* the orchestrator had
already exited, rl logged `Trainer failed with exit code N` from a
post-loop check. Now it logs `Error: Trainer failed with exit code N` /
`Terminating all processes...`. The exit code (1) and cleanup are the
same. The post-loop returncode checks could no longer be reached, so
they are removed. Side effect: if inference or an env server crashes in
the last ~1s, when the trainer and orchestrator also finish, the run now
fails instead of being ignored.

No config, metric, or checkpoint changes. No breaking changes.

## Validation
- I ran a throwaway (uncommitted) script against `rl_local`/`sft_local`,
once on `origin/main` and once on this branch, and diffed the results.
It fakes `subprocess.Popen` and `cleanup_process`, pins the free port,
uuid and `CUDA_VISIBLE_DEVICES=3,5,6,7`, and records each launch's exact
cmd, env delta, log path, kill sequence, exit code and logs. Configs:
reverse-text `rl.toml`, `configs/debug/multi-env/rl.toml`, reverse-text
`sft.toml` (online eval + inference), `configs/debug/fake/sft.toml`.
Scenarios: success;
trainer/orchestrator/inference/env-server/online-eval failure; trainer
failing after the orchestrator exits; SIGTERM; SIGINT; too many GPUs
requested. All records and exit codes were identical. The only log
differences are the two listed above.
- `pytest tests/unit -m "not gpu"`: 683 passed, 1 failed. The failure is
`test_cpu_adam.py::test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients`,
which also fails on `origin/main` on this machine.
- `ruff check .` and `ruff format --check .` pass.
- No GPU on this machine, so I did not run any real launch or
integration test.

## Reviewer GPU checks (not run here)
- rl reverse-text e2e exits 0, and inference/env servers have no late
non-zero exits.
- SIGTERM and Ctrl-C mid-run leave no vLLM or torchrun workers.
- Trainer and inference logs are unchanged.
- sft with online eval waits for the eval to drain before it exits.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core multi-process launcher lifecycle (spawn, monitor,
teardown) for training runs; behavior is mostly preserved but wait/error
ordering changes can alter exit outcomes at run end.
> 
> **Overview**
> **Refactors local RL and SFT launchers** so they no longer duplicate
subprocess orchestration; shared behavior lives in
`prime_rl.utils.process`.
> 
> Adds **`ProcessGroup`** (context manager with `start` / `wait`),
**`partition_gpus`**, and **`torchrun_cmd`**. Both `rl` and `sft`
entrypoints now start inference, env servers, orchestrator/online-eval,
and trainer through `ProcessGroup` instead of inline `Popen`, monitor
threads, error queues, and hand-rolled SIGTERM/Ctrl-C cleanup.
> 
> Commands, env vars, log paths, and start order are intended to stay
the same. **Minor differences:** debug log lines drop the `"start"`
prefix on command logs; RL’s wait loop now checks the error queue before
completion (aligned with SFT), so late failures from non-terminal
processes (e.g. inference/env server in the last second) can fail the
run where RL previously might have exited successfully.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fb27b22cf76aa28b094caedb07a646b7d5db7c7e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:53:33 -07:00
faresobeidandGitHub 73c4736352 refactor: move packing to orchestrator, DSv4 eager reference to tests, inline conversion_utils (#3785)
Pure moves + import updates. No logic change.

**Design / target structure**
- `trainer/batch.py` -> `orchestrator/batch.py`. Only
`orchestrator/packing.py` uses it. Nothing in `trainer/` imports it. Its
test already lives at `tests/unit/orchestrator/test_batch.py`.
- `trainer/models/deepseek_v4/eager_reference.py` ->
`tests/unit/train/models/deepseek_v4_eager_reference.py`. Only the DSv4
tests import it. Its docstring says nothing in production calls it.
- `trainer/conversion_utils.py` (one 10-line function) is inlined into
`transports/weights/nccl.py`, its only user.

**Left as is (not equivalent)**
- FLOPs models: `orchestrator/batch.py` (forward-cost coefficients for
bin balancing) and `trainer/perf.py` `_get_num_flop_per_token` (train
FLOPs for MFU, LoRA-aware) give different numbers. For example, o_proj
is `2*h*h` vs `h*heads*head_dim`, router params are counted only in
perf, and attention uses `head_dim` vs `h/heads`. On Qwen3-0.6B/1.7B,
Qwen3-VL-4B, Qwen3.5-2B and debug-moe they differ by 4-11%, so merging
them would change either the packing or the MFU metric.
- `list_shards` duplicate in `tools/convert_fp8_to_bf16.py` and
`tools/convert_bf16_to_fp8.py`: kept so `convert_fp8_to_bf16.py` stays
standalone (torch + safetensors only, no `prime_rl` import).
- Blockwise FP8 dequant: the tools version takes the block size from
`quantization_config` and handles shapes that are not multiples of the
block (via ceil + slice). The DSv4 version infers the block size from
the shape ratio, needs exact divisibility, and also handles MXFP4. They
are not interchangeable.
- `tools/convert_dcp_to_fp8.py` sibling imports: these already work from
the repo root and from any cwd. Python puts the script's directory on
`sys.path`, and the same holds under `torchrun`. I checked `--help` from
the repo root and from `/tmp`. No change needed.

**Breaking changes**
- Import paths: `prime_rl.trainer.batch` ->
`prime_rl.orchestrator.batch`. `prime_rl.trainer.conversion_utils` and
`prime_rl.trainer.models.deepseek_v4.eager_reference` are removed from
the package.

**Validation**
- `pytest tests/unit/orchestrator/test_batch.py
tests/unit/train/models/test_deepseek_v4_cpu.py
tests/unit/train/models/test_deepseek_v4.py
tests/unit/train/models/test_deepseek_v4_kernels.py
tests/unit/transports tests/unit/train/test_perf.py -m "not gpu"`: 31
passed, 97 deselected. Both DSv4 test modules import fine. No GPU on
this machine, so the GPU DSv4 tests and integration tests were not run.
- `ruff check .` and `ruff format --check .` both pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Import-path-only refactor with inlined helper code; no training,
packing, or NCCL broadcast logic changes, aside from downstream breakage
if anything still imports the removed modules.
> 
> **Overview**
> This PR reorganizes modules so orchestrator-only, test-only, and
single-use code no longer lives under `trainer/`. **Batch packing**
moves from `prime_rl.trainer.batch` to `prime_rl.orchestrator.batch`,
with `packing.py` and orchestrator unit tests updated to the new import
path.
> 
> **DeepSeek V4 eager reference** implementations move out of the
production package into
`tests/unit/train/models/deepseek_v4_eager_reference.py`; DSv4 GPU tests
import from there instead of
`prime_rl.trainer.models.deepseek_v4.eager_reference`.
> 
> **Layer counting for NCCL weight broadcast** drops the standalone
`trainer/conversion_utils.py` module: `get_max_layer_num` is defined
inline in `transports/weights/nccl.py`, its only caller. Behavior is
unchanged; callers must switch imports for batch and remove use of the
deleted trainer modules.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9287ae8ce22ba8731b80ebc1634ee0d5bbb25ea3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-03 13:42:11 -07:00
16 changed files with 263 additions and 347 deletions
+2
View File
@@ -325,6 +325,8 @@ type = "grpo"
type = "linear"
```
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
### Hierarchical GRPO
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
@@ -208,6 +208,9 @@ class GRPOAlgoConfig(BaseAlgoConfig):
length_penalty: LengthPenaltyConfig | None = None
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
length_weighted_baseline: bool = False
"""Use the token-length-weighted group mean reward ``sum_i(L_i * r_i) / sum_i(L_i)`` as the baseline instead of the plain mean, where ``L_i`` is the number of trainable (mask-True, policy-sampled) tokens of rollout ``i`` summed across all its turns."""
class EchoAlgoConfig(GRPOAlgoConfig):
type: Literal["echo"] = "echo" # type: ignore[assignment]
+62 -216
View File
@@ -1,13 +1,9 @@
import json
import os
import signal
import subprocess
import sys
import time
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
from prime_rl.configs.algorithm import FrozenModelConfig
@@ -35,11 +31,10 @@ from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
ProcessGroup,
partition_gpus,
set_proc_title,
torchrun_cmd,
)
RL_CONFIG = "rl.json"
@@ -141,25 +136,9 @@ def rl_local(config: RLConfig):
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
infer_gpu_ids, trainer_gpu_ids = partition_gpus(num_infer_gpus, config.deployment.num_train_gpus)
logger.info(f"Using local->physical GPU mapping: {dict(enumerate(infer_gpu_ids + trainer_gpu_ids))}")
start_command = sys.argv
logger.debug(f"RL start command: {' '.join(start_command)}")
@@ -185,53 +164,22 @@ def rl_local(config: RLConfig):
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
try:
# Optionally, start inference process
with ProcessGroup() as processes:
if config.inference:
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.log", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
processes.start(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
log_path=log_dir / "inference.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No [inference] block configured - the policy inference server will not be started here. "
@@ -259,167 +207,65 @@ def rl_local(config: RLConfig):
# orchestrator start in parallel.
for split, source in env_servers(config):
name = source.resolved_name
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
logger.info(f"Starting {name} server")
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
env_server_log.parent.mkdir(parents=True, exist_ok=True)
with open(env_server_log, "w") as log_file:
env_server_process = Popen(
env_server_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**config.env_vars,
**config.orchestrator.env_vars,
},
stdout=log_file,
stderr=log_file,
)
processes.append(env_server_process)
# Start monitoring thread
stop_event = Event()
stop_events[f"env/{split}/{name}"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
daemon=True,
processes.start(
f"{split} env server {name}",
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
logger.info("Starting orchestrator")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.log", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
processes.start(
"orchestrator",
["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.orchestrator.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "orchestrator",
},
log_path=log_dir / "orchestrator.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.trainer.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / TRAINER_CONFIG).as_posix(),
]
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.log", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
processes.start(
"trainer",
torchrun_cmd(
"prime_rl.trainer.rl.train",
config_dir / TRAINER_CONFIG,
len(trainer_gpu_ids),
log_dir,
config.trainer.log.ranks_filter,
),
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
**config.env_vars,
**config.trainer.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "trainer",
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
},
log_path=log_dir / "trainer.log",
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Trainer and orchestrator completion is the successful stop condition.
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
while not all(event.is_set() for event in completion_events):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
processes.wait("trainer", "orchestrator")
logger.success("Training finished!")
# Cleanup threads and processes
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
+25 -101
View File
@@ -1,12 +1,9 @@
import json
import os
import signal
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.eval import SFTOnlineEvalConfig
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
@@ -34,11 +31,10 @@ from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
ProcessGroup,
partition_gpus,
set_proc_title,
torchrun_cmd,
)
SFT_CONFIG = "sft.json"
@@ -333,21 +329,14 @@ def sft_local(config: SFTConfig):
)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
# Partition GPUs (inference first, then the trainer) only when the launcher must split
# them between processes; plain SFT leaves them to torchrun.
infer_gpu_ids: list[int] = []
trainer_gpu_ids: list[int] = []
if config.inference is not None:
num_infer_gpus = config.deployment.num_infer_gpus
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
)
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
@@ -364,37 +353,11 @@ def sft_local(config: SFTConfig):
"WANDB_ARGS": json.dumps(sys.argv),
}
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
processes.append(process)
stop_event = Event()
stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
monitor_thread.start()
monitor_threads.append(monitor_thread)
return process
try:
with ProcessGroup() as processes:
# Optionally, start the inference server for online evals
if config.inference is not None:
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
start_process(
processes.start(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
@@ -413,7 +376,7 @@ def sft_local(config: SFTConfig):
for source in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting {name} server")
start_process(
processes.start(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
@@ -422,7 +385,7 @@ def sft_local(config: SFTConfig):
if config.eval is not None:
logger.info("Starting online evals")
start_process(
processes.start(
"online-eval",
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
env={
@@ -439,23 +402,6 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "eval.log",
)
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_train_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
config_path.as_posix(),
]
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
trainer_env = {
@@ -470,48 +416,26 @@ def sft_local(config: SFTConfig):
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
if trainer_gpu_ids:
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
processes.start(
"trainer",
torchrun_cmd(
"prime_rl.trainer.sft.train",
config_path,
config.deployment.num_train_gpus,
log_dir,
config.log.ranks_filter,
),
env=trainer_env,
log_path=log_dir / "trainer.log",
)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the online-eval process, which drains its final evals
# after the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "online-eval" in stop_events:
terminal_events.append(stop_events["online-eval"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
logger.error(f"Error: {error_queue[0]}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if not pending:
break
pending[0].wait(timeout=1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
logger.success("SFT training finished!")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
+10 -3
View File
@@ -6,7 +6,7 @@ import verifiers.v1 as vf
from prime_rl.configs.algorithm import GRPOAlgoConfig
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
from prime_rl.orchestrator.algo.routing import assign_advantages
from prime_rl.orchestrator.algo.routing import assign_advantages, trainable_nodes
if TYPE_CHECKING:
from prime_rl.orchestrator.clients import InferenceClient
@@ -20,6 +20,7 @@ class GRPOAlgorithm(Algorithm):
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
super().__init__(config, clients)
self.length_penalty = config.length_penalty
self.length_weighted_baseline = config.length_weighted_baseline
async def score_group(self, episodes: list[vf.Episode]) -> None:
import torch # only the trainer-side extras ship torch; an eval process never scores a group
@@ -28,7 +29,7 @@ class GRPOAlgorithm(Algorithm):
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
length_penalty = self.length_penalty
if length_penalty is None:
advantages = rewards - rewards.mean()
shaped_rewards = rewards
else:
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
@@ -41,6 +42,12 @@ class GRPOAlgorithm(Algorithm):
)
penalty = rewards.mean() * penalty_frac
shaped_rewards = rewards - penalty
advantages = shaped_rewards - shaped_rewards.mean()
baseline = shaped_rewards.mean()
if self.length_weighted_baseline:
lengths = torch.tensor(
[sum(sum(node.mask) for node in trainable_nodes(trace)) for trace in traces], dtype=rewards.dtype
)
baseline = (lengths * shaped_rewards).sum() / lengths.sum()
advantages = shaped_rewards - baseline
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
+7 -2
View File
@@ -8,10 +8,15 @@ from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transports.batch import TrainingSample
def trainable_nodes(trace: vf.Trace) -> list[vf.MessageNode]:
"""Nodes with sampled (mask-True) tokens on the trace's trainable branches, in graph order."""
on_trainable_branch = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
return [node for node in trace.nodes if id(node) in on_trainable_branch and any(node.mask)]
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
"""Assign credit in compact sampled-token order across trainable graph paths."""
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
nodes = trainable_nodes(trace)
for node in nodes:
if len(node.mask) != len(node.token_ids):
raise ValueError(
+1 -1
View File
@@ -1,7 +1,7 @@
from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.orchestrator.batch import build_bin_cost, prepare_batch
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
-13
View File
@@ -1,13 +0,0 @@
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
+12 -1
View File
@@ -11,7 +11,6 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
@@ -21,6 +20,18 @@ from prime_rl.utils.vlm import get_layer_prefix
from prime_rl.utils.weights import resolve_wire_dtype
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
"""Broadcast an integer to a process group using NCCL communicator."""
integer_tensor = torch.tensor([integer], dtype=torch.long).cuda()
+100
View File
@@ -2,6 +2,9 @@ import contextlib
import os
import signal
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
@@ -44,6 +47,41 @@ def get_physical_gpu_ids() -> list[int]:
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
def partition_gpus(num_infer: int, num_train: int) -> tuple[list[int], list[int]]:
"""Split the launcher's physical GPUs into inference GPUs followed by trainer GPUs."""
physical_gpu_ids = get_physical_gpu_ids()
if num_infer + num_train > len(physical_gpu_ids):
raise ValueError(
f"Requested {num_infer + num_train} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
return physical_gpu_ids[:num_infer], physical_gpu_ids[num_infer : num_infer + num_train]
def torchrun_cmd(
module: str, config_path: Path, nproc_per_node: int, log_dir: Path, ranks_filter: list[int]
) -> list[str]:
"""Single-node torchrun command for a trainer module."""
from prime_rl.utils.utils import get_free_port
return [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={nproc_per_node}",
"-m",
module,
"@",
config_path.as_posix(),
]
def set_proc_title(name: str) -> None:
"""Set the process title for visibility in tools like ``ps`` and ``htop``.
@@ -103,3 +141,65 @@ def monitor_process(process: Popen, stop_event: Event, error_queue: list, proces
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
error_queue.append(RuntimeError(err_msg))
stop_event.set()
class ProcessGroup:
"""Launcher subprocesses, each logging to its own file and watched by a monitor thread.
As a context manager, SIGTERM, Ctrl-C, errors and normal exit all terminate every
started process."""
def __init__(self):
self.processes: list[Popen] = []
self.monitor_threads: list[Thread] = []
self.error_queue: list[Exception] = []
self.stop_events: dict[str, Event] = {}
def __enter__(self) -> "ProcessGroup":
signal.signal(signal.SIGTERM, self._sigterm_handler)
return self
def __exit__(self, exc_type, exc, tb) -> None:
if exc_type is KeyboardInterrupt:
get_logger().warning("Received interrupt signal, terminating all processes...")
elif isinstance(exc, Exception):
get_logger().error(f"Error occurred: {exc}")
self.cleanup()
if exc_type is KeyboardInterrupt:
sys.exit(1)
def _sigterm_handler(self, signum, frame):
get_logger().warning("Received SIGTERM, terminating all processes...")
# Clean up here too: a SIGTERM during __exit__'s cleanup would otherwise leave orphans.
self.cleanup()
sys.exit(1)
def cleanup(self) -> None:
cleanup_threads(self.monitor_threads)
cleanup_processes(self.processes)
def start(self, name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> None:
get_logger().debug(f"{name[:1].upper() + name[1:]} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
# If we don't log stdout, the inference server hangs
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
self.processes.append(process)
stop_event = Event()
self.stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, self.error_queue, name), daemon=True)
monitor_thread.start()
self.monitor_threads.append(monitor_thread)
def wait(self, *names: str) -> None:
"""Block until the named processes exit; exit with code 1 as soon as any started process fails."""
events = [self.stop_events[name] for name in names]
while True:
pending = [event for event in events if not event.is_set()]
if self.error_queue:
get_logger().error(f"Error: {self.error_queue[0]}")
get_logger().error("Terminating all processes...")
sys.exit(1)
if not pending:
return
pending[0].wait(timeout=1)
+25 -2
View File
@@ -151,9 +151,11 @@ def _scalar(episode: vf.Episode) -> float:
raise AssertionError("episode has no trainable token")
def _grpo(group: list[vf.Episode], length_penalty=None) -> list[float]:
def _grpo(group: list[vf.Episode], length_penalty=None, length_weighted_baseline=False) -> list[float]:
"""Drive ``GRPOAlgorithm.score_group`` and read back each per-rollout scalar."""
algo = GRPOAlgorithm(GRPOAlgoConfig(length_penalty=length_penalty), clients=None)
algo = GRPOAlgorithm(
GRPOAlgoConfig(length_penalty=length_penalty, length_weighted_baseline=length_weighted_baseline), clients=None
)
asyncio.run(algo.score_group(group))
return [_scalar(episode) for episode in group]
@@ -181,6 +183,27 @@ def test_grpo_singleton_group_is_zero():
assert _grpo([_build_episode(0.7, sampled_lengths=[2])]) == pytest.approx([0.0], abs=1e-6)
def test_grpo_length_weighted_baseline():
# L = [10 + 20 (two turns, observation excluded), 10]: b = (30 * 1 + 10 * 0) / 40 = 0.75
group = [
_build_episode(1.0, sampled_lengths=[10, 20], obs_lengths=[5]),
_build_episode(0.0, sampled_lengths=[10]),
]
advs = _grpo(group, length_weighted_baseline=True)
assert advs == pytest.approx([0.25, -0.75])
# per-token advantage is zero-mean across the group's trainable tokens
assert 30 * advs[0] + 10 * advs[1] == pytest.approx(0.0, abs=1e-6)
# with a length penalty, the weighted baseline applies to the shaped rewards:
# penalty = mean(r) * 0.5 * L / max(L) = [0.25, 1/12], shaped = [0.75, -1/12], b = (30 * 0.75 - 10 / 12) / 40
cfg = LinearLengthPenaltyConfig(num_output_tokens_weight=0.5, num_input_tokens_weight=0.0, num_turns_weight=0.0)
group = [
_build_episode(1.0, sampled_lengths=[10, 20], obs_lengths=[5]),
_build_episode(0.0, sampled_lengths=[10]),
]
advs = _grpo(group, length_penalty=cfg, length_weighted_baseline=True)
assert advs == pytest.approx([0.75 - 65 / 120, -1 / 12 - 65 / 120])
def test_max_rl_mean_normalized():
# mean 0.25: the success gets (1 - 0.25)/0.25 = 3, failures (0 - 0.25)/0.25 = -1
assert _max_rl(_make_group(rewards=[1.0, 0.0, 0.0, 0.0])) == pytest.approx([3.0, -1.0, -1.0, -1.0])
+7 -1
View File
@@ -3,7 +3,13 @@ from types import SimpleNamespace
import numpy as np
import pytest
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
from prime_rl.orchestrator.batch import (
_is_multimodal_sample,
build_bin_cost,
pad_micro_batch,
prepare_batch,
prepare_sample,
)
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, TrainingSample
+2 -1
View File
@@ -8,13 +8,14 @@ from torch import nn
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import load_dcp_from_hf
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM, eager_reference
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.layers import norms
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.utils.utils import default_dtype
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
# Every layer is built through `DeepseekV4Attention.__init__`, which refuses to construct without
# the kernel it would dispatch to, so the whole file needs tilelang even though nothing here calls it.
@@ -8,20 +8,21 @@ import torch
from torch import nn
from torch.utils._python_dispatch import TorchDispatchMode
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_reference
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.eager_reference import (
apply_rotary_pos_emb_interleaved,
dense_mask_from_indices,
eager_attention_with_sinks,
)
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4UnweightedRMSNorm
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
from prime_rl.utils.cp import CPContext
from prime_rl.utils.utils import default_dtype
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
from tests.unit.train.models.deepseek_v4_eager_reference import (
apply_rotary_pos_emb_interleaved,
dense_mask_from_indices,
eager_attention_with_sinks,
)
try:
import tilelang