Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cae5cca73 | ||
|
|
8a6f4ef3bf | ||
|
|
d7afbaa6f3 | ||
|
|
effa509cb3 | ||
|
|
80a52899ea | ||
|
|
12034385ce | ||
|
|
14c0a02653 | ||
|
|
801995a341 | ||
|
|
f725629e47 |
@@ -2,9 +2,13 @@
|
||||
|
||||
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
|
||||
|
||||
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
|
||||
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
|
||||
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
|
||||
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
|
||||
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
|
||||
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
|
||||
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
uv sync --all-extras --group mamba-ssm --locked --no-dev
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --group mamba-ssm --locked --no-dev
|
||||
|
||||
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
|
||||
ARG TARGETARCH
|
||||
|
||||
@@ -62,9 +62,15 @@ class BenchmarkConfig(BaseConfig):
|
||||
|
||||
seq_len: Annotated[int, Field(ge=1, description="Sequence length")] = 512
|
||||
|
||||
ac: Annotated[Literal["Recompute", "Offload", "None"], Field(description="Activation checkpointing type")] = (
|
||||
"Recompute"
|
||||
)
|
||||
ac: Annotated[
|
||||
Literal["Recompute", "Selective", "Offload"] | None,
|
||||
Field(description="Activation checkpointing type"),
|
||||
] = "Recompute"
|
||||
|
||||
selective_targets: Annotated[
|
||||
list[str] | None,
|
||||
Field(description="Selective activation checkpoint targets when ac=Selective"),
|
||||
] = None
|
||||
|
||||
attention: Annotated[
|
||||
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
|
||||
@@ -141,6 +147,10 @@ def build_command(config: BenchmarkConfig) -> list[str]:
|
||||
# Add activation checkpointing if enabled
|
||||
if config.ac == "Recompute":
|
||||
cmd.append("--model.ac")
|
||||
elif config.ac == "Selective":
|
||||
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
|
||||
if config.selective_targets:
|
||||
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
|
||||
elif config.ac == "Offload":
|
||||
cmd.append("--model.ac-offloading")
|
||||
|
||||
|
||||
+7
-5
@@ -55,7 +55,7 @@ flash-attn-3 = [
|
||||
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
]
|
||||
flash-attn-cute = [
|
||||
"flash-attn-cute",
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"reverse-text",
|
||||
@@ -76,7 +76,10 @@ disagg = [
|
||||
"deep-gemm ; platform_machine == 'x86_64'",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
"vllm-router ; platform_machine == 'x86_64'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.3.3",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
@@ -105,16 +108,15 @@ override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"quack-kernels>=0.2.7",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "f5580acd" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "0db45e6" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "5c1c72b" }
|
||||
flash-attn-cute = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "e2743ab5" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "abd9943b" }
|
||||
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
|
||||
vllm-router = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
|
||||
@@ -21,16 +21,18 @@ echo "Creating tmux session: $SESSION_NAME"
|
||||
# Window 0: Terminal
|
||||
tmux new-session -d -s "$SESSION_NAME" -n "Terminal"
|
||||
|
||||
# Window 1: Logs - 3 vertical panes
|
||||
# Window 1: Logs - 4 vertical panes
|
||||
tmux new-window -t "$SESSION_NAME" -n "Logs"
|
||||
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.0"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.1"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.2"
|
||||
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
|
||||
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Inference"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Envs"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.3" -T "Inference"
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.0" \
|
||||
"tail -F ${SLURM_LOG_DIR}/latest_train_node_rank_*.log 2>/dev/null" C-m
|
||||
@@ -38,7 +40,11 @@ tmux send-keys -t "$SESSION_NAME:Logs.0" \
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.1" \
|
||||
"tail -F ${SLURM_LOG_DIR}/latest_orchestrator.log 2>/dev/null" C-m
|
||||
|
||||
ENV_LOG_DIR="${OUTPUT_DIR}/logs/envs"
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
"tail -F ${ENV_LOG_DIR}/*/*/*.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.3" \
|
||||
"tail -F ${SLURM_LOG_DIR}/latest_infer_node_rank_*.log 2>/dev/null" C-m
|
||||
|
||||
# Pane title styling
|
||||
|
||||
+10
-3
@@ -58,23 +58,30 @@ else
|
||||
# Start new tmux session with first window
|
||||
tmux new-session -d -s "$SESSION_NAME" -n "RL"
|
||||
|
||||
# Window 1: RL - 3 vertical panes
|
||||
# Window 1: RL - 4 vertical panes
|
||||
tmux split-window -v -t "$SESSION_NAME:RL.0"
|
||||
tmux split-window -v -t "$SESSION_NAME:RL.1"
|
||||
tmux split-window -v -t "$SESSION_NAME:RL.2"
|
||||
tmux select-layout -t "$SESSION_NAME:RL" even-vertical
|
||||
|
||||
# Pane titles
|
||||
tmux select-pane -t "$SESSION_NAME:RL.0" -T "Trainer"
|
||||
tmux select-pane -t "$SESSION_NAME:RL.1" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:RL.2" -T "Inference"
|
||||
tmux select-pane -t "$SESSION_NAME:RL.2" -T "Envs"
|
||||
tmux select-pane -t "$SESSION_NAME:RL.3" -T "Inference"
|
||||
|
||||
# Logs: Orchestrator
|
||||
tmux send-keys -t "$SESSION_NAME:RL.1" \
|
||||
"echo \"Following orchestrator.stdout (tail -F; waits for rotate/create)...\"; tail -F \"${OUTPUT_DIR}/logs/orchestrator.stdout\" 2>/dev/null" \
|
||||
C-m
|
||||
|
||||
# Logs: Inference
|
||||
# Logs: Envs (all env server and worker logs)
|
||||
tmux send-keys -t "$SESSION_NAME:RL.2" \
|
||||
"echo \"Following env logs (tail -F; waits for rotate/create)...\"; tail -F \"${OUTPUT_DIR}/logs/envs\"/*/*/*.log 2>/dev/null" \
|
||||
C-m
|
||||
|
||||
# Logs: Inference
|
||||
tmux send-keys -t "$SESSION_NAME:RL.3" \
|
||||
"echo \"Following inference.stdout (tail -F; waits for rotate/create)...\"; tail -F \"${OUTPUT_DIR}/logs/inference.stdout\" 2>/dev/null" \
|
||||
C-m
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
@@ -19,4 +19,10 @@ class EnvServerConfig(BaseConfig):
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs/run_default")
|
||||
] = Path("outputs")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_num_workers(self):
|
||||
if self.env.num_workers == "auto":
|
||||
self.env.num_workers = 1
|
||||
return self
|
||||
|
||||
@@ -287,6 +287,17 @@ class EnvConfig(BaseConfig):
|
||||
),
|
||||
),
|
||||
] = {}
|
||||
num_workers: Annotated[
|
||||
int | Literal["auto"],
|
||||
Field(
|
||||
description=(
|
||||
"Number of env server worker processes. "
|
||||
"Set to 'auto' to scale based on the env's concurrency (1 worker per 256 concurrent rollouts). "
|
||||
"When setting manually, we recommend sizing so that each worker handles at most 256 concurrent rollouts. "
|
||||
"Only used when the orchestrator spawns the env server (i.e. address is None)."
|
||||
),
|
||||
),
|
||||
] = "auto"
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(
|
||||
|
||||
@@ -717,7 +717,7 @@ class RLConfig(BaseConfig):
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
# set num_train_workers to the number of data replicas
|
||||
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
|
||||
non_data_parallel_size = self.trainer.model.cp
|
||||
if self.deployment.num_train_gpus > 1:
|
||||
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
|
||||
|
||||
|
||||
@@ -225,10 +225,11 @@ class SFTConfig(BaseConfig):
|
||||
] = 600
|
||||
|
||||
loss_impl: Annotated[
|
||||
Literal["liger", "torch", "liger_fused"],
|
||||
Literal["liger", "torch", "liger_fused", "quack_fused"],
|
||||
Field(
|
||||
description="Implementation of the cross entropy loss function to use. "
|
||||
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits."
|
||||
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits. "
|
||||
"'quack_fused' uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."
|
||||
),
|
||||
] = "torch"
|
||||
|
||||
|
||||
@@ -28,14 +28,34 @@ _ATTN_ALIASES = {"flash_attention_4": "fa4"}
|
||||
class ActivationCheckpointConfig(BaseConfig):
|
||||
"""Configures activation checkpointing."""
|
||||
|
||||
mode: Annotated[
|
||||
Literal["full", "selective"],
|
||||
Field(
|
||||
description="Whether to checkpoint whole transformer blocks (`full`) or selected subcomponents inside supported custom decoder layers (`selective`).",
|
||||
),
|
||||
] = "full"
|
||||
|
||||
freq: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Applies activation checkpointing to every `freq` layers. Defaults to 1, which will is full activation checkpointing.",
|
||||
description="Applies activation checkpointing to every `freq` layers. Defaults to 1.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
targets: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
description="Selective checkpoint targets. `norm` checkpoints every norm module inside selected layers (decoder, attention, MLA, etc.). `attn_proj` checkpoints QKV projections, QK norms, RoPE, and output projection — everything in the attention layer except the kernel. `mlp` checkpoints the entire dense MLP forward (not applicable to MoE layers). `mla_up_proj` checkpoints MLA Q/KV up-projection work where supported. `routed_experts` checkpoints routed expert compute in MoE layers (including LatentMoE). `mamba` checkpoints the Mamba mixer forward in NemotronH Mamba layers. `linear_attn` checkpoints the GatedDeltaNet forward in Qwen3.5-MoE linear attention layers.",
|
||||
),
|
||||
] = ["norm"]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_selective_targets(self):
|
||||
if self.mode == "selective" and not self.targets:
|
||||
raise ValueError("Selective activation checkpointing requires at least one target.")
|
||||
return self
|
||||
|
||||
|
||||
class ActivationOffloadingConfig(BaseConfig):
|
||||
"""Configures the activation offloading."""
|
||||
@@ -202,13 +222,6 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
tp: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="The tensor parallelism size to use. If 1, then no TP will be used.",
|
||||
),
|
||||
] = 1
|
||||
|
||||
cp: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -316,6 +329,12 @@ class ModelConfig(BaseModelConfig):
|
||||
self.ac = ActivationCheckpointConfig()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def selective_ac_only_with_custom_impl(self):
|
||||
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cpu_offload_mutual_exclusion(self):
|
||||
if self.fsdp_cpu_offload and self.optim_cpu_offload:
|
||||
|
||||
@@ -455,6 +455,38 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def format_log_message(
|
||||
trainer_log: str,
|
||||
orchestrator_log: str | None,
|
||||
inference_log: str | None,
|
||||
env_log_dir: Path,
|
||||
train_env_names: list[str],
|
||||
eval_env_names: list[str],
|
||||
) -> str:
|
||||
col = 18
|
||||
i1 = " " * 2
|
||||
i2 = " " * 3
|
||||
i3 = " " * 4
|
||||
max_name = col - 4
|
||||
|
||||
log_lines = [f"{i1}{'Trainer:':<{col}}tail -F {trainer_log}"]
|
||||
if orchestrator_log:
|
||||
log_lines.append(f"{i1}{'Orchestrator:':<{col}}tail -F {orchestrator_log}")
|
||||
if inference_log:
|
||||
log_lines.append(f"{i1}{'Inference:':<{col}}tail -F {inference_log}")
|
||||
log_lines.append(f"{i1}{'Envs:':<{col}}tail -F {env_log_dir}/*/*/*.log")
|
||||
log_lines.append(f"{i2}{'Train:':<{col - 1}}tail -F {env_log_dir}/train/*/*.log")
|
||||
for name in train_env_names:
|
||||
short = name if len(name) <= max_name else name[: max_name - 3] + "..."
|
||||
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/train/{name}/*.log")
|
||||
if eval_env_names:
|
||||
log_lines.append(f"{i2}{'Eval:':<{col - 1}}tail -F {env_log_dir}/eval/*/*.log")
|
||||
for name in eval_env_names:
|
||||
short = name if len(name) <= max_name else name[: max_name - 3] + "..."
|
||||
log_lines.append(f"{i3}{f'{short}:':<{col - 2}}tail -F {env_log_dir}/eval/{name}/*.log")
|
||||
return "Logs:\n" + "\n".join(log_lines)
|
||||
|
||||
|
||||
def rl_slurm(config: RLConfig):
|
||||
assert config.slurm is not None
|
||||
|
||||
@@ -466,22 +498,36 @@ def rl_slurm(config: RLConfig):
|
||||
logger.info(f"Wrote config to {config_dir / RL_TOML}")
|
||||
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Trainer: tail -F {log_dir}/trainer.stdout\n"
|
||||
f" Orchestrator: tail -F {log_dir}/orchestrator.stdout\n"
|
||||
f" Inference: tail -F {log_dir}/inference.stdout"
|
||||
env_log_dir = get_log_dir(config.output_dir) / "envs"
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
|
||||
log_message = format_log_message(
|
||||
trainer_log=f"{log_dir}/trainer.stdout",
|
||||
orchestrator_log=f"{log_dir}/orchestrator.stdout",
|
||||
inference_log=f"{log_dir}/inference.stdout",
|
||||
env_log_dir=env_log_dir,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
else:
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
slurm_log_dir = config.output_dir / "slurm"
|
||||
log_lines = [f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log"]
|
||||
if config.deployment.num_infer_nodes > 0:
|
||||
log_lines.append(f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log")
|
||||
log_lines.append(f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log")
|
||||
log_message = "Logs:\n" + "\n".join(log_lines)
|
||||
env_log_dir = get_log_dir(config.output_dir) / "envs"
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
|
||||
has_infer = config.deployment.num_infer_nodes > 0
|
||||
log_message = format_log_message(
|
||||
trainer_log=f"{slurm_log_dir}/latest_train_node_rank_0.log",
|
||||
orchestrator_log=f"{slurm_log_dir}/latest_orchestrator.log" if has_infer else None,
|
||||
inference_log=f"{slurm_log_dir}/latest_infer_node_rank_0.log" if has_infer else None,
|
||||
env_log_dir=env_log_dir,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
|
||||
script_path = config.output_dir / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import asyncio
|
||||
|
||||
from verifiers.workers import ZMQEnvServer
|
||||
from verifiers.serve import ZMQEnvServer
|
||||
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.utils.config import cli
|
||||
@@ -19,17 +19,16 @@ def run_server(config: EnvServerConfig):
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
|
||||
env_name = config.env.name or config.env.id
|
||||
log_file = (get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix()
|
||||
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
|
||||
|
||||
server = ZMQEnvServer(
|
||||
env_id=strip_env_version(config.env.id),
|
||||
env_args=config.env.args,
|
||||
extra_env_kwargs=config.env.extra_env_kwargs,
|
||||
log_level=config.log.level,
|
||||
log_file_level=config.log.vf_level,
|
||||
log_file=log_file,
|
||||
log_dir=log_dir,
|
||||
json_logging=config.log.json_logging,
|
||||
num_workers=config.env.num_workers,
|
||||
**{"address": config.env.address} if config.env.address is not None else {},
|
||||
)
|
||||
asyncio.run(server.run())
|
||||
|
||||
@@ -53,6 +53,7 @@ from prime_rl.orchestrator.vf_utils import (
|
||||
get_completion_len,
|
||||
get_seq_len,
|
||||
intercept_vf_logging,
|
||||
resolve_num_workers,
|
||||
setup_env_client,
|
||||
spawn_env_server,
|
||||
task_uses_group_scoring,
|
||||
@@ -85,7 +86,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
intercept_vf_logging(logger="verifiers.workers", level=config.log.vf_level) # show logs from env clients
|
||||
intercept_vf_logging(logger="verifiers.serve", level=config.log.vf_level) # show logs from env clients
|
||||
logger.info("Starting orchestrator")
|
||||
|
||||
event_loop_lag_monitor = EventLoopLagMonitor()
|
||||
@@ -172,10 +173,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Load environment and extract dataset
|
||||
logger.info(
|
||||
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
|
||||
f"Loading {len(config.env)} training environment(s) ({', '.join(env.resolved_name for env in config.env)})"
|
||||
)
|
||||
env_ids = [strip_env_version(env.id) for env in config.env]
|
||||
train_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.env)]
|
||||
train_env_names = [env.resolved_name for env in config.env]
|
||||
train_env_group = vf.EnvGroup(
|
||||
envs=[vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.env)],
|
||||
env_names=train_env_names,
|
||||
@@ -216,15 +217,18 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
|
||||
if env.address is None:
|
||||
num_workers = resolve_num_workers(env.num_workers, config.max_inflight_rollouts)
|
||||
log_dir = (get_log_dir(config.output_dir.parent) / "envs" / "train" / env_name).as_posix()
|
||||
address, process = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
num_workers=num_workers,
|
||||
log_level=config.log.vf_level,
|
||||
log_dir=log_dir,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
logger.info(f"Spawned env server for {env_name} with {num_workers} worker(s)")
|
||||
env_processes.append(process)
|
||||
else:
|
||||
if env_name in train_env_deferred_group_scoring_tasks:
|
||||
@@ -251,21 +255,34 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
if config.eval:
|
||||
env_ids = [strip_env_version(env.id) for env in config.eval.env]
|
||||
eval_envs = [vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.eval.env)]
|
||||
eval_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.eval.env)]
|
||||
eval_env_names = [env.resolved_name for env in config.eval.env]
|
||||
eval_sampling_args = get_eval_sampling_args(config.eval.sampling)
|
||||
eval_env_addresses = []
|
||||
|
||||
for env_id, env, eval_env_name in zip(env_ids, config.eval.env, eval_env_names):
|
||||
if env.address is None:
|
||||
num_examples = env.num_examples or config.eval.num_examples
|
||||
rollouts_per_example = env.rollouts_per_example or config.eval.rollouts_per_example
|
||||
if num_examples == -1:
|
||||
max_concurrent = 1024
|
||||
logger.warning(
|
||||
f"Eval env '{eval_env_name}' uses all examples (num_examples=-1). "
|
||||
f"Defaulting max_concurrent={max_concurrent} for worker scaling."
|
||||
)
|
||||
else:
|
||||
max_concurrent = num_examples * rollouts_per_example
|
||||
num_workers = resolve_num_workers(env.num_workers, max_concurrent)
|
||||
log_dir = (get_log_dir(config.output_dir.parent) / "envs" / "eval" / eval_env_name).as_posix()
|
||||
address, process = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "eval" / f"{eval_env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
num_workers=num_workers,
|
||||
log_level=config.log.vf_level,
|
||||
log_dir=log_dir,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
logger.info(f"Spawned eval env server for {eval_env_name} with {num_workers} worker(s)")
|
||||
env_processes.append(process)
|
||||
else:
|
||||
address = env.address
|
||||
@@ -490,9 +507,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Schedule generating the training batch
|
||||
temperature = compute_temperature(progress.step, config.sampling, config.max_steps)
|
||||
sampling_args = get_sampling_args(
|
||||
config.sampling, temperature=temperature, use_token_client=config.use_token_client
|
||||
)
|
||||
is_vllm = config.teacher_rollout_model is None
|
||||
sampling_args = get_sampling_args(config.sampling, temperature=temperature, is_vllm=is_vllm)
|
||||
scheduler.set_sampling_args(sampling_args)
|
||||
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
|
||||
|
||||
|
||||
@@ -88,9 +88,8 @@ class Scheduler:
|
||||
self.enable_policy_updates = enable_policy_updates
|
||||
self.lora_name = lora_name
|
||||
initial_temp = compute_temperature(step=0, sampling_config=config.sampling, max_steps=config.max_steps)
|
||||
self.sampling_args = get_sampling_args(
|
||||
config.sampling, temperature=initial_temp, use_token_client=config.use_token_client
|
||||
)
|
||||
is_vllm = config.teacher_rollout_model is None
|
||||
self.sampling_args = get_sampling_args(config.sampling, temperature=initial_temp, is_vllm=is_vllm)
|
||||
self.model_name = self.config.model.name
|
||||
self.json_logging = config.log.json_logging
|
||||
|
||||
|
||||
@@ -36,13 +36,14 @@ async def get_semaphore() -> AsyncContextManager:
|
||||
return SEMAPHORE
|
||||
|
||||
|
||||
def get_sampling_args(sampling_config: SamplingConfig, temperature: float, use_token_client: bool = True) -> dict:
|
||||
def get_sampling_args(sampling_config: SamplingConfig, temperature: float, is_vllm: bool = True) -> dict:
|
||||
# Convert SamplingConfig to vLLM OAI sampling args
|
||||
# https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html#extra-parameters_2
|
||||
sampling_args = dict(sampling_config)
|
||||
sampling_args.pop("temp_scheduler", None)
|
||||
sampling_args["temperature"] = temperature
|
||||
sampling_args["top_p"] = 1.0
|
||||
sampling_args["logprobs"] = True
|
||||
extra_body = dict(sampling_config.extra_body)
|
||||
|
||||
min_tokens = sampling_args.pop("min_tokens")
|
||||
@@ -53,12 +54,9 @@ def get_sampling_args(sampling_config: SamplingConfig, temperature: float, use_t
|
||||
if repetition_penalty != 1.0:
|
||||
extra_body["repetition_penalty"] = repetition_penalty
|
||||
|
||||
extra_body["top_k"] = -1
|
||||
extra_body["min_p"] = 0.0
|
||||
|
||||
sampling_args["logprobs"] = True
|
||||
|
||||
if use_token_client:
|
||||
if is_vllm:
|
||||
extra_body["top_k"] = -1
|
||||
extra_body["min_p"] = 0.0
|
||||
extra_body["return_token_ids"] = True
|
||||
|
||||
if extra_body:
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import math
|
||||
import multiprocessing as mp
|
||||
from collections.abc import Awaitable, Callable
|
||||
from itertools import cycle
|
||||
from typing import Any
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.envs.environment import EnvClient
|
||||
from verifiers.utils.worker_utils import get_free_port_pair
|
||||
from verifiers.workers import ZMQEnvClient, ZMQEnvServer
|
||||
from verifiers.serve import EnvClient, ZMQEnvClient, ZMQEnvServer
|
||||
from verifiers.utils.serve_utils import get_free_port
|
||||
|
||||
from prime_rl.utils.logger import InterceptHandler, ProgressTracker, get_logger
|
||||
|
||||
@@ -17,15 +17,30 @@ REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
|
||||
DEFAULT_STATE_COLUMNS = []
|
||||
|
||||
|
||||
WORKERS_PER_CONCURRENCY = 256
|
||||
|
||||
|
||||
def resolve_num_workers(num_workers: int | str, max_concurrent: int | None = None) -> int:
|
||||
"""Resolve num_workers from config value.
|
||||
|
||||
When set to ``"auto"``, scales based on max_concurrent using the same
|
||||
heuristic as verifiers' eval_utils: 1 worker per 256 concurrent rollouts.
|
||||
"""
|
||||
if num_workers == "auto":
|
||||
assert max_concurrent is not None, "max_concurrent must be set when num_workers='auto'"
|
||||
return max(1, math.ceil(max_concurrent / WORKERS_PER_CONCURRENCY))
|
||||
return int(num_workers)
|
||||
|
||||
|
||||
def spawn_env_server(
|
||||
env_id: str,
|
||||
env_args: dict[str, Any],
|
||||
extra_env_kwargs: dict[str, Any],
|
||||
address: str | None = None,
|
||||
num_workers: int = 1,
|
||||
# logging configs
|
||||
log_level: str | None = None,
|
||||
log_file: str | None = None,
|
||||
log_file_level: str | None = None,
|
||||
log_dir: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> tuple[str, mp.Process]:
|
||||
"""
|
||||
@@ -33,7 +48,7 @@ def spawn_env_server(
|
||||
|
||||
Mirrors vf.Environment.start_server().
|
||||
"""
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port_pair()}"
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port()}"
|
||||
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
|
||||
# the parent process, which has caused hangs when multiple env server
|
||||
# subprocesses share the same fds.
|
||||
@@ -44,10 +59,14 @@ def spawn_env_server(
|
||||
env_args,
|
||||
extra_env_kwargs,
|
||||
log_level,
|
||||
log_file,
|
||||
log_file_level,
|
||||
log_dir,
|
||||
),
|
||||
kwargs=dict(
|
||||
address=address,
|
||||
json_logging=json_logging,
|
||||
console_logging=False,
|
||||
num_workers=num_workers,
|
||||
),
|
||||
kwargs=dict(address=address, json_logging=json_logging),
|
||||
daemon=False, # cannot run daemon because env server uses subprocesses
|
||||
)
|
||||
process.start()
|
||||
|
||||
@@ -31,6 +31,11 @@ from prime_rl.trainer.models import (
|
||||
get_custom_vlm_cls,
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
supports_selective_activation_checkpointing,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
@@ -600,12 +605,49 @@ def reshard_module(model: nn.Module):
|
||||
|
||||
|
||||
def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
selective_layers = 0
|
||||
full_layers = 0
|
||||
fallback_layer_types: set[str] = set()
|
||||
model_supported_targets: set[str] = set()
|
||||
|
||||
for layer_id, (layer_name, transformer_block) in enumerate(language_model.layers.named_children()):
|
||||
if layer_id % ac_config.freq == 0:
|
||||
if layer_id % ac_config.freq != 0:
|
||||
continue
|
||||
|
||||
if ac_config.mode == "selective" and supports_selective_activation_checkpointing(transformer_block):
|
||||
model_supported_targets.update(get_supported_targets(transformer_block))
|
||||
set_selective_activation_checkpointing(transformer_block, ac_config.targets)
|
||||
selective_layers += 1
|
||||
else:
|
||||
if ac_config.mode == "selective":
|
||||
fallback_layer_types.add(type(transformer_block).__name__)
|
||||
transformer_block = checkpoint_wrapper(transformer_block, preserve_rng_state=False)
|
||||
full_layers += 1
|
||||
|
||||
language_model.layers.register_module(layer_name, transformer_block)
|
||||
get_logger().info(f"Applied activation checkpointing (freq={ac_config.freq})")
|
||||
|
||||
if ac_config.mode == "selective":
|
||||
unsupported_targets = frozenset(ac_config.targets) - model_supported_targets
|
||||
if unsupported_targets:
|
||||
raise ValueError(
|
||||
f"Selective activation checkpoint targets {sorted(unsupported_targets)} are not supported "
|
||||
f"by the selected model layers. Supported targets across the model: {sorted(model_supported_targets)}"
|
||||
)
|
||||
if fallback_layer_types:
|
||||
logger.warning(
|
||||
"Selective activation checkpointing is not supported for layer types "
|
||||
f"{sorted(fallback_layer_types)}; falling back to full checkpointing for those layers."
|
||||
)
|
||||
logger.info(
|
||||
"Applied selective activation checkpointing "
|
||||
f"(freq={ac_config.freq}, targets={ac_config.targets}, selective_layers={selective_layers}, "
|
||||
f"full_fallback_layers={full_layers})"
|
||||
)
|
||||
return
|
||||
|
||||
logger.info(f"Applied activation checkpointing (freq={ac_config.freq})")
|
||||
|
||||
|
||||
def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
@@ -638,6 +680,12 @@ def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
|
||||
buffer.data = buffer.data.to("cuda")
|
||||
|
||||
|
||||
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
|
||||
for module in model.modules():
|
||||
if isinstance(module, (MoE, LatentMoE)) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
|
||||
|
||||
def _validate_flash_attn_4_installed() -> None:
|
||||
"""Validate that flash-attn-cute is installed and not overwritten by flash-attn.
|
||||
|
||||
@@ -678,7 +726,7 @@ def setup_model(
|
||||
config: ModelConfig,
|
||||
parallel_dims: ParallelDims,
|
||||
loading_from_checkpoint_later: bool = False,
|
||||
fused_cross_entropy: bool = False,
|
||||
fused_cross_entropy: bool | str = False,
|
||||
) -> nn.Module:
|
||||
if config.attn == "flash_attention_3" and not is_flash_attn_3_available():
|
||||
raise ValueError(
|
||||
@@ -760,6 +808,7 @@ def setup_model(
|
||||
else:
|
||||
load_dcp_from_hf(model, config, parallel_dims)
|
||||
|
||||
_reset_runtime_moe_buffers(model)
|
||||
return model
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
RotaryEmbedding,
|
||||
RotaryEmbeddingConfig,
|
||||
@@ -146,6 +146,24 @@ class AfmoeAttentionBase(nn.Module):
|
||||
class AfmoeSDPAAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
dropout_p: float = 0.0,
|
||||
) -> torch.Tensor:
|
||||
return F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
is_causal=attention_mask is None,
|
||||
scale=self.scaling,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -159,14 +177,12 @@ class AfmoeSDPAAttention(AfmoeAttentionBase):
|
||||
)
|
||||
|
||||
dropout_p = self.attention_dropout if self.training else 0.0
|
||||
attn_output = F.scaled_dot_product_attention(
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
attention_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
is_causal=attention_mask is None, # Use causal if no explicit mask
|
||||
scale=self.scaling,
|
||||
)
|
||||
|
||||
return self._finalize_output(attn_output, gate_states, input_shape)
|
||||
@@ -202,6 +218,16 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -229,9 +255,14 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
attn_output = out.contiguous().view(*input_shape, -1)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate_states)
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, None
|
||||
|
||||
@@ -37,7 +37,7 @@ from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import warnings
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
@@ -21,193 +20,39 @@ from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
convert_tt_layer_to_vllm_kernel,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
RotaryEmbedding,
|
||||
RotaryEmbeddingConfig,
|
||||
apply_rotary_pos_emb_interleave,
|
||||
)
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
|
||||
except ImportError:
|
||||
sparse_mla_fwd_interface = None # type: ignore
|
||||
sparse_mla_bwd = None # type: ignore
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
|
||||
|
||||
class _SparseMLA(torch.autograd.Function):
|
||||
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, q, kv, indices, sm_scale):
|
||||
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, do):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
|
||||
return dq, dkv, None, None
|
||||
|
||||
|
||||
class LayerNorm(nn.Module):
|
||||
def __init__(self, dim: int, eps: float = 1e-6):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
|
||||
self.bias = nn.Parameter(torch.zeros(dim, dtype=torch.float32))
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
return F.layer_norm(x.float(), (self.dim,), self.weight.float(), self.bias.float(), self.eps).type_as(x)
|
||||
|
||||
|
||||
class Indexer(nn.Module):
|
||||
def __init__(self, config: GlmMoeDsaConfig):
|
||||
super().__init__()
|
||||
if config.q_lora_rank is None:
|
||||
raise ValueError("Sparse indexer requires q_lora_rank to be set")
|
||||
|
||||
self.n_head = config.index_n_heads
|
||||
self.head_dim = config.index_head_dim
|
||||
self.rope_dim = config.qk_rope_head_dim
|
||||
self.wq_b = nn.Linear(config.q_lora_rank, self.n_head * self.head_dim, bias=False)
|
||||
self.wk = nn.Linear(config.hidden_size, self.head_dim, bias=config.attention_bias)
|
||||
self.k_norm = LayerNorm(dim=self.head_dim, eps=1e-6)
|
||||
self.weights_proj = nn.Linear(config.hidden_size, self.n_head, bias=False)
|
||||
self.weight_scale = (self.head_dim**-0.5) * (self.n_head**-0.5)
|
||||
|
||||
@torch.no_grad()
|
||||
def compute_sparse_indices(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_latent: torch.Tensor,
|
||||
ks: torch.Tensor,
|
||||
ke: torch.Tensor,
|
||||
index_topk: int,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
total_tokens = hidden_states.shape[1]
|
||||
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
|
||||
|
||||
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
|
||||
k_idx = self.k_norm(self.wk(hidden_states[0]))
|
||||
w = self.weights_proj(hidden_states[0])
|
||||
|
||||
q_pe = q_idx[..., : self.rope_dim]
|
||||
q_nope = q_idx[..., self.rope_dim :]
|
||||
k_pe = k_idx[..., : self.rope_dim]
|
||||
k_nope = k_idx[..., self.rope_dim :]
|
||||
|
||||
cos, sin = position_embeddings
|
||||
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
|
||||
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
|
||||
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
|
||||
q_pe = q_pe.transpose(1, 2).squeeze(0)
|
||||
k_pe = k_pe.squeeze(1).squeeze(0)
|
||||
|
||||
q_idx = torch.cat([q_pe, q_nope], dim=-1)
|
||||
k_idx = torch.cat([k_pe, k_nope], dim=-1)
|
||||
|
||||
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
|
||||
return indices.view(1, total_tokens, 1, index_topk)
|
||||
|
||||
|
||||
class GlmMoeDsaAttention(nn.Module):
|
||||
def __init__(self, config: GlmMoeDsaConfig):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.kv_lora_rank = config.kv_lora_rank
|
||||
self.qk_rope_head_dim = config.qk_rope_head_dim
|
||||
self.qk_nope_head_dim = config.qk_nope_head_dim
|
||||
self.qk_head_dim = config.qk_head_dim
|
||||
self.v_head_dim = config.v_head_dim
|
||||
|
||||
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
|
||||
self.q_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
||||
|
||||
self.kv_a_proj_with_mqa = nn.Linear(
|
||||
config.hidden_size,
|
||||
self.kv_lora_rank + self.qk_rope_head_dim,
|
||||
bias=config.attention_bias,
|
||||
)
|
||||
self.kv_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=self.kv_lora_rank, eps=config.rms_norm_eps))
|
||||
self.kv_b_proj = nn.Linear(
|
||||
self.kv_lora_rank,
|
||||
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
||||
bias=False,
|
||||
)
|
||||
|
||||
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
self.indexer = Indexer(config)
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
ks: torch.Tensor | None = None,
|
||||
ke: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
batch_size, total_tokens, _ = hidden_states.shape
|
||||
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
|
||||
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
||||
|
||||
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
||||
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
||||
k_compressed_normed = self.kv_a_layernorm(k_compressed)
|
||||
|
||||
q_rope_r = q_rope.transpose(1, 2)
|
||||
k_rope_r = k_rope.unsqueeze(1)
|
||||
cos, sin = position_embeddings
|
||||
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
|
||||
q_rope = q_rope_r.transpose(1, 2)
|
||||
k_rope = k_rope_r.squeeze(1)
|
||||
|
||||
indices = self.indexer.compute_sparse_indices(
|
||||
hidden_states, q_latent, ks, ke, self.config.index_topk, position_embeddings
|
||||
)
|
||||
|
||||
# KV absorption
|
||||
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
|
||||
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
|
||||
w_v = kv_b_w[:, self.qk_nope_head_dim :, :]
|
||||
|
||||
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
|
||||
|
||||
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
|
||||
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
|
||||
|
||||
# Sentinel zero-token so padded indices (= total_tokens) are in-bounds
|
||||
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
|
||||
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
|
||||
# Un-absorb
|
||||
out = torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
|
||||
out = out.reshape(batch_size, total_tokens, -1)
|
||||
return self.o_proj(out), None
|
||||
def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArgs:
|
||||
if config.q_lora_rank is None:
|
||||
raise ValueError("Sparse MLA attention requires q_lora_rank to be set")
|
||||
return SparseMlaAttentionArgs(
|
||||
hidden_size=config.hidden_size,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
kv_lora_rank=config.kv_lora_rank,
|
||||
q_lora_rank=config.q_lora_rank,
|
||||
qk_rope_head_dim=config.qk_rope_head_dim,
|
||||
qk_nope_head_dim=config.qk_nope_head_dim,
|
||||
qk_head_dim=config.qk_head_dim,
|
||||
v_head_dim=config.v_head_dim,
|
||||
attention_bias=config.attention_bias,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
index_n_heads=config.index_n_heads,
|
||||
index_head_dim=config.index_head_dim,
|
||||
index_topk=config.index_topk,
|
||||
)
|
||||
|
||||
|
||||
class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: GlmMoeDsaConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = GlmMoeDsaAttention(config)
|
||||
self.self_attn = GlmMoeDsaAttention(_sparse_mla_attention_args(config))
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb_interleave
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
|
||||
except ImportError:
|
||||
sparse_mla_fwd_interface = None # type: ignore
|
||||
sparse_mla_bwd = None # type: ignore
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SparseMlaAttentionArgs:
|
||||
hidden_size: int
|
||||
num_attention_heads: int
|
||||
kv_lora_rank: int
|
||||
q_lora_rank: int
|
||||
qk_rope_head_dim: int
|
||||
qk_nope_head_dim: int
|
||||
qk_head_dim: int
|
||||
v_head_dim: int
|
||||
attention_bias: bool
|
||||
rms_norm_eps: float
|
||||
index_n_heads: int
|
||||
index_head_dim: int
|
||||
index_topk: int
|
||||
|
||||
|
||||
class _SparseMLA(torch.autograd.Function):
|
||||
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, q, kv, indices, sm_scale):
|
||||
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, do):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
|
||||
return dq, dkv, None, None
|
||||
|
||||
|
||||
class Indexer(nn.Module):
|
||||
def __init__(self, args: SparseMlaAttentionArgs):
|
||||
super().__init__()
|
||||
self.n_head = args.index_n_heads
|
||||
self.head_dim = args.index_head_dim
|
||||
self.rope_dim = args.qk_rope_head_dim
|
||||
self.wq_b = nn.Linear(args.q_lora_rank, self.n_head * self.head_dim, bias=False)
|
||||
self.wk = nn.Linear(args.hidden_size, self.head_dim, bias=args.attention_bias)
|
||||
self.k_norm = LayerNorm(dim=self.head_dim, eps=1e-6)
|
||||
self.weights_proj = nn.Linear(args.hidden_size, self.n_head, bias=False)
|
||||
self.weight_scale = (self.head_dim**-0.5) * (self.n_head**-0.5)
|
||||
|
||||
@torch.no_grad()
|
||||
def compute_sparse_indices(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_latent: torch.Tensor,
|
||||
ks: torch.Tensor,
|
||||
ke: torch.Tensor,
|
||||
index_topk: int,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
total_tokens = hidden_states.shape[1]
|
||||
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
|
||||
|
||||
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
|
||||
k_idx = self.k_norm(self.wk(hidden_states[0]))
|
||||
w = self.weights_proj(hidden_states[0])
|
||||
|
||||
q_pe = q_idx[..., : self.rope_dim]
|
||||
q_nope = q_idx[..., self.rope_dim :]
|
||||
k_pe = k_idx[..., : self.rope_dim]
|
||||
k_nope = k_idx[..., self.rope_dim :]
|
||||
|
||||
cos, sin = position_embeddings
|
||||
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
|
||||
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
|
||||
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
|
||||
q_pe = q_pe.transpose(1, 2).squeeze(0)
|
||||
k_pe = k_pe.squeeze(1).squeeze(0)
|
||||
|
||||
q_idx = torch.cat([q_pe, q_nope], dim=-1)
|
||||
k_idx = torch.cat([k_pe, k_nope], dim=-1)
|
||||
|
||||
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
|
||||
return indices.view(1, total_tokens, 1, index_topk)
|
||||
|
||||
|
||||
class GlmMoeDsaAttention(nn.Module):
|
||||
def __init__(self, args: SparseMlaAttentionArgs):
|
||||
super().__init__()
|
||||
self.args = args
|
||||
self.num_heads = args.num_attention_heads
|
||||
self.kv_lora_rank = args.kv_lora_rank
|
||||
self.qk_rope_head_dim = args.qk_rope_head_dim
|
||||
self.qk_nope_head_dim = args.qk_nope_head_dim
|
||||
self.qk_head_dim = args.qk_head_dim
|
||||
self.v_head_dim = args.v_head_dim
|
||||
|
||||
self.q_a_proj = nn.Linear(args.hidden_size, args.q_lora_rank, bias=args.attention_bias)
|
||||
self.q_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=args.q_lora_rank, eps=args.rms_norm_eps))
|
||||
self.q_b_proj = nn.Linear(args.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
||||
|
||||
self.kv_a_proj_with_mqa = nn.Linear(
|
||||
args.hidden_size,
|
||||
self.kv_lora_rank + self.qk_rope_head_dim,
|
||||
bias=args.attention_bias,
|
||||
)
|
||||
self.kv_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=self.kv_lora_rank, eps=args.rms_norm_eps))
|
||||
self.kv_b_proj = nn.Linear(
|
||||
self.kv_lora_rank,
|
||||
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
|
||||
bias=False,
|
||||
)
|
||||
|
||||
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
|
||||
self.indexer = Indexer(args)
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
def _mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
||||
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
||||
return q_latent, self.kv_a_layernorm(k_compressed), k_rope
|
||||
|
||||
def _mla_up_proj(
|
||||
self,
|
||||
q_latent: torch.Tensor,
|
||||
k_compressed_normed: torch.Tensor,
|
||||
k_rope: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
batch_size, total_tokens, _ = q_latent.shape
|
||||
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
|
||||
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
||||
|
||||
q_rope_r = q_rope.transpose(1, 2)
|
||||
k_rope_r = k_rope.unsqueeze(1)
|
||||
cos, sin = position_embeddings
|
||||
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
|
||||
q_rope = q_rope_r.transpose(1, 2)
|
||||
k_rope = k_rope_r.squeeze(1)
|
||||
|
||||
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
|
||||
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
|
||||
w_v = kv_b_w[:, self.qk_nope_head_dim :, :]
|
||||
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
|
||||
|
||||
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
|
||||
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
|
||||
|
||||
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
|
||||
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
|
||||
return sparse_q, sparse_kv, w_v
|
||||
|
||||
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
|
||||
return torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
ks: torch.Tensor | None = None,
|
||||
ke: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
batch_size, total_tokens, _ = hidden_states.shape
|
||||
|
||||
q_latent, k_compressed_normed, k_rope = self._mla_latents(hidden_states)
|
||||
|
||||
indices = self.indexer.compute_sparse_indices(
|
||||
hidden_states, q_latent, ks, ke, self.args.index_topk, position_embeddings
|
||||
)
|
||||
|
||||
sparse_q, sparse_kv, w_v = self._mla_up_proj(
|
||||
q_latent,
|
||||
k_compressed_normed,
|
||||
k_rope,
|
||||
position_embeddings=position_embeddings,
|
||||
)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
out = self._mla_unabsorb(out, w_v)
|
||||
|
||||
out = out.reshape(batch_size, total_tokens, -1)
|
||||
return self.o_proj(out), None
|
||||
@@ -6,7 +6,7 @@ import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from .rms_norm import RMSNorm, RMSNormConfig
|
||||
from .norms import RMSNorm, RMSNormConfig
|
||||
from .rotary_emb import apply_rotary_pos_emb
|
||||
|
||||
# flash-attention-2
|
||||
@@ -105,13 +105,22 @@ class FlashAttention(nn.Module):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def forward(
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
return out.contiguous().view(1, out.shape[0], -1)
|
||||
|
||||
def _attn_projections(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
@@ -144,14 +153,29 @@ class FlashAttention(nn.Module):
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
return query_states, key_states, value_states
|
||||
|
||||
out = out.contiguous()
|
||||
attn_output = out.view(1, out.shape[0], -1)
|
||||
attn_weights = None
|
||||
def _output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, attn_weights
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self._attn_projections(hidden_states, position_embeddings)
|
||||
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
attn_output = self._output_proj(attn_output)
|
||||
return attn_output, None
|
||||
|
||||
|
||||
class SDPAAttention(nn.Module):
|
||||
@@ -188,19 +212,17 @@ class SDPAAttention(nn.Module):
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
def _attn_projections(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states: torch.Tensor = self.q_proj(hidden_states)
|
||||
key_states: torch.Tensor = self.k_proj(hidden_states)
|
||||
value_states: torch.Tensor = self.v_proj(hidden_states)
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
@@ -222,17 +244,35 @@ class SDPAAttention(nn.Module):
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
# TODO: Can we optimize the rotary application instead of double transpose?
|
||||
return query_states, key_states, value_states
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
out = F.scaled_dot_product_attention(query_states, key_states, value_states, is_causal=True)
|
||||
out = out.transpose(1, 2).contiguous() # .view(out.shape[0], out.shape[1], -1)
|
||||
attn_output = out.view(out.shape[0], out.shape[1], -1)
|
||||
attn_weights = None
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
return out.view(out.shape[0], out.shape[1], -1)
|
||||
|
||||
# attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, attn_weights
|
||||
def _output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self._attn_projections(hidden_states, position_embeddings)
|
||||
|
||||
attn_output = self._attention_core(query_states, key_states, value_states)
|
||||
attn_output = self._output_proj(attn_output)
|
||||
return attn_output, None
|
||||
|
||||
|
||||
ATTN_IMPL2CLASS = {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
from collections.abc import Iterable
|
||||
from functools import wraps
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
|
||||
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "routed_experts", "mamba", "linear_attn"})
|
||||
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
|
||||
|
||||
|
||||
def _is_norm_module(module: nn.Module) -> bool:
|
||||
return "norm" in type(module).__name__.lower()
|
||||
|
||||
|
||||
def _should_checkpoint(module: nn.Module) -> bool:
|
||||
return torch.is_grad_enabled() and module.training
|
||||
|
||||
|
||||
def checkpoint_method(module: nn.Module, method_name: str) -> None:
|
||||
patched_methods = frozenset(getattr(module, _PATCHED_METHODS_ATTR, ()))
|
||||
if method_name in patched_methods:
|
||||
return
|
||||
|
||||
original = getattr(module, method_name)
|
||||
|
||||
@wraps(original)
|
||||
def checkpointed(*args, **kwargs):
|
||||
if not _should_checkpoint(module):
|
||||
return original(*args, **kwargs)
|
||||
|
||||
def fn(*checkpoint_args):
|
||||
return original(*checkpoint_args, **kwargs)
|
||||
|
||||
return checkpoint(fn, *args, use_reentrant=False, preserve_rng_state=False)
|
||||
|
||||
setattr(module, method_name, checkpointed)
|
||||
setattr(module, _PATCHED_METHODS_ATTR, patched_methods.union({method_name}))
|
||||
|
||||
|
||||
def _configure_norm_checkpointing(layer: nn.Module) -> None:
|
||||
for module in layer.modules():
|
||||
if module is layer or not _is_norm_module(module):
|
||||
continue
|
||||
checkpoint_method(module, "forward")
|
||||
|
||||
|
||||
def _is_dense_mlp(mlp: nn.Module) -> bool:
|
||||
return not hasattr(mlp, "_run_routed_experts") and not hasattr(mlp, "tokens_per_expert")
|
||||
|
||||
|
||||
def get_supported_targets(layer: nn.Module) -> frozenset[str]:
|
||||
supported_targets = {"norm"}
|
||||
self_attn = getattr(layer, "self_attn", None)
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
mamba = getattr(layer, "mamba", None)
|
||||
linear_attn = getattr(layer, "linear_attn", None)
|
||||
|
||||
if self_attn is not None and hasattr(self_attn, "_attn_projections"):
|
||||
supported_targets.add("attn_proj")
|
||||
if self_attn is not None and hasattr(self_attn, "_mla_up_proj"):
|
||||
supported_targets.add("mla_up_proj")
|
||||
if mlp is not None and _is_dense_mlp(mlp):
|
||||
supported_targets.add("mlp")
|
||||
if mlp is not None and hasattr(mlp, "_run_routed_experts"):
|
||||
supported_targets.add("routed_experts")
|
||||
if mamba is not None:
|
||||
supported_targets.add("mamba")
|
||||
if linear_attn is not None:
|
||||
supported_targets.add("linear_attn")
|
||||
|
||||
return frozenset(supported_targets)
|
||||
|
||||
|
||||
def set_selective_activation_checkpointing(layer: nn.Module, targets: Iterable[str]) -> None:
|
||||
normalized_targets = frozenset(targets)
|
||||
invalid_targets = normalized_targets - SELECTIVE_AC_TARGETS
|
||||
if invalid_targets:
|
||||
raise ValueError(f"Unsupported selective activation checkpoint targets: {sorted(invalid_targets)}")
|
||||
|
||||
enabled_targets = normalized_targets & get_supported_targets(layer)
|
||||
self_attn = getattr(layer, "self_attn", None)
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
|
||||
mamba = getattr(layer, "mamba", None)
|
||||
linear_attn = getattr(layer, "linear_attn", None)
|
||||
|
||||
if self_attn is not None and "attn_proj" in enabled_targets:
|
||||
checkpoint_method(self_attn, "_attn_projections")
|
||||
checkpoint_method(self_attn, "_output_proj")
|
||||
if self_attn is not None and "mla_up_proj" in enabled_targets:
|
||||
checkpoint_method(self_attn, "_mla_up_proj")
|
||||
if mlp is not None and "mlp" in enabled_targets:
|
||||
checkpoint_method(mlp, "forward")
|
||||
if mlp is not None and "routed_experts" in enabled_targets:
|
||||
checkpoint_method(mlp, "_run_routed_experts")
|
||||
if mamba is not None and "mamba" in enabled_targets:
|
||||
checkpoint_method(mamba, "forward")
|
||||
if linear_attn is not None and "linear_attn" in enabled_targets:
|
||||
checkpoint_method(linear_attn, "forward")
|
||||
if "norm" in enabled_targets:
|
||||
_configure_norm_checkpointing(layer)
|
||||
|
||||
|
||||
def supports_selective_activation_checkpointing(layer: nn.Module) -> bool:
|
||||
return type(layer).__module__.startswith("prime_rl.trainer.models.")
|
||||
@@ -9,6 +9,8 @@ from torch import Tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
FUSED_CE_IGNORE_INDEX = -100
|
||||
|
||||
|
||||
class PrimeLmOutput(TypedDict, total=False):
|
||||
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
|
||||
@@ -79,7 +81,7 @@ class FusedCrossEntropyOutputLinear(torch.nn.Linear):
|
||||
projection with the cross-entropy loss computation.
|
||||
"""
|
||||
|
||||
IGNORE_INDEX = -100
|
||||
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
|
||||
|
||||
def __init__(self, in_features: int, out_features: int, softcap: float | None = None):
|
||||
super().__init__(in_features, out_features, bias=False)
|
||||
@@ -105,6 +107,45 @@ class FusedCrossEntropyOutputLinear(torch.nn.Linear):
|
||||
return PrimeLmOutput(loss=loss)
|
||||
|
||||
|
||||
class QuackFusedCrossEntropyOutputLinear(torch.nn.Linear):
|
||||
"""Fused lm_head + cross-entropy loss using quack-kernels.
|
||||
|
||||
Chunks the linear projection and cross-entropy computation to avoid
|
||||
materializing the full [N, V] logits tensor, using quack's optimized
|
||||
CuTe DSL kernels for CE and GEMM.
|
||||
"""
|
||||
|
||||
IGNORE_INDEX = FUSED_CE_IGNORE_INDEX
|
||||
|
||||
def __init__(self, in_features: int, out_features: int, chunk_size: int = 4096):
|
||||
super().__init__(in_features, out_features, bias=False)
|
||||
self.chunk_size = chunk_size
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
labels: torch.Tensor | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
if labels is None:
|
||||
return PrimeLmOutput(logits=super().forward(hidden_states))
|
||||
|
||||
from quack.linear_cross_entropy import chunked_linear_cross_entropy
|
||||
|
||||
b, s, h = hidden_states.shape
|
||||
hidden_flat = hidden_states.reshape(b * s, h).contiguous()
|
||||
labels_flat = labels.reshape(b * s).contiguous()
|
||||
loss = chunked_linear_cross_entropy(
|
||||
hidden_flat,
|
||||
self.weight,
|
||||
labels_flat,
|
||||
chunk_size=self.chunk_size,
|
||||
ignore_index=self.IGNORE_INDEX,
|
||||
reduction="mean",
|
||||
)
|
||||
return PrimeLmOutput(loss=loss)
|
||||
|
||||
|
||||
def _online_logsumexp_and_weighted_update(
|
||||
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
@@ -227,7 +268,11 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
|
||||
return grad_hidden, grad_weight, None, None, None
|
||||
|
||||
|
||||
def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None, fused_cross_entropy: bool = False) -> None:
|
||||
def inject_prime_lm_head(
|
||||
model: nn.Module,
|
||||
chunk_size: int | None = None,
|
||||
fused_cross_entropy: bool | str = False,
|
||||
) -> None:
|
||||
"""
|
||||
Inject a PrimeRL LM head into a model.
|
||||
|
||||
@@ -238,8 +283,10 @@ def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None, fused_
|
||||
model: The model to wrap.
|
||||
chunk_size: When set to an int, uses FusedOutputLinear with sequence-token chunked
|
||||
logprob/entropy computation (for RL).
|
||||
fused_cross_entropy: When True, uses FusedCrossEntropyOutputLinear which fuses the lm_head
|
||||
projection with cross-entropy loss to avoid materializing full logits (for SFT).
|
||||
fused_cross_entropy: Controls fused lm_head + CE loss. Accepts:
|
||||
- False: no fusion
|
||||
- True or "liger": Liger kernel fusion
|
||||
- "quack": quack-kernels fusion (chunked linear + CE with CuTe DSL kernels)
|
||||
"""
|
||||
# Guards so we have nicer error messages when a non-standard model is used
|
||||
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
|
||||
@@ -254,15 +301,27 @@ def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None, fused_
|
||||
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation
|
||||
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
|
||||
if final_logit_softcapping and not fused_cross_entropy:
|
||||
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
|
||||
if final_logit_softcapping:
|
||||
if fused_cross_entropy == "quack":
|
||||
raise ValueError(
|
||||
"quack_fused does not support Gemma logit softcapping. "
|
||||
"Use loss_impl='liger_fused' or loss_impl='torch' instead."
|
||||
)
|
||||
if not fused_cross_entropy:
|
||||
from prime_rl.trainer.models.layers.lm_head_gemma import inject_gemma_lm_head
|
||||
|
||||
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
|
||||
return
|
||||
inject_gemma_lm_head(model, chunk_size, final_logit_softcapping)
|
||||
return
|
||||
|
||||
# Replace the lm_head with the appropriate wrapper
|
||||
old_lm_head = model.lm_head
|
||||
if fused_cross_entropy:
|
||||
if fused_cross_entropy == "quack":
|
||||
logger.info("Injecting fused cross-entropy LM head (quack-kernels)")
|
||||
model.lm_head = QuackFusedCrossEntropyOutputLinear(
|
||||
in_features=old_lm_head.in_features,
|
||||
out_features=old_lm_head.out_features,
|
||||
)
|
||||
elif fused_cross_entropy:
|
||||
logger.info("Injecting fused cross-entropy LM head (Liger kernel)")
|
||||
model.lm_head = FusedCrossEntropyOutputLinear(
|
||||
in_features=old_lm_head.in_features,
|
||||
|
||||
@@ -375,7 +375,32 @@ class MoE(nn.Module):
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
def _run_routed_experts(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
token_indices_experts_sorted: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
top_scores_experts_sorted: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
dim = x.shape[-1]
|
||||
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
routed_input = torch.gather(x, dim=0, index=routed_indices)
|
||||
|
||||
if self.score_before_experts:
|
||||
routed_input = (routed_input.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
|
||||
|
||||
routed_output = self.experts(routed_input, num_tokens_per_expert)
|
||||
|
||||
if not self.score_before_experts:
|
||||
routed_output = (routed_output.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
|
||||
|
||||
return routed_output
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor with shape ``(bs, slen, dim)``.
|
||||
@@ -403,9 +428,9 @@ class MoE(nn.Module):
|
||||
|
||||
# tokens_per_expert will be used to update the expert bias for load balancing.
|
||||
# and also to count the expert usage
|
||||
# TODO: Activation Checkpointing has the side effect of double counting tokens_per_expert --
|
||||
# first in the forward pass, and then in the backward pass. However, this has no
|
||||
# effect on the expert bias update thanks to the torch.sign() operator.
|
||||
# Full block checkpointing can double count tokens_per_expert because it reruns the router
|
||||
# in backward. The selective MoE path avoids that by checkpointing only the
|
||||
# routed expert compute below.
|
||||
with torch.no_grad():
|
||||
self.tokens_per_expert.add_(num_tokens_per_expert)
|
||||
|
||||
@@ -423,28 +448,19 @@ class MoE(nn.Module):
|
||||
num_tokens_per_expert,
|
||||
) = self.reorderer(top_scores, selected_experts_indices)
|
||||
|
||||
# shape (bs*slen*top_k, dim)
|
||||
token_indices_experts_sorted = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
|
||||
# shape (bs*slen*top_k, dim)
|
||||
routed_input = torch.gather(x, dim=0, index=token_indices_experts_sorted)
|
||||
|
||||
if self.score_before_experts:
|
||||
routed_input = (routed_input.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
|
||||
|
||||
# shape (bs*slen*top_k, dim)
|
||||
routed_output = self.experts(routed_input, num_tokens_per_expert)
|
||||
|
||||
if not self.score_before_experts:
|
||||
routed_output = (routed_output.to(torch.float32) * top_scores_experts_sorted.reshape(-1, 1)).to(x.dtype)
|
||||
|
||||
# shared expert
|
||||
routed_output = self._run_routed_experts(
|
||||
x,
|
||||
token_indices_experts_sorted,
|
||||
num_tokens_per_expert,
|
||||
top_scores_experts_sorted,
|
||||
)
|
||||
if self.shared_expert is not None:
|
||||
out = self.shared_expert(x)
|
||||
else:
|
||||
out = torch.zeros_like(x)
|
||||
|
||||
out = out.scatter_add(dim=0, index=token_indices_experts_sorted, src=routed_output)
|
||||
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
out = out.scatter_add(dim=0, index=routed_indices, src=routed_output)
|
||||
out = out.reshape(bs, slen, dim)
|
||||
return out
|
||||
|
||||
@@ -693,6 +709,26 @@ class LatentMoE(nn.Module):
|
||||
persistent=False,
|
||||
)
|
||||
|
||||
def _run_routed_experts(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
token_indices_experts_sorted: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
top_scores_experts_sorted: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
dim = x.shape[-1]
|
||||
token_indices_expanded = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
routed_input = torch.gather(x, dim=0, index=token_indices_expanded)
|
||||
|
||||
routed_input = self.fc1_latent_proj(routed_input)
|
||||
routed_output = self.experts(routed_input, num_tokens_per_expert)
|
||||
|
||||
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
|
||||
routed_output = routed_output * self.routed_scaling_factor
|
||||
|
||||
routed_output = self.fc2_latent_proj(routed_output)
|
||||
return routed_output
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
bs, slen, dim = x.shape
|
||||
x_flat = x.view(-1, dim)
|
||||
@@ -708,24 +744,13 @@ class LatentMoE(nn.Module):
|
||||
num_tokens_per_expert,
|
||||
) = self.reorderer(top_scores, selected_experts_indices)
|
||||
|
||||
token_indices_expanded = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
routed_input = torch.gather(x_flat, dim=0, index=token_indices_expanded)
|
||||
routed_output = self._run_routed_experts(
|
||||
x_flat,
|
||||
token_indices_experts_sorted,
|
||||
num_tokens_per_expert,
|
||||
top_scores_experts_sorted,
|
||||
)
|
||||
|
||||
# Apply latent projection before expert computation
|
||||
routed_input = self.fc1_latent_proj(routed_input)
|
||||
|
||||
routed_output = self.experts(routed_input, num_tokens_per_expert)
|
||||
|
||||
# Apply scores after expert computation (matches vLLM's fused kernel behavior)
|
||||
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
|
||||
|
||||
# Apply routed_scaling_factor after expert output
|
||||
routed_output = routed_output * self.routed_scaling_factor
|
||||
|
||||
# Project back from latent space
|
||||
routed_output = self.fc2_latent_proj(routed_output)
|
||||
|
||||
# Shared expert
|
||||
out = self.shared_expert(x_flat)
|
||||
|
||||
token_indices_full = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.integrations import use_kernel_forward_from_hub
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _get_quack_rmsnorm():
|
||||
"""Lazy-load quack rmsnorm. Returns None if unavailable or GPU is pre-Hopper."""
|
||||
if not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9:
|
||||
return None
|
||||
try:
|
||||
from quack import rmsnorm
|
||||
|
||||
return rmsnorm
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
|
||||
class _ContiguousGrad(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad):
|
||||
return grad.contiguous()
|
||||
|
||||
|
||||
def _contiguous_grad(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Identity in forward, makes gradient contiguous in backward.
|
||||
|
||||
Quack's RMSNorm backward kernel requires contiguous gradients (stride[-1]==1)
|
||||
but upstream ops like attention permute can produce non-contiguous ones.
|
||||
"""
|
||||
return _ContiguousGrad.apply(x) if x.requires_grad else x
|
||||
|
||||
|
||||
@dataclass
|
||||
class RMSNormConfig:
|
||||
hidden_size: int
|
||||
eps: float = 1e-6
|
||||
|
||||
|
||||
@use_kernel_forward_from_hub("RMSNorm")
|
||||
class RMSNorm(nn.Module):
|
||||
def __init__(self, config: RMSNormConfig) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(config.hidden_size))
|
||||
self.variance_epsilon = config.eps
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
quack_fn = _get_quack_rmsnorm() if hidden_states.is_cuda else None
|
||||
if quack_fn is not None:
|
||||
out = quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
|
||||
return _contiguous_grad(out)
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def extra_repr(self):
|
||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||
|
||||
|
||||
class LayerNorm(nn.Module):
|
||||
def __init__(self, dim: int, eps: float = 1e-6):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
|
||||
self.bias = nn.Parameter(torch.zeros(dim, dtype=torch.float32))
|
||||
|
||||
def forward(self, x: torch.Tensor):
|
||||
return F.layer_norm(x.float(), (self.dim,), self.weight.float(), self.bias.float(), self.eps).type_as(x)
|
||||
@@ -1,32 +1,3 @@
|
||||
from dataclasses import dataclass
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.integrations import use_kernel_forward_from_hub
|
||||
|
||||
|
||||
@dataclass
|
||||
class RMSNormConfig:
|
||||
hidden_size: int
|
||||
eps: float = 1e-6
|
||||
|
||||
|
||||
@use_kernel_forward_from_hub("RMSNorm")
|
||||
class RMSNorm(nn.Module):
|
||||
def __init__(self, config: RMSNormConfig) -> None:
|
||||
"""
|
||||
Glm4MoeRMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(config.hidden_size))
|
||||
self.variance_epsilon = config.eps
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def extra_repr(self):
|
||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||
__all__ = ["RMSNorm", "RMSNormConfig"]
|
||||
|
||||
@@ -38,7 +38,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -13,7 +13,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
|
||||
|
||||
@@ -170,10 +170,13 @@ class NemotronHConfig(PretrainedConfig):
|
||||
self.mamba_proj_bias = mamba_proj_bias
|
||||
self.chunk_size = mamba_chunk_size
|
||||
|
||||
# Zamba2MambaMixer compat aliases (read by parent __init__ before NemotronHMamba2Mixer overrides)
|
||||
# Zamba2MambaMixer compat aliases (read by parent __init__ before NemotronHMamba2Mixer overrides).
|
||||
# mamba_expand must give the correct intermediate_size = mamba_num_heads * mamba_head_dim
|
||||
# when Zamba2 computes int(mamba_expand * hidden_size); the config's raw "expand" field
|
||||
# does not satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
|
||||
self.mamba_d_state = ssm_state_size
|
||||
self.mamba_d_conv = mamba_d_conv
|
||||
self.mamba_expand = mamba_expand
|
||||
self.mamba_expand = (mamba_num_heads * mamba_head_dim) / hidden_size
|
||||
self.mamba_ngroups = mamba_n_groups
|
||||
self.mamba_headdim = mamba_head_dim
|
||||
self.n_mamba_heads = mamba_num_heads
|
||||
|
||||
@@ -81,12 +81,44 @@ def _patch_mamba2_use_triton_ssd():
|
||||
logger.info("Patched NemotronHMamba2Mixer to use mamba_ssm Triton SSD kernels")
|
||||
|
||||
|
||||
def _ensure_zamba2_compat(config: NemotronHConfig):
|
||||
"""Add Zamba2-compatible attribute aliases to NemotronHConfig.
|
||||
|
||||
The HF modular NemotronHMamba2Mixer inherits from Zamba2MambaMixer, whose
|
||||
__init__ reads Zamba2-style attribute names before the NemotronH child
|
||||
overrides them. We set the missing aliases so the parent __init__ doesn't
|
||||
crash.
|
||||
|
||||
Critically, ``mamba_expand`` must give ``mamba_num_heads * mamba_head_dim``
|
||||
when multiplied by ``hidden_size``; the config's ``expand`` field does not
|
||||
satisfy this for all model sizes (e.g. Nemotron-3-Nano-30B).
|
||||
"""
|
||||
correct_intermediate = config.mamba_num_heads * config.mamba_head_dim
|
||||
correct_expand = correct_intermediate / config.hidden_size
|
||||
|
||||
aliases = {
|
||||
"mamba_d_state": config.ssm_state_size,
|
||||
"mamba_d_conv": config.conv_kernel,
|
||||
"mamba_ngroups": config.n_groups,
|
||||
"mamba_headdim": config.mamba_head_dim,
|
||||
"n_mamba_heads": config.mamba_num_heads,
|
||||
"add_bias_linear": getattr(config, "use_bias", False),
|
||||
"use_mem_eff_path": True,
|
||||
}
|
||||
for attr, value in aliases.items():
|
||||
if not hasattr(config, attr):
|
||||
setattr(config, attr, value)
|
||||
|
||||
config.mamba_expand = correct_expand
|
||||
|
||||
|
||||
class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual."""
|
||||
|
||||
def __init__(self, config: NemotronHConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
_patch_mamba2_use_triton_ssd()
|
||||
_ensure_zamba2_compat(config)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
self.mamba = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
|
||||
self.mlp = None # No MoE in this layer type
|
||||
|
||||
@@ -378,6 +378,22 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
|
||||
class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
"""Gated softmax attention using PyTorch's scaled_dot_product_attention."""
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
key_states = _repeat_kv(key_states, self.num_key_value_groups)
|
||||
value_states = _repeat_kv(value_states, self.num_key_value_groups)
|
||||
return F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
is_causal=True,
|
||||
scale=self.scaling,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -401,17 +417,7 @@ class Qwen3_5MoeGatedSDPAAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
key_states = _repeat_kv(key_states, self.num_key_value_groups)
|
||||
value_states = _repeat_kv(value_states, self.num_key_value_groups)
|
||||
|
||||
attn_output = F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
is_causal=True,
|
||||
scale=self.scaling,
|
||||
)
|
||||
|
||||
attn_output = self._attention_core(query_states, key_states, value_states)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
attn_output = attn_output.view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate)
|
||||
@@ -446,6 +452,16 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -474,9 +490,14 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
attn_output = out.contiguous().view(*input_shape, -1)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate)
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, None
|
||||
|
||||
@@ -31,7 +31,7 @@ from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.trainer.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig
|
||||
from prime_rl.trainer.models.qwen3_moe.converting_qwen3_moe import (
|
||||
|
||||
@@ -37,7 +37,6 @@ class ParallelDims:
|
||||
dp_replicate: int
|
||||
dp_shard: int
|
||||
cp: int
|
||||
tp: int
|
||||
pp: int
|
||||
ep: int
|
||||
world_size: int
|
||||
@@ -50,25 +49,24 @@ class ParallelDims:
|
||||
self._validate()
|
||||
|
||||
def _validate(self):
|
||||
dp_replicate, dp_shard, cp, tp, pp, ep = (
|
||||
dp_replicate, dp_shard, cp, pp, ep = (
|
||||
self.dp_replicate,
|
||||
self.dp_shard,
|
||||
self.cp,
|
||||
self.tp,
|
||||
self.pp,
|
||||
self.ep,
|
||||
)
|
||||
for d in (dp_replicate, cp, tp, pp, ep):
|
||||
for d in (dp_replicate, cp, pp, ep):
|
||||
assert d >= 1, "Parallelism degree should be >= 1, except for dp_shard"
|
||||
|
||||
assert dp_shard == -1 or dp_shard >= 1, " dp_shard must -1 or >=1."
|
||||
if dp_shard < 0:
|
||||
self.dp_shard = dp_shard = self.world_size // (dp_replicate * cp * tp * pp)
|
||||
self.dp_shard = dp_shard = self.world_size // (dp_replicate * cp * pp)
|
||||
assert dp_shard >= 1
|
||||
|
||||
assert dp_replicate * dp_shard * cp * tp * pp == self.world_size, (
|
||||
assert dp_replicate * dp_shard * cp * pp == self.world_size, (
|
||||
f"Invalid parallel dims: dp_replicate({dp_replicate}) * dp_shard({dp_shard}) * "
|
||||
f"cp({cp}) * tp({tp}) * pp({pp}) != WORLD_SIZE({self.world_size})"
|
||||
f"cp({cp}) * pp({pp}) != WORLD_SIZE({self.world_size})"
|
||||
)
|
||||
|
||||
if ep > 1:
|
||||
@@ -97,9 +95,8 @@ class ParallelDims:
|
||||
dp_shard_mod_ep,
|
||||
dp_shard_in_ep,
|
||||
self.cp,
|
||||
self.tp,
|
||||
],
|
||||
["pp", "dp_replicate", "dp_shard_mod_ep", "dp_shard_in_ep", "cp", "tp"],
|
||||
["pp", "dp_replicate", "dp_shard_mod_ep", "dp_shard_in_ep", "cp"],
|
||||
):
|
||||
# dp_shard_mod_ep is needed even if it's 1, whose FSDP wrapping
|
||||
# helps the MoE layers do mixed precision training
|
||||
@@ -158,8 +155,8 @@ class ParallelDims:
|
||||
dims = []
|
||||
names = []
|
||||
for d, name in zip(
|
||||
[self.pp, self.dp_replicate, self.dp_shard, self.cp, self.tp],
|
||||
["pp", "dp_replicate", "dp_shard", "cp", "tp"],
|
||||
[self.pp, self.dp_replicate, self.dp_shard, self.cp],
|
||||
["pp", "dp_replicate", "dp_shard", "cp"],
|
||||
):
|
||||
if d > 1 or name == "dp_shard":
|
||||
dims.append(d)
|
||||
@@ -245,10 +242,6 @@ class ParallelDims:
|
||||
def fsdp_enabled(self):
|
||||
return self.dp_shard_enabled or self.cp_enabled
|
||||
|
||||
@property
|
||||
def tp_enabled(self):
|
||||
return self.tp > 1
|
||||
|
||||
@property
|
||||
def pp_enabled(self):
|
||||
return self.pp > 1
|
||||
@@ -263,17 +256,14 @@ class ParallelDims:
|
||||
|
||||
@cached_property
|
||||
def non_data_parallel_size(self):
|
||||
return self.cp * self.tp * self.pp
|
||||
return self.cp * self.pp
|
||||
|
||||
@cached_property
|
||||
def seq_len_divisor(self):
|
||||
# Sequence Parallel requires that seq_len be divisible by TP degree.
|
||||
# https://github.com/pytorch/torchtitan/pull/640#discussion_r1849481001
|
||||
|
||||
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
|
||||
# when load balancing is enabled (by default).
|
||||
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
|
||||
return self.tp * (self.cp * 2)
|
||||
return self.cp * 2
|
||||
|
||||
@cached_property
|
||||
def logger(self):
|
||||
@@ -286,7 +276,6 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
|
||||
dp_replicate=config.dp_replicate,
|
||||
dp_shard=-1,
|
||||
cp=config.cp,
|
||||
tp=config.tp,
|
||||
pp=1,
|
||||
ep=config.ep,
|
||||
world_size=dist.get_world_size(),
|
||||
@@ -297,8 +286,7 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
|
||||
raise ValueError(
|
||||
f"Sequence length ({seq_len}) must be divisible by "
|
||||
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
|
||||
f"This requirement comes from context parallel (CP={config.cp}) and "
|
||||
f"tensor parallel (TP={config.tp}) configurations."
|
||||
f"This requirement comes from context parallel (CP={config.cp})."
|
||||
)
|
||||
|
||||
return parallel_dims
|
||||
|
||||
@@ -47,7 +47,7 @@ from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.utils import clean_exit, to_col_format
|
||||
import torch.distributed as dist
|
||||
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss
|
||||
from prime_rl.trainer.models.layers.lm_head import FusedCrossEntropyOutputLinear
|
||||
from prime_rl.trainer.models.layers.lm_head import FUSED_CE_IGNORE_INDEX
|
||||
|
||||
from torchtitan.distributed.utils import clip_grad_norm_
|
||||
|
||||
@@ -89,10 +89,10 @@ def train(config: SFTConfig):
|
||||
# Initialize parallel dimensions
|
||||
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
|
||||
|
||||
total_micro_batches = config.data.batch_size * config.model.cp * config.model.tp
|
||||
total_micro_batches = config.data.batch_size * config.model.cp
|
||||
micro_batches_per_step = world.world_size * config.data.micro_batch_size
|
||||
assert total_micro_batches % micro_batches_per_step == 0, (
|
||||
f"batch_size * cp * tp ({total_micro_batches}) must be divisible by "
|
||||
f"batch_size * cp ({total_micro_batches}) must be divisible by "
|
||||
f"world_size * micro_batch_size ({micro_batches_per_step})"
|
||||
)
|
||||
grad_accum_steps = total_micro_batches // micro_batches_per_step
|
||||
@@ -119,9 +119,8 @@ def train(config: SFTConfig):
|
||||
# Initialize the model and tokenizer
|
||||
logger.info(f"Initializing model ({config.model})")
|
||||
loading_from_ckpt_later = config.ckpt and checkpoint_step is not None
|
||||
model = setup_model(
|
||||
config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=config.loss_impl == "liger_fused"
|
||||
)
|
||||
fused_cross_entropy: bool | str = {"liger_fused": "liger", "quack_fused": "quack"}.get(config.loss_impl, False)
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=fused_cross_entropy)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
@@ -152,7 +151,7 @@ def train(config: SFTConfig):
|
||||
|
||||
# Set up the dataset and dataloader
|
||||
logger.info(f"Initializing data ({config.data})")
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp * config.model.tp)
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
@@ -193,7 +192,7 @@ def train(config: SFTConfig):
|
||||
ce_loss = LigerCrossEntropyLoss(reduction="none")
|
||||
case "torch":
|
||||
ce_loss = CrossEntropyLoss(reduction="none")
|
||||
case "liger_fused":
|
||||
case "liger_fused" | "quack_fused":
|
||||
pass # loss is computed inside the fused lm_head
|
||||
case _:
|
||||
raise ValueError(f"Invalid loss implementation: {config.loss_impl}")
|
||||
@@ -216,9 +215,9 @@ def train(config: SFTConfig):
|
||||
token_count = loss_mask.sum(dtype=torch.int64)
|
||||
|
||||
with maybe_activation_offloading(config.model.ac_offloading):
|
||||
if config.loss_impl == "liger_fused":
|
||||
if config.loss_impl in ("liger_fused", "quack_fused"):
|
||||
masked_target_ids = target_ids.clone()
|
||||
masked_target_ids[~loss_mask] = FusedCrossEntropyOutputLinear.IGNORE_INDEX
|
||||
masked_target_ids[~loss_mask] = FUSED_CE_IGNORE_INDEX
|
||||
out = forward(model, input_ids, position_ids, labels=masked_target_ids)
|
||||
loss_sum = out["loss"] * token_count
|
||||
else:
|
||||
@@ -258,7 +257,7 @@ def train(config: SFTConfig):
|
||||
|
||||
def run_validation(step: int) -> None:
|
||||
val_dataset = setup_dataset(
|
||||
tokenizer, config.val.data, config.model.cp * config.model.tp, max_epochs=1, raw_dataset=val_raw_dataset
|
||||
tokenizer, config.val.data, config.model.cp, max_epochs=1, raw_dataset=val_raw_dataset
|
||||
)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
|
||||
@@ -410,8 +409,8 @@ def train(config: SFTConfig):
|
||||
memory_profiler.step()
|
||||
|
||||
# Compute step metrics
|
||||
# Divide by CP and TP since those ranks process the same data
|
||||
num_tokens = config.data.batch_size * config.data.seq_len // (config.model.cp * config.model.tp)
|
||||
# Divide by CP since those ranks process the same data
|
||||
num_tokens = config.data.batch_size * config.data.seq_len // config.model.cp
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples = dataset.step
|
||||
perf_counter = get_perf_counter(model, config.data.seq_len)
|
||||
|
||||
@@ -154,3 +154,8 @@ def test_cli_overrides_toml(tmp_path):
|
||||
def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
with pytest.raises(ValidationError, match="fused_lm_head_chunk_size"):
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_selective_activation_checkpointing_requires_custom_impl():
|
||||
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
|
||||
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
|
||||
|
||||
@@ -14,7 +14,6 @@ supported-markers = [
|
||||
overrides = [
|
||||
{ name = "nvidia-cudnn-cu12", specifier = ">=9.15" },
|
||||
{ name = "nvidia-cutlass-dsl", specifier = ">=4.4.1" },
|
||||
{ name = "quack-kernels", specifier = ">=0.2.7" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=5c1c72b" },
|
||||
]
|
||||
|
||||
@@ -851,15 +850,14 @@ requires-dist = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flash-attn-cute"
|
||||
version = "0.1.0"
|
||||
source = { git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=e2743ab5#e2743ab5b3803bb672b16437ba98a3b1d4576c50" }
|
||||
name = "flash-attn-4"
|
||||
version = "4.0.0b6.dev7+gabd9943"
|
||||
source = { git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=abd9943b#abd9943b66704f650ea1485a17126cd3817d1b1d" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "nvidia-cutlass-dsl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "quack-kernels", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "torch-c-dlpack-ext", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
@@ -2543,7 +2541,7 @@ disagg = [
|
||||
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "nixl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
envs = [
|
||||
{ name = "aime2024", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -2566,7 +2564,10 @@ flash-attn-3 = [
|
||||
{ name = "flash-attn-3", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
flash-attn-cute = [
|
||||
{ name = "flash-attn-cute", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "flash-attn-4", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
quack = [
|
||||
{ name = "quack-kernels", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
|
||||
[package.dev-dependencies]
|
||||
@@ -2596,7 +2597,7 @@ requires-dist = [
|
||||
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
|
||||
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-3", marker = "platform_machine == 'x86_64' and extra == 'flash-attn-3'", url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-cute", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=e2743ab5" },
|
||||
{ name = "flash-attn-4", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=abd9943b" },
|
||||
{ name = "flash-linear-attention", git = "https://github.com/fla-org/flash-linear-attention" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
{ name = "liger-kernel", specifier = ">=0.5.10" },
|
||||
@@ -2614,6 +2615,7 @@ requires-dist = [
|
||||
{ name = "pydantic", specifier = ">=1.10.13" },
|
||||
{ name = "pydantic-config", git = "https://github.com/samsja/pydantic_config.git?branch=main" },
|
||||
{ name = "pyzmq", specifier = ">=27.1.0" },
|
||||
{ name = "quack-kernels", marker = "extra == 'quack'", specifier = ">=0.3.3" },
|
||||
{ name = "reverse-text", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
{ name = "rich", specifier = ">=14.0.0" },
|
||||
{ name = "ring-flash-attn", specifier = ">=0.1.8" },
|
||||
@@ -2627,13 +2629,13 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=5c1c72b" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=f5580acd" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=0db45e6" },
|
||||
{ name = "vllm", specifier = ">=0.17.0" },
|
||||
{ name = "vllm-router", marker = "extra == 'disagg'", url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
{ name = "wiki-search", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
]
|
||||
provides-extras = ["flash-attn", "flash-attn-3", "flash-attn-cute", "envs", "disagg"]
|
||||
provides-extras = ["flash-attn", "flash-attn-3", "flash-attn-cute", "envs", "disagg", "quack"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
@@ -3036,7 +3038,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "quack-kernels"
|
||||
version = "0.2.10"
|
||||
version = "0.3.6"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -3044,9 +3046,9 @@ dependencies = [
|
||||
{ name = "torch", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "torch-c-dlpack-ext", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/23/28/231c862500fec531080cc733e5766b46518edaefe0a068d46b276c380a25/quack_kernels-0.2.10.tar.gz", hash = "sha256:df86e981ea76542467ae2cd9ac606d587658e8d648a51c34dc0f2913a3e26bf6", size = 161102, upload-time = "2026-02-18T22:20:50.17Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/75/af/5b77f565d4268905eb7e7fe3367f877ae98d0cae920c6d9f2d019a39f214/quack_kernels-0.3.6.tar.gz", hash = "sha256:43af5a1f31099682cb1c53aa835fcdfebeb88d917c08aa342b959af88c6e8749", size = 192593, upload-time = "2026-03-24T13:30:00.923Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/10/ac/8f70ddd397aff1d606d7aa6fbe857a2bc58a817965099cd97d91264175a8/quack_kernels-0.2.10-py3-none-any.whl", hash = "sha256:a5b604c5cf28d9e601aae00488b6b603bb4060ccab8409a4443e72a649226f74", size = 165298, upload-time = "2026-02-18T22:20:48.978Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8e/28/e688da97806474963b2983a8231572733de11ed48f8899410c0afc8bdf15/quack_kernels-0.3.6-py3-none-any.whl", hash = "sha256:973d974ccca816014006af8f136294ba0f15b1c324197f8b54ffc6500666e0e5", size = 198865, upload-time = "2026-03-24T13:29:59.107Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3827,8 +3829,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.11"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=f5580acd#f5580acd7dfbea25f370cc8fd3ec0ec2974693c4" }
|
||||
version = "0.1.12.dev1"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=0db45e6#0db45e6f4d8b20fb6ecfbb0e06138735ec4f3d99" }
|
||||
dependencies = [
|
||||
{ name = "aiolimiter", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "anthropic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -3951,12 +3953,12 @@ name = "vllm-router"
|
||||
version = "0.1.11"
|
||||
source = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "fastapi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "orjson", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "requests", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "setproctitle", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "uvicorn", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "aiohttp", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "fastapi", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "orjson", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "requests", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "setproctitle", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "uvicorn", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.3/vllm_router-0.1.11-cp38-abi3-linux_x86_64.whl", hash = "sha256:43c96cebde3d59f88c0e84fe735bba5ccb6a308d3305c80ffc3723194a5f7230" },
|
||||
|
||||
Reference in New Issue
Block a user