TRL changes the Inkling 2 Mini recipe runs on, relative to upstream huggingface/trl. upstream base: d115286bc5aef8d346e8510bfe312803c7881c4a (2026-11-11, Add UDPO loss for noisy preferences to DPOTrainer (#8211)) source: the trl-inkling-exp worktree: younesbelkada/trl async-grpo-shared-vllm (e498acc6) plus uncommitted Inkling changes (Inkling 2 Loop tree packing, the adapter rename for vLLM) Apply on a checkout of the upstream base: git apply trl.patch (train_hf_jobs.sh does this and builds a wheel) Regenerate: git diff d115286bc5aef8d346e8510bfe312803c7881c4a -- trl/, plus git diff --no-index /dev/null for each untracked file under trl/ diff --git a/trl/experimental/async_distillation/async_distillation_config.py b/trl/experimental/async_distillation/async_distillation_config.py index bc1d422e..38a1e7a2 100644 --- a/trl/experimental/async_distillation/async_distillation_config.py +++ b/trl/experimental/async_distillation/async_distillation_config.py @@ -84,6 +84,9 @@ class AsyncDistillationConfig(_BaseConfig): Timeout in seconds for calls to the vLLM servers: waiting for the student's server to be ready at startup, each generation or scoring request, and each weight-sync call. Waiting for the server and weight-sync calls raise when it runs out; a generation or scoring request that times out is retried. + vllm_lora_name (`str`, *optional*, defaults to `"trl-policy"`): + Prefix of the adapter names published to the student's vLLM server under adapter-only sync + (`{vllm_lora_name}-v{N}`). Give each trainer its own prefix when several share one server. teacher_server_urls (`dict[str, str]`, *optional*, defaults to `{"default": "http://localhost:8001"}`): Teacher vLLM server(s), each started with `vllm serve --logprobs-mode processed_logprobs --max-logprobs -1`. Every teacher is static: this trainer never streams weight updates to any of them, so a @@ -295,6 +298,13 @@ class AsyncDistillationConfig(_BaseConfig): "weight-sync calls raise when it runs out; a generation or scoring request that times out is retried." }, ) + vllm_lora_name: str = field( + default="trl-policy", + metadata={ + "help": "Prefix of the adapter names published to the student's vLLM server under adapter-only sync " + "(`{vllm_lora_name}-v{N}`). Give each trainer its own prefix when several share one server." + }, + ) teacher_server_urls: dict[str, str] | str | None = field( default=None, metadata={ diff --git a/trl/experimental/async_distillation/async_distillation_trainer.py b/trl/experimental/async_distillation/async_distillation_trainer.py index 69a5da64..b42c97c9 100644 --- a/trl/experimental/async_distillation/async_distillation_trainer.py +++ b/trl/experimental/async_distillation/async_distillation_trainer.py @@ -1348,7 +1348,7 @@ class AsyncDistillationTrainer(_BaseTrainer): # Adapter-only vLLM sync is derived from a PEFT model plus a server started with `--enable-lora`, rather # than configured. Rank 0 probes and broadcasts the answer below. self._lora_sync = False - self._lora_name = "trl-policy" + self._lora_name = self.args.vllm_lora_name # Absolute: the path is resolved by the *server's* process, which has its own working directory and may not # be on this machine. vLLM reads a path it cannot resolve as a Hub repo id, failing deep inside the engine. self._lora_dir = os.path.abspath(os.path.join(self.args.output_dir, ".vllm_lora")) @@ -1967,11 +1967,10 @@ class AsyncDistillationTrainer(_BaseTrainer): # Under DDP `self.model` is the wrapper, which does not expose `save_pretrained`. model = self.accelerator.unwrap_model(self.model) - logger.info("Weight sync: pausing vLLM...") - if self.accelerator.is_main_process: - self.vllm_client.pause() + # No `/pause`: in-flight requests keep the adapter they named, and pausing would stall every other trainer + # sharing this server. t_pause = time.time() - logger.info(f"Weight sync: pause took {t_pause - t0:.1f}s, waiting for all ranks...") + logger.info("Weight sync: waiting for all ranks...") self.accelerator.wait_for_everyone() t_barrier = time.time() @@ -1984,12 +1983,11 @@ class AsyncDistillationTrainer(_BaseTrainer): self.accelerator.wait_for_everyone() - logger.info(f"Weight sync: resuming vLLM... (transfer took {t_transfer - t_barrier:.1f}s)") + logger.info(f"Weight sync: loading adapter... (transfer took {t_transfer - t_barrier:.1f}s)") if self.accelerator.is_main_process: # The adapter has to exist on the server BEFORE the version moves below: the rollout worker derives the # adapter it requests from `model_version`, so bumping first would name one that is not loaded yet. self.vllm_client.load_lora_adapter(f"{self._lora_name}-v{version}", adapter_dir) - self.vllm_client.resume() stale_version = version - (self.args.max_staleness + 1) if stale_version > 0: self.vllm_client.unload_lora_adapter(f"{self._lora_name}-v{stale_version}") diff --git a/trl/experimental/async_grpo/async_grpo_config.py b/trl/experimental/async_grpo/async_grpo_config.py index 6335eb5f..26a20220 100644 --- a/trl/experimental/async_grpo/async_grpo_config.py +++ b/trl/experimental/async_grpo/async_grpo_config.py @@ -88,6 +88,9 @@ class AsyncGRPOConfig(_BaseConfig): Timeout in seconds for calls to the vLLM server: waiting for it to be ready at startup, each generation request, and each weight-sync call. Waiting for the server and weight-sync calls raise when it runs out; a generation request that times out is retried. + vllm_lora_name (`str`, *optional*, defaults to `"trl-policy"`): + Prefix of the adapter names published to the vLLM server under adapter-only sync (`{vllm_lora_name}-v{N}`). + Give each trainer its own prefix when several share one server. > Parameters that control the training @@ -296,6 +299,13 @@ class AsyncGRPOConfig(_BaseConfig): "it runs out; a generation request that times out is retried." }, ) + vllm_lora_name: str = field( + default="trl-policy", + metadata={ + "help": "Prefix of the adapter names published to the vLLM server under adapter-only sync " + "(`{vllm_lora_name}-v{N}`). Give each trainer its own prefix when several share one server." + }, + ) # Parameters that control the training epsilon: float = field( diff --git a/trl/experimental/async_grpo/async_grpo_trainer.py b/trl/experimental/async_grpo/async_grpo_trainer.py index d716d5c7..2296d12f 100644 --- a/trl/experimental/async_grpo/async_grpo_trainer.py +++ b/trl/experimental/async_grpo/async_grpo_trainer.py @@ -36,6 +36,7 @@ from accelerate.logging import get_logger from accelerate.utils import broadcast_object_list, is_peft_model, set_seed from datasets import Dataset, IterableDataset from packaging.version import Version +from safetensors.torch import load_file, save_file from torch.distributed._tensor import DTensor from torch.utils.data import DataLoader from transformers import AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, TrainerCallback @@ -60,7 +61,15 @@ from ...trainer.utils import ( ) from .async_grpo_config import AsyncGRPOConfig from .async_rollout_worker import AsyncRolloutLoop, AsyncRolloutWorker, RolloutSample -from .packing import TREE_ATTENTION, TreeRow, patch_tree_gdn, register_tree_attention, unpad_tree +from .packing import ( + TREE_ATTENTION, + TreeRow, + patch_tree_gdn, + patch_tree_inkling2_loop, + patch_tree_qwen4_exp, + register_tree_attention, + unpad_tree, +) from .vllm_client import VLLMClient from .weight_transfer import WeightTransferClient @@ -688,6 +697,19 @@ def validate_lora_for_vllm_sync(model: "PeftModel") -> "LoraConfig": return peft_config +# transformers renames Inkling 2 Loop's checkpoint on load; vLLM keeps the checkpoint's names and loads LoRA by them +_INKLING2_LOOP_VLLM_NAMES = [ + (".language_model.layers.", ".llm.layers."), + (".self_attn.q_proj.linear.", ".attn.wq_du."), + (".self_attn.k_proj.linear.", ".attn.wk_dv."), + (".self_attn.v_proj.linear.", ".attn.wv_dv."), + (".self_attn.o_proj.linear.", ".attn.wo_ud."), + (".self_attn.o_proj.gate_proj.", ".attn.gate_attn."), + (".self_attn.relative_position_bias.linear.", ".attn.wr_du."), + (".self_attn.sink_proj.", ".attn.attn_sink_proj."), +] + + def save_lora_adapter(model: "PeftModel", accelerator: Accelerator, adapter_name: str, dest_dir: str) -> None: """ Save one PEFT adapter to `dest_dir`, gathering sharded parameters as needed. @@ -732,6 +754,21 @@ def save_lora_adapter(model: "PeftModel", accelerator: Accelerator, adapter_name # PEFT nests every adapter but `"default"` in a subdirectory, while vLLM expects `adapter_config.json` at the root # of the path it is handed. saved_dir = tmp_dir if adapter_name == "default" else os.path.join(tmp_dir, adapter_name) + if model.config.model_type == "inkling2_loop": + weights_path = os.path.join(saved_dir, "adapter_model.safetensors") + tensors = {} + for name, tensor in load_file(weights_path).items(): + for old, new in _INKLING2_LOOP_VLLM_NAMES: + name = name.replace(old, new) + tensors[name] = tensor + save_file(tensors, weights_path) + # vLLM checks `target_modules` against its own module names too + config_path = os.path.join(saved_dir, "adapter_config.json") + with open(config_path) as f: + adapter_config = json.load(f) + adapter_config["target_modules"] = sorted({name.split(".lora_")[0].rsplit(".", 1)[-1] for name in tensors}) + with open(config_path, "w") as f: + json.dump(adapter_config, f, indent=2) shutil.rmtree(dest_dir, ignore_errors=True) os.rename(saved_dir, dest_dir) # atomic within one filesystem shutil.rmtree(tmp_dir, ignore_errors=True) @@ -1007,19 +1044,26 @@ class AsyncGRPOTrainer(_BaseTrainer): text_config = model.config.get_text_config() layer_types = set(getattr(text_config, "layer_types", None) or []) - {"full_attention", "sliding_attention"} + # Inkling 2 Loop's hybrid layers are attention plus short convolutions: once patched, nothing is left to check + if layer_types <= {"hybrid", "hybrid_sliding"} and layer_types and patch_tree_inkling2_loop(model): + layer_types = set() # Check tree attention compat if layer_types: - if layer_types == {"linear_attention"} and Version(transformers.__version__) < Version("5.15.0"): + if "linear_attention" in layer_types and Version(transformers.__version__) < Version("5.15.0"): raise ValueError( f"Tree packing of {type(model).__name__}'s gated DeltaNet layers requires transformers>=5.15.0: " "before it, these layers call the functions they stored at init rather than the module-level " "ones tree packing patches, so they would scan across samples." ) - if layer_types != {"linear_attention"} or not patch_tree_gdn(model): + # Qwen4-Exp's indexed attention and n-gram embedding read across tokens too: patched for that model only + supported = ( + {"linear_attention", "indexed_attention"} if patch_tree_qwen4_exp(model) else {"linear_attention"} + ) + if not layer_types <= supported or not patch_tree_gdn(model): raise ValueError( f"{type(model).__name__} has {sorted(layer_types)} layers. Tree packing routes attention and " - "transformers' gated DeltaNet layers along each sample's own path; any other recurrent or " - "convolutional layer would scan across samples." + "transformers' gated DeltaNet layers and Inkling 2 Loop's hybrid layers along each sample's own " + "path; any other recurrent or convolutional layer would scan across samples." ) if any(name.endswith(".sinks") for name, _ in model.named_parameters()): raise ValueError( @@ -1247,7 +1291,7 @@ class AsyncGRPOTrainer(_BaseTrainer): # Adapter-only vLLM sync is derived from a PEFT model plus a server started with `--enable-lora`, rather # than configured. Rank 0 probes and broadcasts the answer below. self._lora_sync = False - self._lora_name = "trl-policy" + self._lora_name = self.args.vllm_lora_name # Absolute: the path is resolved by the *server's* process, which has its own working directory and may not # be on this machine. vLLM reads a path it cannot resolve as a Hub repo id, failing deep inside the engine. self._lora_dir = os.path.abspath(os.path.join(self.args.output_dir, ".vllm_lora")) @@ -1457,8 +1501,9 @@ class AsyncGRPOTrainer(_BaseTrainer): **router_kwargs, **unpad_tree(inputs), ) - log_probs = outputs.log_probs.flatten()[token_index] - entropy = outputs.entropy.flatten()[token_index] + # With a model split over GPUs (`device_map`), the outputs are on the last GPU and the inputs on the first + log_probs = outputs.log_probs.flatten().to(token_index.device)[token_index] + entropy = outputs.entropy.flatten().to(token_index.device)[token_index] self._last_forward_time_s = time.time() - forward_start log_ratio = log_probs - old_log_probs @@ -1467,7 +1512,7 @@ class AsyncGRPOTrainer(_BaseTrainer): is_masked = (coef_1 < low) | (coef_1 > high) if self.args.score_centering: # Score centering: https://huggingface.co/papers/2609.20807, Appendix A.2 - score_log_probs = outputs.score_log_probs[0][token_index] + score_log_probs = outputs.score_log_probs[0].to(token_index.device)[token_index] sampler_log_probs = inputs["sampler_log_probs"][mask_bool][token_index] with torch.no_grad(): q = sampler_log_probs.exp() @@ -1496,7 +1541,7 @@ class AsyncGRPOTrainer(_BaseTrainer): # The policy loss above is scaled for gradient accumulation (HF auto-scaling is off here), so scale aux too if self.aux_loss_enabled: - aux_loss = outputs.aux_loss + aux_loss = outputs.aux_loss.to(loss.device) loss = loss + self.router_aux_loss_coef * aux_loss / self.current_gradient_accumulation_steps with torch.no_grad(): @@ -1799,11 +1844,10 @@ class AsyncGRPOTrainer(_BaseTrainer): # Under DDP `self.model` is the wrapper, which does not expose `save_pretrained`. model = self.accelerator.unwrap_model(self.model) - logger.info("Weight sync: pausing vLLM...") - if self.accelerator.is_main_process: - self.vllm_client.pause() + # No `/pause`: in-flight requests keep the adapter they named, and pausing would stall every other trainer + # sharing this server. t_pause = time.time() - logger.info(f"Weight sync: pause took {t_pause - t0:.1f}s, waiting for all ranks...") + logger.info("Weight sync: waiting for all ranks...") self.accelerator.wait_for_everyone() t_barrier = time.time() @@ -1816,12 +1860,11 @@ class AsyncGRPOTrainer(_BaseTrainer): self.accelerator.wait_for_everyone() - logger.info(f"Weight sync: resuming vLLM... (transfer took {t_transfer - t_barrier:.1f}s)") + logger.info(f"Weight sync: loading adapter... (transfer took {t_transfer - t_barrier:.1f}s)") if self.accelerator.is_main_process: # The adapter has to exist on the server BEFORE the version moves below: the rollout worker derives the # adapter it requests from `model_version`, so bumping first would name one that is not loaded yet. self.vllm_client.load_lora_adapter(f"{self._lora_name}-v{version}", adapter_dir) - self.vllm_client.resume() stale_version = version - (self.args.max_staleness + 1) if stale_version > 0: self.vllm_client.unload_lora_adapter(f"{self._lora_name}-v{stale_version}") diff --git a/trl/experimental/async_grpo/async_rollout_worker.py b/trl/experimental/async_grpo/async_rollout_worker.py index 754a02d4..d55e043d 100644 --- a/trl/experimental/async_grpo/async_rollout_worker.py +++ b/trl/experimental/async_grpo/async_rollout_worker.py @@ -564,6 +564,9 @@ class AsyncRolloutLoop: max_workers=max(1, config.max_concurrent_rollouts), thread_name_prefix="grpo-tool" ) + # Starts at the requested concurrency, not at `KV cache tokens / max_model_len`: agent rollouts use a small + # fraction of max_model_len, and growing 25% per turnover of the pool took hours when rollouts last minutes. + # The control loop still cuts it when the server's KV cache fills up. self._kv_cap = config.max_concurrent_rollouts self._total_rollouts = 0 self._metrics_poll_s = 5.0 @@ -667,7 +670,6 @@ class AsyncRolloutLoop: async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session: self.session = session await self._check_sampling_replay() - await self._init_kv_cap() logger.info( f"vllm worker started: num_generations={self.config.num_generations}, " f"max_concurrent_rollouts={self.config.max_concurrent_rollouts}, kv_cap={self._kv_cap}, " @@ -694,26 +696,6 @@ class AsyncRolloutLoop: expected_tokens = self._produced_tokens + self._rollouts_unqueued * self._tokens_per_rollout return expected_tokens < self._token_allowance.value - async def _init_kv_cap(self) -> None: - """Start the cap at `KV cache tokens / max_model_len`: as many requests as fit at full length.""" - try: - async with self.session.get(f"{self.vllm_server_url}/metrics") as response: - response.raise_for_status() - text = await response.text() - async with self.session.get(f"{self.vllm_server_url}/v1/models") as response: - response.raise_for_status() - models = await response.json() - except Exception as e: - logger.warning(f"Could not read the vLLM server's KV capacity, starting at max_concurrent_rollouts: {e!r}") - return - kv_matches = re.findall(r'^vllm:cache_config_info\{.*kv_cache_size_tokens="(\d+)"', text, re.M) - if not kv_matches: - logger.warning("`/metrics` has no `kv_cache_size_tokens`, starting at max_concurrent_rollouts") - return - kv_tokens = sum(map(int, kv_matches)) - max_model_len = max(model["max_model_len"] for model in models["data"] if model["max_model_len"]) - self._kv_cap = max(1, min(self.config.max_concurrent_rollouts, kv_tokens // max_model_len)) - async def _control_loop(self, stop_event: asyncio.Event) -> None: """Size the KV cap from the vLLM server's load, polled from `/metrics`. diff --git a/trl/experimental/async_grpo/openenv_harness.py b/trl/experimental/async_grpo/openenv_harness.py index 1958e09c..f434e4bd 100644 --- a/trl/experimental/async_grpo/openenv_harness.py +++ b/trl/experimental/async_grpo/openenv_harness.py @@ -161,6 +161,17 @@ class _HarnessRolloutLoop(AsyncRolloutLoop): if correctness is not None: self._rates["rollout/correctness_mean"][0] += correctness self._rates["rollout/correctness_mean"][1] += 1.0 + # Tool calls, output tokens and thinking of solved rollouts only: the cost of a solution, unmixed with + # failed attempts + if correctness >= 1.0: + self._rates["rollout/solved_tool_calls_mean"][0] += sum(metrics["tool_calls_by_name"].values()) + self._rates["rollout/solved_tool_calls_mean"][1] += 1.0 + self._rates["rollout/solved_completion_tokens_mean"][0] += metrics["completion_tokens"] + self._rates["rollout/solved_completion_tokens_mean"][1] += 1.0 + self._rates["rollout/solved_thinking_chars_mean"][0] += metrics["thinking_chars"] + self._rates["rollout/solved_thinking_chars_mean"][1] += 1.0 + metrics.pop("completion_tokens") + metrics.pop("thinking_chars") for name, count in metrics.pop("tool_calls_by_name").items(): self._counters[f"tools/{name}/call_count"] += count for name, count in metrics.pop("tool_failures_by_name").items(): @@ -302,6 +313,8 @@ class _HarnessRolloutLoop(AsyncRolloutLoop): tool_calls_by_name=tool_calls_by_name, tool_failures_by_name=tool_failures_by_name, tool_latency=tool_latency, + completion_tokens=len(completion_ids), + thinking_chars=_thinking_chars(trace), ) if self._rollout_reward_fn is not None and env_reward is not None: metrics["correctness"] = env_reward @@ -400,6 +413,20 @@ def _tool_failures_by_name(entries: list[TraceEntry]) -> dict[str, int]: return failures +def _thinking_chars(entries: list[TraceEntry]) -> int: + """Characters of reasoning text over a rollout's captured model calls. + + vLLM's reasoning parser returns it apart from the answer, as `reasoning_content` (or `reasoning` in newer versions); + the engine reports no separate token count for it. Calls without a captured response count 0. + """ + total = 0 + for entry in entries: + choices = (entry.get("response") or {}).get("choices") or [] + message = choices[0].get("message") or {} if choices else {} + total += len(message.get("reasoning_content") or message.get("reasoning") or "") + return total + + def _messages_from_trace(entries: list[TraceEntry]) -> list[Message]: """Return the last selected request's messages followed by its assistant reply.""" if not entries: diff --git a/trl/experimental/async_grpo/packing.py b/trl/experimental/async_grpo/packing.py index 9d5a54b6..e67362ee 100644 --- a/trl/experimental/async_grpo/packing.py +++ b/trl/experimental/async_grpo/packing.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import copy import math import sys from functools import cache @@ -300,13 +301,180 @@ def patch_tree_gdn(model) -> bool: def causal_conv1d_fn(hidden_states, weight, bias=None, activation=None, **kwargs): if "tree_segment_parents" not in kwargs: return conv(hidden_states, weight, bias, activation=activation, **kwargs) - return tree_causal_conv1d(hidden_states, weight, bias, activation, kwargs, conv) + # Triton launches on the current device, not the inputs': with a model split over GPUs (`device_map`), a layer + # on another GPU would run on the wrong stream and read inputs not yet written + with torch.cuda.device(hidden_states.device): + return tree_causal_conv1d(hidden_states, weight, bias, activation, kwargs, conv) def torch_chunk_gated_delta_rule(query, key, value, g, beta, use_qk_l2norm_in_kernel=False, **kwargs): if "tree_segment_parents" not in kwargs: return chunk(query, key, value, g=g, beta=beta, use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, **kwargs) - return tree_chunk_gated_delta_rule(query, key, value, g, beta, kwargs, use_qk_l2norm_in_kernel), None + with torch.cuda.device(query.device): + return tree_chunk_gated_delta_rule(query, key, value, g, beta, kwargs, use_qk_l2norm_in_kernel), None modeling.causal_conv1d_fn, modeling.torch_chunk_gated_delta_rule = causal_conv1d_fn, torch_chunk_gated_delta_rule _PATCHED.add(modeling) return True + + +_PATCHED_QWEN4_EXP = set() + + +def patch_tree_qwen4_exp(model) -> bool: + """ + Make Qwen4-Exp's indexed attention and per-layer n-gram embedding (PLE) follow the tree of a tree-packed forward. + + Both read across tokens outside the attention interface and the gated DeltaNet functions [`patch_tree_gdn`] wraps: + the indexer picks each query's key blocks among all the tokens it sees, and PLE hashes each token with the ones + before it and runs a dilated convolution over them. Given the tree of [`~packing.TreeRow.pack`], the attention and + PLE forwards follow it (see `tree_qwen4_exp`); otherwise they run unchanged. + + Returns: + `bool`: whether the model's modeling module is Qwen4-Exp's. + """ + modeling = sys.modules[type(model).__module__] + names = ("Qwen4ExpTextAttention", "Qwen4ExpTextPLELayer", "Qwen4ExpTextDecoderLayer") + attention, ple, decoder = (vars(modeling).get(name) for name in names) + if attention is None or ple is None or decoder is None: + return False + # accelerate's `device_map` hooks call the forward a module had when the model was dispatched, saved as + # `_old_forward`: point them at the patched one too, or a split model keeps running the reference + for module in model.modules(): + if isinstance(module, (attention, ple, decoder)) and "_old_forward" in vars(module): + module._old_forward = lambda *args, module=module, **kwargs: type(module).forward(module, *args, **kwargs) + if modeling in _PATCHED_QWEN4_EXP: + return True + from .tree_qwen4_exp import tree_parent_index, tree_ple, tree_qsa_attention + + attention_forward, ple_forward, decoder_forward = attention.forward, ple.forward, decoder.forward + + def attention_forward_(self, hidden_states, position_embeddings, attention_mask, past_key_values=None, **kwargs): + if "tree_kv_index" not in kwargs: + return attention_forward( + self, hidden_states, position_embeddings, attention_mask, past_key_values, **kwargs + ) + # On the inputs' GPU: with a model split over GPUs (`device_map`), the current device is another one + with torch.cuda.device(hidden_states.device): + return tree_qsa_attention( + self, hidden_states, position_embeddings, kwargs, modeling.apply_rotary_pos_emb + ), None + + # The decoder layer calls PLE without the forward's keyword arguments, so it hands PLE the tree here + def decoder_forward_(self, hidden_states, *args, **kwargs): + if self.ple is not None: + tree = "tree_segment_parents" in kwargs + self.ple.tree_parent_index = tree_parent_index(kwargs, hidden_states.shape[1]) if tree else None + return decoder_forward(self, hidden_states, *args, **kwargs) + + def ple_forward_(self, hidden_states, input_ids, past_key_values, conv_mask=None): + if self.tree_parent_index is None: + return ple_forward(self, hidden_states, input_ids, past_key_values, conv_mask=conv_mask) + with torch.cuda.device(hidden_states.device): + return tree_ple(self, hidden_states, input_ids, self.tree_parent_index) + + attention.forward, decoder.forward, ple.forward = attention_forward_, decoder_forward_, ple_forward_ + _PATCHED_QWEN4_EXP.add(modeling) + return True + + +_PATCHED_INKLING2_LOOP = set() +_IN_TREE_FORWARD = set() + + +def patch_tree_inkling2_loop(model) -> bool: + """ + Make Inkling 2 Loop's attention and short convolutions follow the tree of a tree-packed forward. + + Its attention adds a learned bias per query-key distance and a sink logit per query, which the FlashAttention + kernel of [`tree_attention`] cannot, and its short convolutions don't pass the forward's keyword arguments to the + functions [`patch_tree_gdn`] wraps. Given the tree of [`~packing.TreeRow.pack`], the attention and both kinds + of short convolution follow it (see `tree_inkling2_loop`); otherwise they run unchanged. The looped + core works position by position and needs nothing, but its attention residuals, which attend over the depth of one + position through the attention interface, are kept on eager attention so they never reach [`tree_attention`]. + + Returns: + `bool`: whether the model's modeling module is Inkling 2 Loop's. + """ + modeling = sys.modules[type(model).__module__] + names = ( + "Inkling2LoopSlidingAttention", + "Inkling2LoopFullAttention", + "Inkling2LoopShortConvolution", + "Inkling2LoopDynamicShortConvolution", + "Inkling2LoopTextModel", + "Inkling2LoopMessageAttentionResidual", + "Inkling2LoopBlockAttentionResidual", + ) + classes = [vars(modeling).get(name) for name in names] + if any(cls is None for cls in classes): + return False + sliding, full, short_conv, dynamic_conv, text_model, message_residual, block_residual = classes + # Per model: the residuals get their own config, on eager attention, as the model is switched to tree attention + for module in model.modules(): + if isinstance(module, (message_residual, block_residual)): + module.config = copy.copy(module.config) + module.config._attn_implementation = "eager" + # accelerate's `device_map` hooks call the forward a module had when the model was dispatched, saved as + # `_old_forward`: point them at the patched one too, or a split model keeps running the reference + patched = (sliding, full, short_conv, dynamic_conv, text_model) + for module in model.modules(): + if isinstance(module, patched) and "_old_forward" in vars(module): + module._old_forward = lambda *args, module=module, **kwargs: type(module).forward(module, *args, **kwargs) + if modeling in _PATCHED_INKLING2_LOOP: + return True + from .tree_inkling2_loop import ( + tree_dynamic_short_convolution, + tree_inkling2_loop_attention, + tree_short_convolution, + ) + + def follow_tree(cls, tree_forward): + forward = cls.forward + + def wrapper(self, *args, **kwargs): + if "tree_segment_parents" not in kwargs: + return forward(self, *args, **kwargs) + # On the inputs' GPU: with a model split over GPUs (`device_map`), the current device is another one + with torch.cuda.device(next(t for t in (*args, *kwargs.values()) if isinstance(t, torch.Tensor)).device): + return tree_forward(self, *args, **kwargs) + + cls.forward = wrapper + + def attention(self, hidden_states, key_hidden_states=None, value_hidden_states=None, conv_mask=None, **kwargs): + for name in ("attention_mask", "relative_distance", "cache", "cache_offset"): + kwargs.pop(name, None) + return tree_inkling2_loop_attention( + self, hidden_states, key_hidden_states, value_hidden_states, conv_mask, kwargs + ) + + for cls in (sliding, full): + follow_tree(cls, attention) + follow_tree(short_conv, lambda self, hidden_states, *args, **kwargs: tree_short_convolution( + self, modeling.causal_conv1d_fn, hidden_states, kwargs + )) # fmt: skip + follow_tree(dynamic_conv, lambda self, hidden_states, dynamic_input, *args, **kwargs: tree_dynamic_short_convolution( + self, hidden_states, dynamic_input, kwargs + )) # fmt: skip + + # The text model builds dense `(N, N)` relative distances for the reference attention, gigabytes at training lengths. + # The tree attention computes its own from depths, so during a tree-packed forward they are a broadcast placeholder. + get_relative_distance, text_forward = modeling.get_relative_distance, text_model.forward + + def relative_distance(inputs_embeds, cache, is_sliding): + if modeling not in _IN_TREE_FORWARD: + return get_relative_distance(inputs_embeds, cache, is_sliding) + n = inputs_embeds.shape[1] + return torch.zeros((), dtype=torch.long, device=inputs_embeds.device).expand(n, n) + + def text_model_forward(self, *args, **kwargs): + if "tree_segment_parents" not in kwargs: + return text_forward(self, *args, **kwargs) + _IN_TREE_FORWARD.add(modeling) + try: + return text_forward(self, *args, **kwargs) + finally: + _IN_TREE_FORWARD.discard(modeling) + + modeling.get_relative_distance, text_model.forward = relative_distance, text_model_forward + _PATCHED_INKLING2_LOOP.add(modeling) + return True diff --git a/trl/trainer/utils.py b/trl/trainer/utils.py index d9613b68..cfbb2b3e 100644 --- a/trl/trainer/utils.py +++ b/trl/trainer/utils.py @@ -1759,7 +1759,7 @@ def add_fused_lm_head( else: # Some models return no router logits, e.g. granite-4.0-h-350m, which has no experts aux_loss = loss.new_zeros(()) - loss = loss + getattr(text_config, "router_aux_loss_coef", 0.0) * aux_loss + loss = loss + getattr(text_config, "router_aux_loss_coef", 0.0) * aux_loss.to(loss.device) return FusedCausalLMOutput( loss=loss, diff --git a/trl/experimental/async_grpo/tree_inkling2_loop.py b/trl/experimental/async_grpo/tree_inkling2_loop.py new file mode 100644 index 00000000..802dc240 --- /dev/null +++ b/trl/experimental/async_grpo/tree_inkling2_loop.py @@ -0,0 +1,204 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Inkling 2 Loop's sequence-mixing steps over a tree-packed row, patched in by `patch_tree_inkling2_loop` +(`packing.py`). + +Three steps read across tokens, and each follows transformers' reference (`modeling_inkling2_loop.py`) with a token's +past taken along its own path in the tree: + +- Attention (sliding and full): a learned bias per query-key distance (zero past `rel_extent`), one sink logit per query + and head, and a window for the sliding layers. The reference builds the bias as a dense `(query, key)` matrix from + flat positions; here each segment gathers its root path (`tree_kv_index`, whose index is the depth) and computes the + bias and window from depth differences, chunk by chunk. +- Short convolutions (on keys, values and after the attention): their 4 taps run back along the token's path. +- Dynamic short convolutions (keys and values of the full layers): the same, with per-token weights. + +The looped core, its messages and the attention residuals all work position by position, so they need nothing. +""" + +import math +import sys + +import torch +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + +from .tree_gated_delta_rule import tree_causal_conv1d + + +# Upper bound on one chunk's `(queries, heads, keys)` attention scores, in elements (256 MB in float32) +_MAX_SCORES = 2**26 + + +def tree_parent_index(tree, n_tokens): + """ + Packed position of the token before each one in its samples, `-1` for a first token: the previous position inside a + segment, the end of the parent segment at a segment start. + """ + cu_seqlens, parents = tree["tree_cu_seqlens_q"].long(), tree["tree_segment_parents"].long() + parent_index = torch.arange(-1, n_tokens - 1, device=cu_seqlens.device) + parent_index[cu_seqlens[:-1]] = torch.where(parents >= 0, cu_seqlens[parents.clamp_min(0) + 1] - 1, -1) + return parent_index + + +def _chunk_attention(module, eager, query, key, value, rel_logits, sinks, first_depth, key_start, window, scaling): + """ + Queries at depths `first_depth, first_depth + 1, ...` over the keys at depths `key_start, key_start + 1, ...`: a + dense attention over one window, so it runs the model's own `eager_attention_forward` (scores plus relative bias and + mask, softmax with the sink as one extra logit), which keeps the reference's rounding in bfloat16. + """ + n_queries, n_heads = query.shape[0], query.shape[1] + n_keys = key.shape[0] + distance = (first_depth + torch.arange(n_queries, device=query.device))[:, None] - ( + key_start + torch.arange(n_keys, device=query.device) + )[None, :] + rel_extent = rel_logits.shape[-1] + index = distance.clamp(0, rel_extent - 1)[:, None, :].expand(-1, n_heads, -1) + bias = rel_logits.gather(-1, index).to(query.dtype) + bias = bias.masked_fill(((distance < 0) | (distance >= rel_extent))[:, None, :], 0.0) + visible = distance >= 0 + if window is not None: + visible = visible & (distance < window) + mask = torch.zeros(visible.shape, dtype=query.dtype, device=query.device) + mask = mask.masked_fill(~visible, torch.finfo(query.dtype).min) + + # (tokens, heads, head_dim) -> (1, heads, tokens, head_dim), as the attention interface takes them + out, _ = eager( + module, + query.transpose(0, 1)[None], + key.to(query.dtype).transpose(0, 1)[None], + value.to(query.dtype).transpose(0, 1)[None], + mask[None, None], + scaling=scaling, + position_bias=bias.transpose(0, 1)[None], + sinks=sinks.to(query.dtype).T[None, :, :, None], + ) + return out[0] + + +def _segment_attention(module, eager, query, key, value, rel_logits, sinks, path, window, scaling): + """ + A segment's queries (the last `len(query)` tokens of `path`) over the K/V rows of their path. Checkpointed per chunk + of queries, so the backward holds one chunk's scores at a time. + """ + n_queries, n_heads = query.shape[0], query.shape[1] + first_depth = len(path) - n_queries + key_start = 0 if window is None else max(0, first_depth - window + 1) + keys = key.index_select(0, path[key_start:]) + values = value.index_select(0, path[key_start:]) + chunk = max(1, _MAX_SCORES // (n_heads * len(keys))) + outputs = [] + for s in range(0, n_queries, chunk): + depth = first_depth + s + # The keys this chunk can see: its window (or all of the path) up to its last query + lo = 0 if window is None else max(0, depth - window + 1) - key_start + hi = min(depth + chunk, len(path)) - key_start + outputs.append( + checkpoint( + _chunk_attention, + module, + eager, + query[s : s + chunk], + keys[lo:hi], + values[lo:hi], + rel_logits[s : s + chunk], + sinks[s : s + chunk], + depth, + key_start + lo, + window, + scaling, + use_reentrant=False, + ) + ) + return torch.cat(outputs) + + +def tree_inkling2_loop_attention(module, hidden_states, key_hidden_states, value_hidden_states, conv_mask, kwargs): + """`Inkling2LoopSlidingAttention.forward` / `Inkling2LoopFullAttention.forward` over a tree-packed row.""" + position_ids = kwargs["position_ids"] + input_shape = hidden_states.shape[:-1] + key_hidden_states = hidden_states if key_hidden_states is None else key_hidden_states + value_hidden_states = hidden_states if value_hidden_states is None else value_hidden_states + + query = module.q_proj(hidden_states, position_ids) + key = module.k_proj(key_hidden_states, conv_mask=conv_mask, **kwargs) + value = module.v_proj(value_hidden_states, conv_mask=conv_mask, **kwargs) + # (1, heads, N, head_dim) -> (N, heads, head_dim). K/V are gathered from float32 copies: `index_select`'s backward + # adds the many queries' contributions to a row atomically, which would lose precision in bfloat16 + query = query[0].transpose(0, 1) + key, value = (x[0].transpose(0, 1).float().contiguous() for x in (key, value)) + + # The bias of each query for every distance, `(N, heads, rel_extent)`, instead of the reference's dense matrix + bias = module.relative_position_bias + relative_states = bias.linear(hidden_states).view(*input_shape, bias.num_heads, -1) + rel_logits = (bias.norm(relative_states, position_ids) @ bias.proj)[0] + sinks = module.sink_proj(hidden_states)[0] + + eager = sys.modules[type(module).__module__].eager_attention_forward + cu_q, cu_k = kwargs["tree_cu_seqlens_q"].tolist(), kwargs["tree_cu_seqlens_k"].tolist() + attn_output = torch.cat( + [ + _segment_attention( + module, + eager, + query[q_start:q_end], + key, + value, + rel_logits[q_start:q_end], + sinks[q_start:q_end], + kwargs["tree_kv_index"][k_start:k_end], + module.sliding_window, + module.scaling, + ) + for q_start, q_end, k_start, k_end in zip(cu_q[:-1], cu_q[1:], cu_k[:-1], cu_k[1:], strict=True) + ] + ) + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + return module.o_proj(attn_output, hidden_states), None + + +def tree_short_convolution(module, conv, hidden_states, tree): + """`Inkling2LoopShortConvolution.forward` over a tree-packed row, its taps run by TRL's tree convolution.""" + input_dtype = hidden_states.dtype + hidden_states = hidden_states.float() + residual = hidden_states + weight, bias = module.conv1d.weight.squeeze(1), module.conv1d.bias + hidden_states = tree_causal_conv1d(hidden_states.transpose(1, 2), weight, bias, None, tree, conv).transpose(1, 2) + return ((hidden_states + residual) / math.sqrt(module.conv_kernel_size + 1)).to(input_dtype) + + +def tree_dynamic_short_convolution(module, hidden_states, dynamic_input, tree): + """`Inkling2LoopDynamicShortConvolution.forward` over a tree-packed row: each window runs back along the path.""" + input_dtype = hidden_states.dtype + _, n_tokens, hidden_size = hidden_states.shape + width = module.conv_kernel_size + dynamic_weights = module.weight_proj(dynamic_input).float().view(1, n_tokens, module.num_heads, 1, width) + weights = module.static_weight.float().T.view(module.num_heads, -1, width) + dynamic_weights + + hidden_states = hidden_states.float() + residual = hidden_states + # taps[t, lag]: the packed position `lag` steps back along t's path, `-1` past its first token + parent_index = tree_parent_index(tree, n_tokens) + taps, index = [], torch.arange(n_tokens, device=hidden_states.device) + for _ in range(width): + taps.append(index) + index = torch.where(index >= 0, parent_index[index.clamp_min(0)], -1) + taps = torch.stack(taps, dim=1) + rows = F.pad(hidden_states[0], (0, 0, 0, 1)) # a zero row for the taps past a first token + windows = rows[taps.where(taps >= 0, n_tokens)].transpose(1, 2) # (N, hidden, width) + windows = windows.reshape(1, n_tokens, module.num_heads, -1, width) + hidden_states = (windows * weights).sum(-1).reshape(1, n_tokens, hidden_size) + return ((hidden_states + residual) / math.sqrt(2 * width + 1)).to(input_dtype) diff --git a/trl/experimental/async_grpo/tree_qwen4_exp.py b/trl/experimental/async_grpo/tree_qwen4_exp.py new file mode 100644 index 00000000..c9f3e5e2 --- /dev/null +++ b/trl/experimental/async_grpo/tree_qwen4_exp.py @@ -0,0 +1,229 @@ +# Copyright 2020-2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Qwen4-Exp's indexed attention (QSA) and per-layer n-gram embedding (PLE) over a tree-packed row, patched in by +[`~packing.patch_tree_qwen4_exp`]. + +Both follow transformers' reference implementation (`modeling_qwen4_exp.py`), which loops over every query position and +reads the tokens before each one from the flat row. Here a token's past is its path in the tree: the K/V rows tree +attention gathers for its segment (`tree_kv_index`), and the chain of `tree_parent_index`. + +QSA: each query sees at most `indexer_budget + compress_ratio - 1` tokens. Its visible tokens are cut into blocks of +`compress_ratio` consecutive ones, the indexer scores the blocks it sees whole, the query keeps the `block_topk` best +and the 0 to `compress_ratio - 1` tokens after the last whole block, and attends over those alone. The selection carries +no gradient, as in the reference (it is a boolean mask there), so it runs under `no_grad`. +""" + +import math + +import torch +import torch.nn.functional as F +from torch.utils.checkpoint import checkpoint + + +# Queries per chunk: bounds the indexer's score matrix and the gathered K/V of the sparse attention +_CHUNK = 1024 + + +def _select_tokens(indexer, q_index, k_index, cos, sin, path, apply_rotary_pos_emb): + """ + Packed positions each of a segment's queries attends to, `-1`-padded: its `block_topk` best whole blocks and the + tokens after the last one. `path` is the segment's root-to-end path, the queries are its last `len(q_index)` tokens. + """ + ratio, n_queries = indexer.compress_ratio, len(q_index) + n_blocks = len(path) // ratio + depths = torch.arange(len(path) - n_queries, len(path), device=path.device) + complete = (depths + 1) // ratio # whole blocks each query sees + k = min(indexer.block_topk, n_blocks) + if k: + blocks = path[: n_blocks * ratio].view(n_blocks, ratio) + pooled = indexer.k_layernorm(k_index[blocks].float().mean(dim=1).to(k_index.dtype)) + starts = blocks[:, 0] + pooled = apply_rotary_pos_emb(pooled.unsqueeze(1), cos=cos[starts], sin=sin[starts]).squeeze(1).float() + selected = [] + for start in range(0, n_queries, _CHUNK): + q = q_index[start : start + _CHUNK].float() + scores = torch.relu(torch.einsum("qhd,bd->qhb", q, pooled)).sum(dim=1) / math.sqrt(indexer.index_head_dim) + visible = torch.arange(n_blocks, device=path.device) < complete[start : start + _CHUNK, None] + top = scores.masked_fill(~visible, -math.inf).topk(k, dim=-1) + tokens = torch.where(torch.isfinite(top.values)[..., None], blocks[top.indices], -1) + selected.append(tokens.flatten(1)) + selected = torch.cat(selected) + else: + selected = path.new_empty((n_queries, 0)) + tail_depths = (complete * ratio)[:, None] + torch.arange(ratio - 1, device=path.device) + tail = torch.where(tail_depths <= depths[:, None], path[tail_depths.clamp_max(len(path) - 1)], -1) + return torch.cat([selected, tail], dim=1) + + +def _sparse_attention(query, key, value, selected, scaling): + """ + Each query attends over its own selected K/V rows. Grouped by K/V head, so a group's query heads share the + gathered rows instead of repeating them, and checkpointed per chunk, so the backward holds one chunk's rows at a + time. + + The rows are gathered with `index_select` from a float32 copy of K/V: each row is selected by up to `budget` + queries, and the backward of advanced indexing (`key[index]`) sums those duplicates by sorting every index, which + took 97% of the layer's forward + backward. `index_select`'s backward adds them atomically instead, in float32 so + that thousands of contributions per row keep their precision. The copy is small: K/V have few heads. + """ + n_kv_heads, head_dim = key.shape[1], key.shape[2] + key, value = key.float().contiguous(), value.float().contiguous() + + def chunk(query, key, value, selected): + rows = selected.clamp_min(0).flatten() + shape = (*selected.shape, n_kv_heads, head_dim) + out = F.scaled_dot_product_attention( + query.reshape(len(query), n_kv_heads, -1, head_dim), + key.index_select(0, rows).view(shape).to(query.dtype).transpose(1, 2), + value.index_select(0, rows).view(shape).to(query.dtype).transpose(1, 2), + attn_mask=(selected >= 0)[:, None, None, :], + scale=scaling, + ) + return out.reshape(len(query), -1, head_dim) + + return torch.cat( + [ + checkpoint(chunk, query[s : s + _CHUNK], key, value, selected[s : s + _CHUNK], use_reentrant=False) + for s in range(0, len(query), _CHUNK) + ] + ) + + +def tree_qsa_attention(module, hidden_states, position_embeddings, tree, apply_rotary_pos_emb): + """`Qwen4ExpTextAttention.forward` over a tree-packed row: the projections as in the reference, then QSA per + segment.""" + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, module.head_dim) + + query_states, gate = torch.chunk( + module.q_proj(hidden_states).view(*input_shape, -1, module.head_dim * 2), 2, dim=-1 + ) + gate = gate.reshape(*input_shape, -1) + + query_states = module.q_norm(query_states.view(hidden_shape)).transpose(1, 2) + key_states = module.k_norm(module.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2) + value_states = module.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) + + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) + # (1, heads, N, head_dim) -> (N, heads, head_dim) + query, key, value = (x[0].transpose(0, 1) for x in (query_states, key_states, value_states)) + cos, sin = cos[0], sin[0] + + indexer = module.indexer + with torch.no_grad(): + q_index, k_index = torch.split( + indexer.index_qk_proj(hidden_states[0]), + [indexer.index_n_heads * indexer.index_head_dim, indexer.index_kv_heads * indexer.index_head_dim], + dim=-1, + ) + q_index = indexer.q_layernorm(q_index.view(len(q_index), -1, indexer.index_head_dim)) + q_index = apply_rotary_pos_emb(q_index, cos=cos, sin=sin, unsqueeze_dim=1) + k_index = k_index.view(len(k_index), indexer.index_head_dim) # one indexer K head, as the reference assumes + + cu_q, cu_k = tree["tree_cu_seqlens_q"].tolist(), tree["tree_cu_seqlens_k"].tolist() + attn_output = [] + for q_start, q_end, k_start, k_end in zip(cu_q[:-1], cu_q[1:], cu_k[:-1], cu_k[1:], strict=True): + path = tree["tree_kv_index"][k_start:k_end] + with torch.no_grad(): + selected = _select_tokens(indexer, q_index[q_start:q_end], k_index, cos, sin, path, apply_rotary_pos_emb) + attn_output.append(_sparse_attention(query[q_start:q_end], key, value, selected, module.scaling)) + + attn_output = torch.cat(attn_output).reshape(*input_shape, -1).contiguous() + attn_output = attn_output * torch.sigmoid(gate) + return module.o_proj(attn_output) + + +def tree_parent_index(tree, n_tokens): + """ + Packed position of the token before each one in its samples, `-1` for a first token: the previous position inside a + segment, the end of the parent segment at a segment start. + """ + cu_seqlens, parents = tree["tree_cu_seqlens_q"].long(), tree["tree_segment_parents"].long() + parent_index = torch.arange(-1, n_tokens - 1, device=cu_seqlens.device) + parent_index[cu_seqlens[:-1]] = torch.where(parents >= 0, cu_seqlens[parents.clamp_min(0) + 1] - 1, -1) + return parent_index + + +def _ancestor(parent_index, index): + """The packed position before each of `index` in its samples, `-1` past a first token.""" + return torch.where(index >= 0, parent_index[index.clamp_min(0)], -1) + + +def _tree_ngram_embedding(embedding, input_ids, parent_index): + """`Qwen4ExpTextNGramEmbedding.forward` over a tree-packed row: each token's n-gram is read up its path.""" + tokens, eos = input_ids[0], embedding.eos_token_id + # The token `shift` before each one, or EOS where it is missing or an EOS lies in between, as + # `_shift_right_ignore_eos` does on a flat row + shifted_tokens = [tokens] + index, valid = parent_index, parent_index >= 0 + for _ in range(1, embedding.ngram_size): + previous = tokens[index.clamp_min(0)] + valid = valid & (index >= 0) + shifted_tokens.append(torch.where(valid, previous, eos)) + valid = valid & (previous != eos) + index = _ancestor(parent_index, index) + shifted_tokens = [t.unsqueeze(0) for t in shifted_tokens] + + blocks = [] + for ngram in range(2, embedding.ngram_size + 1): + start_idx = (ngram - 2) * embedding.heads_per_ngram + end_idx = start_idx + embedding.heads_per_ngram + mixed_ids = shifted_tokens[0] * embedding.layer_multipliers[0] + for position in range(1, ngram): + mixed_ids = torch.bitwise_xor( + mixed_ids, + shifted_tokens[position] * embedding.layer_multipliers[position], + ) + head_vocab_sizes = embedding.ngram_heads_vocab_sizes[start_idx:end_idx] + head_offsets = embedding.ngram_heads_offsets[start_idx:end_idx] + ngram_ids = torch.remainder(mixed_ids.unsqueeze(-1), head_vocab_sizes.view(1, 1, -1)) + blocks.append(ngram_ids + head_offsets.view(1, 1, -1)) + + ngram_ids = torch.cat(blocks, dim=-1) + execution_device = ( + embedding.ngram_embedding.weight.device if embedding.ngram_embedding.weight.device.type != "meta" else None + ) + return embedding.ngram_embedding(ngram_ids.to(execution_device)).to(ngram_ids.device).flatten(-2) + + +def _tree_short_conv(ple, hidden_states, parent_index): + """`Qwen4ExpTextPLELayer._short_conv` over a tree-packed row: each tap reads the token `k * dilation` before up the + path, zero past the first token, as the reference's left padding.""" + weight = ple.conv1d.weight[:, 0] # (channels, kernel_size), depthwise + kernel_size, dilation = weight.shape[1], ple.conv1d.dilation[0] + hidden_states = hidden_states[0] + out = hidden_states * weight[:, kernel_size - 1] + index = torch.arange(len(hidden_states), device=hidden_states.device) + for tap in range(kernel_size - 2, -1, -1): + for _ in range(dilation): + index = _ancestor(parent_index, index) + out = out + torch.where((index >= 0)[:, None], hidden_states[index.clamp_min(0)], 0) * weight[:, tap] + return F.silu(out).unsqueeze(0) + + +def tree_ple(ple, hidden_states, input_ids, parent_index): + """`Qwen4ExpTextPLELayer.forward` over a tree-packed row (no padding, no cache).""" + embeddings = _tree_ngram_embedding(ple.ple_embedding, input_ids, parent_index) + key_normed = ple.norm_key(ple.key_proj(embeddings)).unflatten(-1, (ple.hc_count, ple.hidden_size)) + value = ple.value_proj(embeddings) + query_normed = ple.norm_query(hidden_states).unflatten(-1, (ple.hc_count, ple.hidden_size)) + gate = (key_normed * query_normed).sum(dim=-1, keepdim=True) / math.sqrt(ple.hidden_size) + gate = gate.abs().clamp_min(1e-6).sqrt() * gate.sign() + gated_value = torch.sigmoid(gate) * value.unsqueeze(-2) + gated_value_normed = ple.norm_conv(gated_value.flatten(-2)) + gated_value = gated_value.flatten(-2) + return gated_value + _tree_short_conv(ple, gated_value_normed, parent_index)