TRL changes the Qwen3.8-Flash-Next recipe runs on, relative to upstream huggingface/trl. upstream base: d115286bc5aef8d346e8510bfe312803c7881c4a (2026-11-11, Add UDPO loss for noisy preferences to DPOTrainer (#8211)) adds: tree packing for Qwen4-Exp (Qwen3.8-Flash-Next) in AsyncGRPO, and the AsyncGRPO changes it relies on Apply on a checkout of the upstream base: git apply trl.patch 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..84591ff5 100644 --- a/trl/experimental/async_grpo/async_grpo_trainer.py +++ b/trl/experimental/async_grpo/async_grpo_trainer.py @@ -38,7 +38,7 @@ from datasets import Dataset, IterableDataset from packaging.version import Version from torch.distributed._tensor import DTensor from torch.utils.data import DataLoader -from transformers import AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, TrainerCallback +from transformers import AutoConfig, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerBase, TrainerCallback from transformers.data.data_collator import DataCollatorMixin from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR, SaveStrategy from transformers.utils import is_peft_available @@ -60,7 +60,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_qwen4_exp, + register_tree_attention, + tree_attn_implementation, + unpad_tree, +) from .vllm_client import VLLMClient from .weight_transfer import WeightTransferClient @@ -987,15 +995,16 @@ class AsyncGRPOTrainer(_BaseTrainer): model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code) model_init_kwargs.setdefault("dtype", args.dtype) model_revision = model_init_kwargs.get("revision") + config = AutoConfig.from_pretrained(model, revision=model_revision, trust_remote_code=args.trust_remote_code) model = create_model_from_path( model, device_map=None, - attn_implementation=TREE_ATTENTION, + attn_implementation=tree_attn_implementation(config), **model_init_kwargs, ) else: model_revision = None - model.set_attn_implementation(TREE_ATTENTION) + model.set_attn_implementation(tree_attn_implementation(model.config)) if args.model_init_kwargs is not None: logger.warning( "You passed `model_init_kwargs` to the `AsyncGRPOConfig`, but your model is already instantiated. " @@ -1009,18 +1018,29 @@ class AsyncGRPOTrainer(_BaseTrainer): layer_types = set(getattr(text_config, "layer_types", None) or []) - {"full_attention", "sliding_attention"} # 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): + if layer_types - {"linear_attention", "indexed_attention"} 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." ) + if layer_types == {"linear_attention", "indexed_attention"} and not patch_tree_qwen4_exp(model): + raise ValueError( + f"{type(model).__name__} selects its sparse-attention keys, builds its n-gram embeddings and " + "convolves its per-layer embeddings through module-level functions that tree packing patches; its " + "modeling module lacks `qsa_select_tokens`, `ngram_shift_right` or `ple_short_conv`." + ) + # The indexer reads the 4D mask the model builds, and selects its own keys on top of it. A flat all-ones mask + # keeps that mask plain causal: inferred from the row's position ids, which are depths and not offsets, it + # would cut every path off from the segments before it. + self.explicit_attention_mask = tree_attn_implementation(model.config) != TREE_ATTENTION + if any(name.endswith(".sinks") for name, _ in model.named_parameters()): raise ValueError( f"{type(model).__name__} uses attention sinks, which the FA3 kernel used by tree packing does not " @@ -1247,7 +1267,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")) @@ -1447,6 +1467,7 @@ class AsyncGRPOTrainer(_BaseTrainer): forward_start = time.time() # MoE models: request router logits so the forward returns the load-balancing loss router_kwargs = {"output_router_logits": True} if self.aux_loss_enabled else {} + mask_kwargs = {"attention_mask": torch.ones_like(input_ids)} if self.explicit_attention_mask else {} outputs = model( input_ids=input_ids, position_ids=position_ids, @@ -1455,6 +1476,7 @@ class AsyncGRPOTrainer(_BaseTrainer): score_ids=sampler_ids, fused_lm_head=True, **router_kwargs, + **mask_kwargs, **unpad_tree(inputs), ) log_probs = outputs.log_probs.flatten()[token_index] @@ -1799,11 +1821,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 +1837,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..07d6e39f 100644 --- a/trl/experimental/async_grpo/openenv_harness.py +++ b/trl/experimental/async_grpo/openenv_harness.py @@ -161,6 +161,10 @@ 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 of solved rollouts only: the efficiency 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 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(): diff --git a/trl/experimental/async_grpo/packing.py b/trl/experimental/async_grpo/packing.py index 9d5a54b6..001a5d01 100644 --- a/trl/experimental/async_grpo/packing.py +++ b/trl/experimental/async_grpo/packing.py @@ -20,6 +20,7 @@ from typing import Any import numpy as np import torch +import torch.nn.functional as F from transformers import AttentionInterface from transformers.integrations.flash_attention import get_target_dtype from transformers.masking_utils import AttentionMaskInterface @@ -221,6 +222,207 @@ def unpad_tree(inputs: dict[str, torch.Tensor]) -> dict[str, Any]: TREE_ATTENTION = "tree_fa3" +QWEN4_EXP = "qwen4_exp" + + +def tree_attn_implementation(config) -> str: + """`sdpa` for Qwen4-Exp, whose attention selects its own mask, and tree attention for every other model.""" + return "sdpa" if config.model_type == QWEN4_EXP else TREE_ATTENTION + + +_MAPS = None # the last row's maps: rebuilding them per layer costs a host sync and an (n, n) mask each time + + +def tree_maps(tree): + """The row's `prev` position on each one's own path, its `depth` there, and `visible`: whether it sees another.""" + global _MAPS + if _MAPS is not None and _MAPS[0] is tree["tree_cu_seqlens_q"]: + return _MAPS[1] + cu_seqlens_q, cu_seqlens_k, kv_index = tree["tree_cu_seqlens_q"], tree["tree_cu_seqlens_k"], tree["tree_kv_index"] + device = kv_index.device + parents = tree["tree_segment_parents"].long() + cu_q, cu_k = cu_seqlens_q.tolist(), cu_seqlens_k.tolist() + n = cu_q[-1] # the row's positions; `tree_kv_index` repeats a segment's whole path, so it is longer + lengths = [end - start for start, end in zip(cu_q[:-1], cu_q[1:], strict=True)] + # A parent is laid out before its children, so one pass gives each segment the depth its first token sits at + depths = [] + for parent in parents.tolist(): + depths.append(0 if parent < 0 else depths[parent] + lengths[parent]) + prev = torch.arange(n, device=device) - 1 + parent_last = torch.where(parents >= 0, cu_seqlens_q.long()[(parents + 1).clamp_min(0)] - 1, -1) + prev[cu_seqlens_q[:-1].long()] = parent_last + segments = torch.repeat_interleave(torch.arange(len(lengths), device=device), torch.tensor(lengths, device=device)) + depth = ( + torch.arange(n, device=device) + - torch.tensor(cu_q[:-1], device=device)[segments] + + torch.tensor(depths, device=device)[segments] + ) + visible = torch.zeros(n, n, dtype=torch.bool, device=device) + for start, end, path_start, path_end in zip(cu_q[:-1], cu_q[1:], cu_k[:-1], cu_k[1:], strict=True): + path = kv_index[path_start:path_end].long() # laid out before this segment, so it is ascending + visible[start:end, path] = path.unsqueeze(0) <= torch.arange(start, end, device=device).unsqueeze(1) + _MAPS = (cu_seqlens_q, {"prev": prev, "depth": depth, "visible": visible}) + return _MAPS[1] + + +def tree_ngram_shift_right(token_ids: torch.Tensor, shift: int, eos_token_id: int, tree) -> torch.Tensor: + """The `shift`-th token before each position on its own path, and EOS where that leaves the path or crosses one.""" + if shift == 0: + return token_ids + prev = tree_maps(tree)["prev"] + n = prev.numel() + tokens = token_ids[:, -n:] + eos = tokens == eos_token_id + index = torch.arange(n, device=prev.device) + valid = torch.ones(tokens.shape, dtype=torch.bool, device=prev.device) + for _ in range(shift): + index = torch.where(index >= 0, prev[index.clamp_min(0)], index) + valid &= (index >= 0) & ~eos.gather(1, index.clamp_min(0).expand(tokens.shape[0], -1)) + shifted = tokens.gather(1, index.clamp_min(0).expand(tokens.shape[0], -1)) + shifted = torch.where(valid, shifted, torch.full_like(shifted, eos_token_id)) + output = token_ids.new_full(token_ids.shape, eos_token_id) # the caller's EOS context columns stay EOS + output[:, -n:] = shifted + return output + + +def tree_ple_short_conv(hidden_states: torch.Tensor, conv1d: torch.nn.Conv1d, tree) -> torch.Tensor: + """The dilated depthwise convolution along each path: every tap reads the position its dilation puts it at.""" + prev = tree_maps(tree)["prev"] + n, device = prev.numel(), prev.device + weight, bias = conv1d.weight, conv1d.bias + states = hidden_states[..., -n:] + output = torch.zeros_like(states) + index = torch.arange(n, device=device) + alive = torch.ones(n, dtype=torch.bool, device=device) + for tap in reversed(range(weight.shape[-1])): + steps = conv1d.dilation[0] if tap < weight.shape[-1] - 1 else 0 # the last tap is the position itself + for _ in range(steps): + alive &= index >= 0 + index = torch.where(index >= 0, prev[index.clamp_min(0)], index) + alive &= index >= 0 + source = index.clamp_min(0).expand(states.shape[0], states.shape[1], -1) + output.addcmul_(states.gather(2, source).masked_fill_(~alive, 0), weight[:, 0, tap].view(1, -1, 1)) + if bias is not None: + output.add_(bias.view(1, -1, 1)) + return F.silu(output) + + +def _rotate_half(x: torch.Tensor) -> torch.Tensor: + """Rotate the first half of the head dimension onto the second, as the model's rotary embedding does.""" + x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def _apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + """Rotate `x` with the `cos` and `sin` of its block's first token, as the model's indexer does.""" + rotary_dim = cos.shape[-1] + rotated = x[..., :rotary_dim] * cos + _rotate_half(x[..., :rotary_dim]) * sin + return torch.cat([rotated, x[..., rotary_dim:]], dim=-1) + + +def tree_qsa_select_tokens(q, raw_keys, full_cos, full_sin, k_layernorm, block_topk, compress_ratio, tree): + """ + The indexer's selection over the row, as a bool mask of shape `(1, 1, q, kv)`: a block is `compress_ratio` + consecutive depths on one path, keyed by its last token. + """ + maps = tree_maps(tree) + prev, depth, visible = maps["prev"], maps["depth"], maps["visible"] + device, n = prev.device, prev.numel() + head_dim = q.shape[-1] + + block_last = torch.nonzero(depth % compress_ratio == compress_ratio - 1).flatten() + members = [block_last] + for _ in range(compress_ratio - 1): + members.insert(0, prev[members[0].clamp_min(0)]) + members = torch.stack(members, dim=1) # (blocks, compress_ratio), by increasing depth + pooled = raw_keys[0].index_select(0, members.flatten()).view(len(block_last), compress_ratio, -1) + pooled = k_layernorm(pooled.float().mean(dim=1).to(raw_keys.dtype)) + block_states = _apply_rope( + pooled.unsqueeze(1), + full_cos[0].index_select(0, members[:, 0]).unsqueeze(1), + full_sin[0].index_select(0, members[:, 0]).unsqueeze(1), + ) + block_states = block_states.squeeze(1).float() + + queries = q[0].float() + num_blocks, num_selected = len(block_last), min(block_topk, len(block_last)) + selected = torch.zeros(n, n, dtype=torch.uint8, device=device) + flat = selected.view(-1) + queries_per_chunk = max(1, 2**24 // max(num_blocks * queries.shape[1], 1)) # bound the score tensor + for start in range(0, n, queries_per_chunk): + stop = min(start + queries_per_chunk, n) + rows = torch.arange(start, stop, device=device) + scores = torch.einsum("qhd,bd->qbh", queries[start:stop], block_states) + scores = scores.relu().sum(dim=-1) / math.sqrt(head_dim) + seen = visible[start:stop].index_select(1, block_last) + top = scores.masked_fill(~seen, float("-inf")).topk(num_selected, dim=-1) + chosen = torch.where(top.values > float("-inf"), top.indices, -1) + kept = chosen >= 0 + ones = torch.ones(chosen.shape, dtype=torch.uint8, device=device) + for member in range(compress_ratio): + source = members[:, member].index_select(0, chosen.flatten().clamp_min(0)).view(chosen.shape) + flat.index_add_(0, (source + rows.view(-1, 1) * n)[kept], ones[kept]) # union: accumulate, do not assign + cutoff = (depth[rows] + 1) // compress_ratio * compress_ratio + tail = visible[start:stop] & (depth.view(1, -1) >= cutoff.view(-1, 1)) + selected[start:stop].bitwise_or_(tail.to(torch.uint8)) + + return (selected.to(torch.bool) & visible).view(1, 1, n, n) + + +_QWEN4_PATCHED = set() + + +def patch_tree_qwen4_exp(model) -> bool: + """ + Make Qwen4-Exp's n-gram embedding, per-layer short convolution and sparse-attention indexer follow each sample's + own path, and report whether the modeling module has those three functions. + """ + modeling = sys.modules[type(model).forward.__module__] + names = ("ngram_shift_right", "ple_short_conv", "qsa_select_tokens") + originals = [vars(modeling).get(name) for name in names] + if any(original is None for original in originals): + return False + if modeling in _QWEN4_PATCHED: + return True + ngram_shift_right, ple_short_conv, qsa_select_tokens = originals + + def ngram_shift_right_fn(token_ids, shift, eos_token_id, **kwargs): + if "tree_segment_parents" not in kwargs: + return ngram_shift_right(token_ids, shift, eos_token_id, **kwargs) + return tree_ngram_shift_right(token_ids, shift, eos_token_id, kwargs) + + def ple_short_conv_fn(hidden_states, conv1d, **kwargs): + if "tree_segment_parents" not in kwargs: + return ple_short_conv(hidden_states, conv1d, **kwargs) + return tree_ple_short_conv(hidden_states, conv1d, kwargs) + + def qsa_select_tokens_fn( + q, + raw_keys, + full_cos, + full_sin, + attention_mask, + k_layernorm, + block_topk, + compress_ratio, + token_budget, + **kwargs, + ): + if "tree_segment_parents" not in kwargs: + return qsa_select_tokens( + q, raw_keys, full_cos, full_sin, attention_mask, k_layernorm, block_topk, compress_ratio, token_budget, + **kwargs, + ) + return tree_qsa_select_tokens(q, raw_keys, full_cos, full_sin, k_layernorm, block_topk, compress_ratio, kwargs) + + modeling.ngram_shift_right, modeling.ple_short_conv, modeling.qsa_select_tokens = ( + ngram_shift_right_fn, + ple_short_conv_fn, + qsa_select_tokens_fn, + ) + _QWEN4_PATCHED.add(modeling) + return True + @cache def _flash_attn(): @@ -289,7 +491,7 @@ def patch_tree_gdn(model) -> bool: Returns: `bool`: whether the model's modeling module has those functions. """ - modeling = sys.modules[type(model).__module__] + modeling = sys.modules[type(model).forward.__module__] conv, chunk = vars(modeling).get("causal_conv1d_fn"), vars(modeling).get("torch_chunk_gated_delta_rule") if conv is None or chunk is None: return False