Python
fixed qwen3.5vl gguf pseudo garbage output + 20%speedup
DeepBeepMeep06701a3a541b
diff --git a/README.md b/README.mdindex 6ebe568..6d90f81 100644--- a/README.md+++ b/README.md@@ -452,6 +452,7 @@ For detailed installation instructions for different GPU generations:### Basic Usage- **[Getting Started Guide](docs/GETTING_STARTED.md)** - First steps and basic usage- **[Models Overview](docs/MODELS.md)** - Available models and their capabilities+- **[Prompts Guide](docs/PROMPTS.md)** - How WanGP interprets prompts, images as prompts, enhancers, and macros### Advanced Features- **[Loras Guide](docs/LORAS.md)** - Using and managing Loras for customizationdiff --git a/docs/LORAS.md b/docs/LORAS.mdindex c028b56..06bbdd2 100644--- a/docs/LORAS.md+++ b/docs/LORAS.md@@ -318,42 +318,6 @@ https://huggingface.co/Kijai/WanVideo_comfy/blob/main/Wan21_T2V_14B_lightx2v_cfg- **OneTrainer** - Alternative training solution- **Custom datasets** - Train on your own content-## Macro System (Advanced)--Create multiple prompts from templates using macros. This allows you to generate variations of a sentence by defining lists of values for different variables.--**Syntax Rule:**--Define your variables on a single line starting with `!`. Each complete variable definition, including its name and values, **must be separated by a colon (`:`)**.--**Format:**--```-! {Variable1}="valueA","valueB" : {Variable2}="valueC","valueD"-This is a template using {Variable1} and {Variable2}.-```--**Example:**--The following macro will generate three distinct prompts by cycling through the values for each variable.--**Macro Definition:**--```-! {Subject}="cat","woman","man" : {Location}="forest","lake","city" : {Possessive}="its","her","his"-In the video, a {Subject} is presented. The {Subject} is in a {Location} and looks at {Possessive} watch.-```--**Generated Output:**--```-In the video, a cat is presented. The cat is in a forest and looks at its watch.-In the video, a woman is presented. The woman is in a lake and looks at her watch.-In the video, a man is presented. The man is in a city and looks at his watch.-```---## Troubleshooting### Lora Not Working0. If it is a lora accelerator, Guidance should be set to 1diff --git a/plugins/wan2gp-guides/plugin.py b/plugins/wan2gp-guides/plugin.pyindex 5f53830..b332aa2 100644--- a/plugins/wan2gp-guides/plugin.py+++ b/plugins/wan2gp-guides/plugin.py@@ -31,6 +31,9 @@ class GuidesPlugin(WAN2GPPlugin):with open("docs/LORAS.md", "r", encoding="utf-8") as reader:loras = reader.read()+ with open("docs/PROMPTS.md", "r", encoding="utf-8") as reader:+ prompts = reader.read()+with open("docs/FINETUNES.md", "r", encoding="utf-8") as reader:finetunes = reader.read()@@ -57,6 +60,8 @@ class GuidesPlugin(WAN2GPPlugin):inputs=[self.state],outputs=[self.main_tabs])+ with gr.Tab("Prompts", id="prompts"):+ gr.Markdown(prompts)with gr.Tab("Loras", id="loras"):gr.Markdown(loras)with gr.Tab("Vace", id="vace"):diff --git a/shared/llm_engines/nanovllm/engine/llm_engine.py b/shared/llm_engines/nanovllm/engine/llm_engine.pyindex 71f99f0..5523b9d 100644--- a/shared/llm_engines/nanovllm/engine/llm_engine.py+++ b/shared/llm_engines/nanovllm/engine/llm_engine.py@@ -241,6 +241,7 @@ class LLMEngine:# This prevents 'deque index out of range' errors from accumulated block leaksif not self.is_finished():self.reset()+ self.model_runner.reset_generation_state()if use_tqdm:pbar = tqdm(total=len(prompts), desc="Generating", dynamic_ncols=True)@@ -314,6 +315,7 @@ class LLMEngine:)if not self.is_finished():self.reset()+ self.model_runner.reset_generation_state()if not isinstance(sampling_params, list):sampling_params = [sampling_params] * len(prompts)if prompt_position_ids is None:diff --git a/shared/llm_engines/nanovllm/engine/model_runner.py b/shared/llm_engines/nanovllm/engine/model_runner.pyindex 3ed5a7f..7198a0c 100644--- a/shared/llm_engines/nanovllm/engine/model_runner.py+++ b/shared/llm_engines/nanovllm/engine/model_runner.py@@ -94,6 +94,7 @@ class ModelRunner:self._graph_cache_order = []self._logits_bias_cache = {}self._sampling_generator = None+ self._runtime_signature = Noneself._guard_counts = {}self._guard_seen_details = set()torch.set_default_dtype(config_dtype)@@ -123,7 +124,16 @@ class ModelRunner:def ensure_runtime_ready(self):if self._runtime_ready:- return+ # In eager mode MMGP may move parameter storage between CPU/GPU after prefill.+ # That changes data_ptr() without invalidating the live KV cache or sequence state.+ # Resetting here drops the prompt context and makes legacy decode drift off-topic.+ if self.enforce_eager:+ return+ current_sig = self._get_graph_capture_signature()+ if current_sig == self._runtime_signature:+ return+ self._note_guard("runtime_reprepare_signature_change")+ self.reset_runtime_state()if self.model is None:raise RuntimeError("LLM model object is not available.")self._tie_word_embeddings_if_needed()@@ -132,6 +142,25 @@ class ModelRunner:if not self.enforce_eager:self.capture_cudagraph()self._runtime_ready = True+ self._runtime_signature = self._get_graph_capture_signature()++ def reset_generation_state(self):+ if self.model is None:+ return+ try:+ for module in self.model.modules():+ reset_sequence_state = getattr(module, "reset_sequence_state", None)+ if callable(reset_sequence_state):+ reset_sequence_state()+ continue+ if hasattr(module, "conv_state"):+ module.conv_state = None+ if hasattr(module, "recurrent_state"):+ module.recurrent_state = None+ except Exception:+ pass+ self._logits_bias_cache.clear()+ reset_context()def _prepare_model_sequence_state(self):if self.model is None:@@ -222,6 +251,7 @@ class ModelRunner:passself._logits_bias_cache.clear()self._sampling_generator = None+ self._runtime_signature = Noneself._runtime_ready = Falsegc.collect()@@ -316,6 +346,7 @@ class ModelRunner:self._cpu_cfg_scales = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)self._cpu_top_ks = torch.zeros(max_bs, dtype=torch.int32, device="cpu", pin_memory=True)self._cpu_top_ps = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)+ self._cpu_min_ps = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)self._cpu_repetition_penalties = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)# Pre-allocate decode buffers on CPU with pinned memory@@ -343,6 +374,7 @@ class ModelRunner:"_cpu_cfg_scales","_cpu_top_ks","_cpu_top_ps",+ "_cpu_min_ps","_cpu_repetition_penalties","_cpu_input_ids","_cpu_positions",@@ -487,10 +519,15 @@ class ModelRunner:layer_id += 1def prepare_block_tables(self, seqs: list[Sequence]):+ bs = len(seqs)max_len = max(len(seq.block_table) for seq in seqs)- block_tables = [seq.block_table + [-1] * (max_len - len(seq.block_table)) for seq in seqs]- block_tables = torch.tensor(block_tables, dtype=torch.int32, pin_memory=True).cuda(non_blocking=True)- return block_tables+ block_tables = self._cpu_block_tables[:bs, :max_len]+ block_tables.fill_(-1)+ for row, seq in enumerate(seqs):+ if not seq.block_table:+ continue+ block_tables[row, :len(seq.block_table)] = torch.tensor(seq.block_table, dtype=torch.int32, device="cpu")+ return block_tables.cuda(non_blocking=True)def prepare_prefill(self, seqs: list[Sequence]):use_prompt_embeds = any(getattr(seq, "prompt_embeds", None) is not None for seq in seqs)@@ -592,6 +629,7 @@ class ModelRunner:# Fill pre-allocated CPU bufferstop_ks_is_zero = Truetop_ps_is_one = True+ min_ps_is_zero = Truerepetition_penalties_is_one = Truefor i, seq in enumerate(target_seqs):self._cpu_temperatures[i] = seq.temperature@@ -602,6 +640,9 @@ class ModelRunner:self._cpu_top_ps[i] = seq.top_p if seq.top_p is not None else 1.0if seq.top_p is not None and seq.top_p != 1.0:top_ps_is_one = False+ self._cpu_min_ps[i] = seq.min_p if seq.min_p is not None else 0.0+ if seq.min_p is not None and seq.min_p > 0.0:+ min_ps_is_zero = Falseself._cpu_repetition_penalties[i] = seq.repetition_penalty if seq.repetition_penalty is not None else 1.0if seq.repetition_penalty is not None and seq.repetition_penalty != 1.0:repetition_penalties_is_one = False@@ -611,9 +652,10 @@ class ModelRunner:cfg_scales = self._cpu_cfg_scales[:num_seqs].cuda(non_blocking=True)top_ks = self._cpu_top_ks[:num_seqs].cuda(non_blocking=True) if not top_ks_is_zero else Nonetop_ps = self._cpu_top_ps[:num_seqs].cuda(non_blocking=True) if not top_ps_is_one else None+ min_ps = self._cpu_min_ps[:num_seqs].cuda(non_blocking=True) if not min_ps_is_zero else Nonerepetition_penalties = self._cpu_repetition_penalties[:num_seqs].cuda(non_blocking=True) if not repetition_penalties_is_one else None- return temperatures, cfg_scales, top_ks, top_ps, repetition_penalties+ return temperatures, cfg_scales, top_ks, top_ps, min_ps, repetition_penalties@torch.inference_mode()def run_model(self, input_ids: torch.Tensor | None, positions: torch.Tensor, is_prefill: bool, inputs_embeds: torch.Tensor | None = None):@@ -693,9 +735,9 @@ class ModelRunner:inputs_embeds = Nonesample_params = self.prepare_sample(seqs, is_cfg_batch=True) if self.rank == 0 else Noneif sample_params is not None:- temperatures, cfg_scales, top_ks, top_ps, repetition_penalties = sample_params+ temperatures, cfg_scales, top_ks, top_ps, min_ps, repetition_penalties = sample_paramselse:- temperatures = cfg_scales = top_ks = top_ps = repetition_penalties = None+ temperatures = cfg_scales = top_ks = top_ps = min_ps = repetition_penalties = None# Run model forward (processes entire batch: cond + uncond)logits_all = self.run_model(input_ids, positions, is_prefill, inputs_embeds=inputs_embeds)@@ -758,6 +800,7 @@ class ModelRunner:temperatures,top_ks=top_ks if top_ks is not None else None,top_ps=top_ps if top_ps is not None else None,+ min_ps=min_ps if min_ps is not None else None,repetition_penalties=None, # Already applied abovegenerator=self._sampling_generator,# input_ids=cond_input_ids,@@ -782,9 +825,9 @@ class ModelRunner:inputs_embeds = Nonesample_params = self.prepare_sample(seqs, is_cfg_batch=False) if self.rank == 0 else Noneif sample_params is not None:- temperatures, cfg_scales, top_ks, top_ps, repetition_penalties = sample_params+ temperatures, cfg_scales, top_ks, top_ps, min_ps, repetition_penalties = sample_paramselse:- temperatures = cfg_scales = top_ks = top_ps = repetition_penalties = None+ temperatures = cfg_scales = top_ks = top_ps = min_ps = repetition_penalties = Nonelogits = self.run_model(input_ids, positions, is_prefill, inputs_embeds=inputs_embeds)if is_prefill:for seq in seqs:@@ -837,6 +880,7 @@ class ModelRunner:temperatures,top_ks=top_ks if top_ks is not None else None,top_ps=top_ps if top_ps is not None else None,+ min_ps=min_ps if min_ps is not None else None,repetition_penalties=None, # Already applied abovegenerator=self._sampling_generator,# input_ids=seq_input_ids,diff --git a/shared/llm_engines/nanovllm/engine/sequence.py b/shared/llm_engines/nanovllm/engine/sequence.pyindex 756f8b0..f9ef9a4 100644--- a/shared/llm_engines/nanovllm/engine/sequence.py+++ b/shared/llm_engines/nanovllm/engine/sequence.py@@ -40,6 +40,7 @@ class Sequence:self.cfg_scale = sampling_params.cfg_scaleself.top_k = sampling_params.top_kself.top_p = sampling_params.top_p+ self.min_p = sampling_params.min_pself.repetition_penalty = sampling_params.repetition_penalty# For CFG: mark if this is an unconditional sequenceself.is_unconditional = is_unconditionaldiff --git a/shared/llm_engines/nanovllm/layers/layernorm.py b/shared/llm_engines/nanovllm/layers/layernorm.pyindex 1fc74c1..c4c753f 100644--- a/shared/llm_engines/nanovllm/layers/layernorm.py+++ b/shared/llm_engines/nanovllm/layers/layernorm.py@@ -94,7 +94,9 @@ class RMSNorm(nn.Module):orig_dtype = x.dtypex_float = x.float()var = x_float.pow(2).mean(dim=-1, keepdim=True)- return (x_float * torch.rsqrt(var + self.eps)).to(orig_dtype) * self.weight+ normed = x_float * torch.rsqrt(var + self.eps)+ normed *= self.weight+ return normed.to(orig_dtype)def _fallback_add_rms_forward(self,@@ -105,8 +107,9 @@ class RMSNorm(nn.Module):summed = x.float() + residual.float()residual_out = summed.to(orig_dtype)var = summed.pow(2).mean(dim=-1, keepdim=True)- normed = (summed * torch.rsqrt(var + self.eps)).to(orig_dtype) * self.weight- return normed, residual_out+ normed = summed * torch.rsqrt(var + self.eps)+ normed *= self.weight+ return normed.to(orig_dtype), residual_outdef _triton_rms_forward(self, x: torch.Tensor) -> torch.Tensor:x_2d = x.reshape(-1, x.shape[-1])diff --git a/shared/llm_engines/nanovllm/layers/sampler.py b/shared/llm_engines/nanovllm/layers/sampler.pyindex 4aecf5d..08ca7f6 100644--- a/shared/llm_engines/nanovllm/layers/sampler.py+++ b/shared/llm_engines/nanovllm/layers/sampler.py@@ -59,6 +59,30 @@ def apply_top_k_top_p(return logits.squeeze(0) if squeezed else logits+def apply_min_p(+ logits: torch.Tensor,+ min_p: Optional[torch.Tensor],+) -> torch.Tensor:+ if min_p is None:+ return logits+ squeezed = False+ if logits.ndim == 1:+ logits = logits.unsqueeze(0)+ squeezed = True+ min_p = min_p.reshape(-1)+ active_mask = min_p > 0+ if not torch.any(active_mask):+ return logits.squeeze(0) if squeezed else logits+ probs = logits.softmax(dim=-1)+ max_probs, max_idx = probs.max(dim=-1, keepdim=True)+ threshold = max_probs * min_p.unsqueeze(1)+ mask = probs < threshold+ mask.scatter_(1, max_idx, False)+ mask &= active_mask.unsqueeze(1)+ logits.masked_fill_(mask, float("-inf"))+ return logits.squeeze(0) if squeezed else logits++def apply_top_k_only(logits: torch.Tensor,k: torch.Tensor,@@ -111,6 +135,7 @@ class Sampler(nn.Module):temperatures: torch.Tensor,top_ks: Optional[torch.Tensor] = None,top_ps: Optional[torch.Tensor] = None,+ min_ps: Optional[torch.Tensor] = None,repetition_penalties: Optional[torch.Tensor] = None,input_ids: Optional[torch.Tensor] = None,generator: Optional[torch.Generator] = None,@@ -129,6 +154,7 @@ class Sampler(nn.Module):top_ks,top_ps,)+ logits = apply_min_p(logits, min_ps)if _SAMPLER_NUMERIC_GUARD:logits = torch.nan_to_num(logits, nan=float("-inf"))invalid_rows = ~torch.isfinite(logits).any(dim=-1)diff --git a/shared/llm_engines/nanovllm/models/qwen3_5.py b/shared/llm_engines/nanovllm/models/qwen3_5.pyindex 7f679b9..d939f2a 100644--- a/shared/llm_engines/nanovllm/models/qwen3_5.py+++ b/shared/llm_engines/nanovllm/models/qwen3_5.py@@ -114,11 +114,118 @@ def _build_mrope_freq_cache(return cached-def _interleave_last_dim_halves(tensor: torch.Tensor) -> torch.Tensor:- if tensor.shape[-1] % 2 != 0:+def _interleave_axis_halves(tensor: torch.Tensor, dim: int) -> torch.Tensor:+ dim = dim if dim >= 0 else tensor.ndim + dim+ if dim < 0 or dim >= tensor.ndim or tensor.shape[dim] % 2 != 0:return tensor- first_half, second_half = tensor.chunk(2, dim=-1)- return torch.stack((first_half, second_half), dim=-1).flatten(-2, -1)+ first_half, second_half = tensor.chunk(2, dim=dim)+ return torch.stack((first_half, second_half), dim=dim + 1).flatten(dim, dim + 1)+++def _inverse_interleave_axis_halves(tensor: torch.Tensor, dim: int) -> torch.Tensor:+ dim = dim if dim >= 0 else tensor.ndim + dim+ if dim < 0 or dim >= tensor.ndim or tensor.shape[dim] % 2 != 0:+ return tensor+ half = tensor.shape[dim] // 2+ tensor = tensor.reshape(*tensor.shape[:dim], half, 2, *tensor.shape[dim + 1 :])+ return torch.cat((tensor.select(dim + 1, 0), tensor.select(dim + 1, 1)), dim=dim)+++def _reorder_v_heads_grouped_to_tiled(+ tensor: torch.Tensor,+ dim: int,+ num_k_heads: int,+ num_v_heads: int,+ head_dim: int,+) -> torch.Tensor:+ dim = dim if dim >= 0 else tensor.ndim + dim+ if dim < 0 or dim >= tensor.ndim or num_k_heads <= 0 or num_v_heads <= 0 or num_v_heads % num_k_heads != 0:+ return tensor+ if tensor.shape[dim] != num_v_heads * head_dim:+ return tensor+ num_v_per_k = num_v_heads // num_k_heads+ shape = list(tensor.shape)+ new_shape = shape[:dim] + [num_k_heads, num_v_per_k, head_dim] + shape[dim + 1 :]+ tensor = tensor.reshape(*new_shape)+ perm = list(range(len(new_shape)))+ perm[dim], perm[dim + 1] = perm[dim + 1], perm[dim]+ return tensor.permute(*perm).reshape(*shape)+++def _reorder_v_heads_tiled_to_grouped(+ tensor: torch.Tensor,+ dim: int,+ num_k_heads: int,+ num_v_heads: int,+ head_dim: int,+) -> torch.Tensor:+ dim = dim if dim >= 0 else tensor.ndim + dim+ if dim < 0 or dim >= tensor.ndim or num_k_heads <= 0 or num_v_heads <= 0 or num_v_heads % num_k_heads != 0:+ return tensor+ if tensor.shape[dim] != num_v_heads * head_dim:+ return tensor+ num_v_per_k = num_v_heads // num_k_heads+ shape = list(tensor.shape)+ new_shape = shape[:dim] + [num_v_per_k, num_k_heads, head_dim] + shape[dim + 1 :]+ tensor = tensor.reshape(*new_shape)+ perm = list(range(len(new_shape)))+ perm[dim], perm[dim + 1] = perm[dim + 1], perm[dim]+ return tensor.permute(*perm).reshape(*shape)+++def _reorder_v_head_axis_grouped_to_tiled(+ tensor: torch.Tensor,+ dim: int,+ num_k_heads: int,+ num_v_heads: int,+) -> torch.Tensor:+ dim = dim if dim >= 0 else tensor.ndim + dim+ if dim < 0 or dim >= tensor.ndim or num_k_heads <= 0 or num_v_heads <= 0 or num_v_heads % num_k_heads != 0:+ return tensor+ if tensor.shape[dim] != num_v_heads:+ return tensor+ num_v_per_k = num_v_heads // num_k_heads+ shape = list(tensor.shape)+ new_shape = shape[:dim] + [num_k_heads, num_v_per_k] + shape[dim + 1 :]+ tensor = tensor.reshape(*new_shape)+ perm = list(range(len(new_shape)))+ perm[dim], perm[dim + 1] = perm[dim + 1], perm[dim]+ return tensor.permute(*perm).reshape(*shape)+++def _reorder_v_head_axis_tiled_to_grouped(+ tensor: torch.Tensor,+ dim: int,+ num_k_heads: int,+ num_v_heads: int,+) -> torch.Tensor:+ dim = dim if dim >= 0 else tensor.ndim + dim+ if dim < 0 or dim >= tensor.ndim or num_k_heads <= 0 or num_v_heads <= 0 or num_v_heads % num_k_heads != 0:+ return tensor+ if tensor.shape[dim] != num_v_heads:+ return tensor+ num_v_per_k = num_v_heads // num_k_heads+ shape = list(tensor.shape)+ new_shape = shape[:dim] + [num_v_per_k, num_k_heads] + shape[dim + 1 :]+ tensor = tensor.reshape(*new_shape)+ perm = list(range(len(new_shape)))+ perm[dim], perm[dim + 1] = perm[dim + 1], perm[dim]+ return tensor.permute(*perm).reshape(*shape)+++def _maybe_reorder_gguf_ssm_param(+ tensor: torch.Tensor,+ *,+ interleave_halves: bool,+ tiled_to_grouped: bool,+ num_k_heads: int,+ num_v_heads: int,+) -> torch.Tensor:+ if tiled_to_grouped:+ return _reorder_v_heads_tiled_to_grouped(tensor, dim=0, num_k_heads=num_k_heads, num_v_heads=num_v_heads, head_dim=1)+ if interleave_halves:+ return _interleave_axis_halves(tensor, dim=0)+ return tensordef clear_qwen35_runtime_caches(device: torch.device | None = None) -> None:@@ -466,6 +573,7 @@ class Qwen3_5Block(nn.Module):self.post_attention_norm.use_triton_rmsnorm = not safe_legacy_kernelsself.ffn_gate = ColumnParallelLinear(int(config.hidden_size), int(config.intermediate_size), bias=False)self.ffn_up = ColumnParallelLinear(int(config.hidden_size), int(config.intermediate_size), bias=False)+ self.ffn_gate_up = Noneself.ffn_down = RowParallelLinear(int(config.intermediate_size), int(config.hidden_size), bias=False)self.mlp_act_fn = SiluAndMul()@@ -496,6 +604,7 @@ class Qwen3_5Block(nn.Module):total_num_kv_heads * self.head_dim,bias=bool(config.attention_bias),)+ self.attn_kv = Noneself.attn_output = RowParallelLinear(total_num_heads * self.head_dim,hidden_size,@@ -527,6 +636,7 @@ class Qwen3_5Block(nn.Module):self.attn_gate = ColumnParallelLinear(hidden_size, self.value_dim, bias=False)self.ssm_alpha = ColumnParallelLinear(hidden_size, self.num_v_heads, bias=False)self.ssm_beta = ColumnParallelLinear(hidden_size, self.num_v_heads, bias=False)+ self.attn_gate_ab = Noneself.ssm_dt = nn.Parameter(torch.zeros(self.num_v_heads))self.ssm_a = nn.Parameter(-torch.ones(self.num_v_heads))if self._short_convolution_cls is not None:@@ -557,6 +667,8 @@ class Qwen3_5Block(nn.Module):self.conv_state_buffer = torch.empty(0)self.recurrent_state_buffer = torch.empty(0)self._gguf_interleave_ssm_ab = False+ self._gguf_v_head_reordered = False+ self._gguf_ssm_param_reordered = Falsedef prepare_sequence_state(self, max_batch_size: int, device: torch.device, dtype: torch.dtype):if self.layer_type != "linear_attention":@@ -632,8 +744,15 @@ class Qwen3_5Block(nn.Module):gate = gate.reshape(batch_size, seq_len, -1)query_states = self.attn_q_norm(query_states)- key_states = self.attn_k_norm(self.attn_k(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim))- value_states = self.attn_v(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim)+ if self.attn_kv is None:+ key_states = self.attn_k(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim)+ value_states = self.attn_v(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim)+ else:+ key_value_states = self.attn_kv(hidden_states).view(batch_size, seq_len, self.num_kv_heads, self.head_dim * 2)+ key_states, value_states = torch.chunk(key_value_states, 2, dim=-1)+ key_states = key_states.contiguous()+ value_states = value_states.contiguous()+ key_states = self.attn_k_norm(key_states)cos, sin = position_embeddingsquery_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)@@ -687,12 +806,39 @@ class Qwen3_5Block(nn.Module):use_precomputed_states = has_previous_state and seq_len == 1mixed_qkv_input = self.attn_qkv(hidden_states)- z = self.attn_gate(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)- b = self.ssm_beta(hidden_states)- a = self.ssm_alpha(hidden_states)- if self._gguf_interleave_ssm_ab:- b = _interleave_last_dim_halves(b)- a = _interleave_last_dim_halves(a)+ if self.attn_gate_ab is None:+ z = self.attn_gate(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)+ a = self.ssm_alpha(hidden_states)+ b = self.ssm_beta(hidden_states)+ else:+ gate_ab = self.attn_gate_ab(hidden_states)+ gate_proj, a, b = torch.split(gate_ab, [self.value_dim, self.num_v_heads, self.num_v_heads], dim=-1)+ z = gate_proj.reshape(batch_size, seq_len, -1, self.head_v_dim)+ if self._gguf_v_head_reordered:+ z = _reorder_v_head_axis_tiled_to_grouped(+ z,+ dim=2,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ )+ if self._gguf_v_head_reordered:+ b = _reorder_v_heads_tiled_to_grouped(+ b,+ dim=-1,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ head_dim=1,+ )+ a = _reorder_v_heads_tiled_to_grouped(+ a,+ dim=-1,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ head_dim=1,+ )+ elif self._gguf_interleave_ssm_ab:+ b = _interleave_axis_halves(b, dim=-1)+ a = _interleave_axis_halves(a, dim=-1)use_short_convolution = (self._use_short_convolution@@ -774,9 +920,30 @@ class Qwen3_5Block(nn.Module):query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)+ if self._gguf_v_head_reordered:+ value = _reorder_v_head_axis_tiled_to_grouped(+ value,+ dim=2,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ )beta = b.sigmoid()- g = self.ssm_a.float() * F.softplus(a.float() + self.ssm_dt)+ ssm_a = _maybe_reorder_gguf_ssm_param(+ self.ssm_a,+ interleave_halves=self._gguf_interleave_ssm_ab,+ tiled_to_grouped=self._gguf_ssm_param_reordered,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ )+ ssm_dt = _maybe_reorder_gguf_ssm_param(+ self.ssm_dt,+ interleave_halves=self._gguf_interleave_ssm_ab,+ tiled_to_grouped=self._gguf_ssm_param_reordered,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ )+ g = ssm_a.float() * F.softplus(a.float() + ssm_dt)if self.num_v_heads // self.num_k_heads > 1:repeat_factor = self.num_v_heads // self.num_k_headsquery = query.repeat_interleave(repeat_factor, dim=2)@@ -837,6 +1004,14 @@ class Qwen3_5Block(nn.Module):z.reshape(-1, self.head_v_dim),)core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)+ if self._gguf_v_head_reordered:+ core_attn_out = _reorder_v_heads_grouped_to_tiled(+ core_attn_out,+ dim=-1,+ num_k_heads=self.num_k_heads,+ num_v_heads=self.num_v_heads,+ head_dim=self.head_v_dim,+ )return self.ssm_out(core_attn_out)def forward(@@ -859,7 +1034,8 @@ class Qwen3_5Block(nn.Module):hidden_states = self._forward_linear_attention(hidden_states, layer_idx, past_key_values, attention_mask)hidden_states, residual = self.post_attention_norm(hidden_states, residual)- hidden_states = self.ffn_down(self.mlp_act_fn(torch.cat((self.ffn_gate(hidden_states), self.ffn_up(hidden_states)), dim=-1)))+ gate_up = self.ffn_gate_up(hidden_states) if self.ffn_gate_up is not None else torch.cat((self.ffn_gate(hidden_states), self.ffn_up(hidden_states)), dim=-1)+ hidden_states = self.ffn_down(self.mlp_act_fn(gate_up))return hidden_states, residualdiff --git a/shared/llm_engines/nanovllm/sampling_params.py b/shared/llm_engines/nanovllm/sampling_params.pyindex 291a1c2..49cc28b 100644--- a/shared/llm_engines/nanovllm/sampling_params.py+++ b/shared/llm_engines/nanovllm/sampling_params.py@@ -10,6 +10,7 @@ class SamplingParams:cfg_scale: float = 1.0 # CFG guidance scale. When > 1.0, applies classifier-free guidancetop_k: Optional[int] = None # Top-k sampling: consider only top k tokenstop_p: Optional[float] = None # Top-p (nucleus) sampling: consider tokens with cumulative probability <= top_p+ min_p: Optional[float] = None # Min-p sampling: keep tokens with probability >= min_p * max_probrepetition_penalty: float = 1.0 # Repetition penalty: >1.0 reduces repetition, <1.0 increases it# Optional logits processor for constrained decoding# Should be a callable with signature: (input_ids: torch.Tensor, logits: torch.Tensor) -> torch.Tensor@@ -29,4 +30,6 @@ class SamplingParams:assert self.top_k > 0, "top_k must be > 0"if self.top_p is not None:assert 0.0 < self.top_p <= 1.0, "top_p must be in (0.0, 1.0]"+ if self.min_p is not None:+ assert 0.0 < self.min_p <= 1.0, "min_p must be in (0.0, 1.0]"assert self.repetition_penalty > 0.0, "repetition_penalty must be > 0.0"diff --git a/shared/prompt_enhancer/prompt_enhance_utils.py b/shared/prompt_enhancer/prompt_enhance_utils.pyindex 6dc1354..d728f74 100644--- a/shared/prompt_enhancer/prompt_enhance_utils.py+++ b/shared/prompt_enhancer/prompt_enhance_utils.py@@ -47,6 +47,11 @@ Do not exceed the 150 word limit!Output the enhanced prompt only."""+QWEN35_THINKING_SUPER_SYSTEM_PROMPT = """Use private reasoning to solve the task as well as possible.+Keep your thinking hidden and do not output any reasoning, chain-of-thought, or thinking process.+Always review your final answer to ensure it meets the user request.+"""+IT2V_CINEMATIC_PROMPT = """You are an expert cinematic director with many award winning movies.You have the following information:1. The user provides a general text input about its scenes expectations@@ -148,6 +153,54 @@ def tensor_to_pil(tensor):return Image.fromarray(numpy_image)+def _use_qwen35_thinking_prompt(prompt_enhancer_model, thinking_enabled: Optional[bool] = None) -> bool:+ if thinking_enabled is not None:+ return bool(thinking_enabled)+ return bool(getattr(prompt_enhancer_model, "_prompt_enhancer_enable_thinking", False))+++def _split_prompt_enhancer_system_suffix(prompt_enhancer_model, prompt: str) -> tuple[str, str, bool]:+ del prompt_enhancer_model+ prompt = str(prompt or "").strip()+ prompt_body, separator, system_suffix = prompt.partition("@@")+ if separator == "@@":+ return prompt_body.strip(), system_suffix.strip(), True+ prompt_body, separator, system_suffix = prompt.partition("@")+ if separator == "":+ return prompt, "", False+ return prompt_body.strip(), system_suffix.strip(), False+++def _merge_prompt_enhancer_system_prompt(prompt_enhancer_model, system_prompt: str, system_suffix: str, replace_system_prompt: bool = False, thinking_enabled: Optional[bool] = None) -> str:+ system_prompt = str(system_prompt or "").rstrip()+ system_suffix = str(system_suffix or "").strip()+ if len(system_suffix) == 0:+ merged_prompt = system_prompt+ elif replace_system_prompt:+ merged_prompt = system_suffix+ else:+ merged_prompt = f"{system_prompt}\nFollow these additional user instructions with higher priority if they conflict with the guidance above:\n{system_suffix}"+ if not _use_qwen35_thinking_prompt(prompt_enhancer_model, thinking_enabled=thinking_enabled):+ return merged_prompt+ if len(merged_prompt) == 0:+ return QWEN35_THINKING_SUPER_SYSTEM_PROMPT.strip()+ return f"{QWEN35_THINKING_SUPER_SYSTEM_PROMPT.rstrip()}\n\n{merged_prompt}"+++def _format_prompt_enhancer_user_content(prompt_enhancer_model, prompt: str, image_caption: Optional[str] = None, thinking_enabled: Optional[bool] = None) -> str:+ prompt, _system_suffix, _replace_system_prompt = _split_prompt_enhancer_system_suffix(prompt_enhancer_model, prompt)+ if not _use_qwen35_thinking_prompt(prompt_enhancer_model, thinking_enabled=thinking_enabled):+ if image_caption is None:+ return f"user_prompt: {prompt}"+ return f"user_prompt: {prompt}\nimage_caption: {image_caption}"+ if image_caption is None:+ return prompt+ image_caption = str(image_caption or "").strip()+ if len(prompt) == 0:+ return f"image_caption:\n{image_caption}"+ return f"{prompt}\n\nimage_caption:\n{image_caption}"++def generate_cinematic_prompt(image_caption_model,image_caption_processor,@@ -165,12 +218,13 @@ def generate_cinematic_prompt(top_k: Optional[int] = None,seed: Optional[int] = None,post_image_caption_hook = None,+ thinking_enabled: Optional[bool] = None,) -> List[str]:prompts = [prompt] if isinstance(prompt, str) else promptif images is None:if prompt_enhancer_instructions is None:- prompt_enhancer_instructions= T2T_TEXT_PROMPT if text_prompt else (T2V_CINEMATIC_PROMPT if video_prompt else T2I_VISUAL_PROMPT)+ prompt_enhancer_instructions = T2T_TEXT_PROMPT if text_prompt else (T2V_CINEMATIC_PROMPT if video_prompt else T2I_VISUAL_PROMPT)prompts = _generate_t2v_prompt(prompt_enhancer_model,prompt_enhancer_tokenizer,@@ -182,10 +236,11 @@ def generate_cinematic_prompt(top_p,top_k,seed,+ thinking_enabled,)else:if prompt_enhancer_instructions is None:- prompt_enhancer_instructions= IT2V_CINEMATIC_PROMPT if video_prompt else IT2I_VISUAL_PROMPT+ prompt_enhancer_instructions = IT2V_CINEMATIC_PROMPT if video_prompt else IT2I_VISUAL_PROMPTprompts = _generate_i2v_prompt(image_caption_model,@@ -202,6 +257,7 @@ def generate_cinematic_prompt(top_k,seed,post_image_caption_hook=post_image_caption_hook,+ thinking_enabled=thinking_enabled,)return prompts@@ -226,14 +282,18 @@ def _generate_t2v_prompt(top_p: Optional[float],top_k: Optional[int],seed: Optional[int],+ thinking_enabled: Optional[bool],) -> List[str]:- messages = [- [- {"role": "system", "content": system_prompt},- {"role": "user", "content": f"user_prompt: {p}"},- ]- for p in prompts- ]+ messages = []+ for prompt in prompts:+ prompt_body, system_suffix, replace_system_prompt = _split_prompt_enhancer_system_suffix(prompt_enhancer_model, prompt)+ message_system_prompt = _merge_prompt_enhancer_system_prompt(prompt_enhancer_model, system_prompt, system_suffix, replace_system_prompt, thinking_enabled=thinking_enabled)+ messages.append(+ [+ {"role": "system", "content": message_system_prompt},+ {"role": "user", "content": _format_prompt_enhancer_user_content(prompt_enhancer_model, prompt_body, thinking_enabled=thinking_enabled)},+ ]+ )if hasattr(prompt_enhancer_model, "generate_messages"):return prompt_enhancer_model.generate_messages(@@ -244,6 +304,7 @@ def _generate_t2v_prompt(top_p=top_p,top_k=top_k,seed=seed,+ thinking_enabled=thinking_enabled,)texts = [@@ -290,6 +351,7 @@ def _generate_i2v_prompt(top_k: Optional[int],seed: Optional[int],post_image_caption_hook = None,+ thinking_enabled: Optional[bool] = None,) -> List[str]:if hasattr(image_caption_model, "generate_image_captions"):image_captions = image_caption_model.generate_image_captions(first_frames)@@ -305,13 +367,16 @@ def _generate_i2v_prompt(post_image_caption_hook()if len(image_captions) == 1 and len(image_captions) < len(prompts):image_captions *= len(prompts)- messages = [- [- {"role": "system", "content": system_prompt},- {"role": "user", "content": f"user_prompt: {p}\nimage_caption: {c}"},- ]- for p, c in zip(prompts, image_captions)- ]+ messages = []+ for prompt, image_caption in zip(prompts, image_captions):+ prompt_body, system_suffix, replace_system_prompt = _split_prompt_enhancer_system_suffix(prompt_enhancer_model, prompt)+ message_system_prompt = _merge_prompt_enhancer_system_prompt(prompt_enhancer_model, system_prompt, system_suffix, replace_system_prompt, thinking_enabled=thinking_enabled)+ messages.append(+ [+ {"role": "system", "content": message_system_prompt},+ {"role": "user", "content": _format_prompt_enhancer_user_content(prompt_enhancer_model, prompt_body, image_caption=image_caption, thinking_enabled=thinking_enabled)},+ ]+ )if hasattr(prompt_enhancer_model, "generate_messages"):return prompt_enhancer_model.generate_messages(@@ -322,6 +387,7 @@ def _generate_i2v_prompt(top_p=top_p,top_k=top_k,seed=seed,+ thinking_enabled=thinking_enabled,)texts = [diff --git a/shared/prompt_enhancer/qwen35_text.py b/shared/prompt_enhancer/qwen35_text.pyindex 469d0db..f8aec12 100644--- a/shared/prompt_enhancer/qwen35_text.py+++ b/shared/prompt_enhancer/qwen35_text.py@@ -4,6 +4,7 @@ import gcimport jsonimport osimport re+import sysimport typesfrom collections import OrderedDict@@ -18,7 +19,7 @@ from shared.llm_engines.nanovllm.vllm_support import (NanoVllmTextEngine,resolve_lm_decoder_engine,)-from shared.qtypes.gguf import materialize_module_source_tensors+from shared.qtypes.gguf import GGUFWeightTensor, materialize_module_source_tensorsfrom .qwen3_5 import register_qwen35_configfrom .qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig@@ -27,6 +28,7 @@ from .qwen35_vl import (enhancer_quantization_QUANTO_INT8,_collect_suppressed_token_ids,_collect_stop_token_ids,+ _resolve_qwen35_checkpoint_file,_load_qwen35_tokenizer,_resolve_qwen35_asset_file,_resolve_qwen35_assets_dir,@@ -40,9 +42,13 @@ QWEN35_TEXT_VLLM_CUDAGRAPH_ENV = "WGP_QWEN35_PROMPT_ENHANCER_VLLM_CUDAGRAPH"QWEN35_GGUF_LLAMACPP_ENV = "WGP_GGUF_LLAMACPP_CUDA"QWEN35_PROMPT_MIN_NEW_TOKENS = 4QWEN35_PROMPT_DEFAULT_TOP_K = 20+QWEN35_PROMPT_DEFAULT_MIN_P_GGUF = 0.05QWEN35_PROMPT_ENABLE_PRESENCE_PENALTY = TrueQWEN35_PROMPT_PRESENCE_PENALTY = 1.5QWEN35_PROMPT_SUPPRESS_LOGITS_BIAS = -1e4+QWEN35_PROMPT_ENABLE_THINKING = False+QWEN35_PROMPT_THINKING_EXTRA_TOKENS = 3000+QWEN35_PROMPT_THINKING_MAX_TOKENS = 2000def _env_enabled(name: str, default: bool = True) -> bool:@@ -57,7 +63,6 @@ def _resolve_gguf_model_path(model_path: str | None, assets_dir: str, variant: sraise FileNotFoundError(f"Missing Qwen3.5 GGUF checkpoint: {resolved}")return resolved- assets_dir = _resolve_qwen35_assets_dir(assets_dir, variant=variant)exact_path = get_qwen35_text_gguf_path(assets_dir, variant=variant)if os.path.isfile(exact_path):return exact_path@@ -69,9 +74,21 @@ def get_qwen35_text_assets_dir(assets_dir: str, variant: str | None = None) -> sdef get_qwen35_text_quanto_int8_path(assets_dir: str, variant: str | None = None) -> str:- assets_dir = _resolve_qwen35_assets_dir(assets_dir, variant=variant)filename = get_qwen35_variant_spec(variant)["text_int8_filename"]- return _resolve_qwen35_asset_file(assets_dir, filename, variant=variant, error_if_none=False) or os.path.join(assets_dir, filename)+ return _resolve_qwen35_checkpoint_file(assets_dir, filename, variant=variant, error_if_none=False)+++def _resolve_gguf_linear_attention_layout_from_filename(model_path: str) -> tuple[bool, bool, bool]:+ filename = os.path.basename(str(model_path or "")).strip().lower().replace("_", "-")+ if filename == "qwen3.5-9b-abliterated-q4-k-m-bis.gguf":+ return True, True, False+ if filename in {+ "qwen3.5-9b-abliterated-text-q4-k-m.gguf",+ "qwen3.5-4b-abliterated-text-q4-k-m.gguf",+ }:+ return False, True, False+ return False, False, True+def _load_text_config(config_path: str) -> Qwen3_5TextConfig:with open(config_path, "r", encoding="utf-8") as reader:@@ -91,19 +108,6 @@ def _ensure_tied_output_weight(new_sd, tied_map):return tied_map-def _interleave_qwen35_ssm_heads(tensor: torch.Tensor) -> torch.Tensor:- if tensor.ndim == 0 or tensor.shape[0] % 2 != 0:- return tensor- half = tensor.shape[0] // 2- if tensor.ndim == 1:- output = torch.empty_like(tensor)- output[0::2] = tensor[:half]- output[1::2] = tensor[half:]- return output- first_half, second_half = tensor[:half], tensor[half:]- return torch.stack((first_half, second_half), dim=1).flatten(0, 1)--def _build_qwen35_gguf_preprocess_sd(tie_output_to_embeddings: bool = False):def preprocess_sd(sd, quant_map=None, tied_map=None):new_sd = OrderedDict()@@ -112,8 +116,6 @@ def _build_qwen35_gguf_preprocess_sd(tie_output_to_embeddings: bool = False):continueif name.endswith(".ssm_dt.bias"):name = name[:-5]- if name.endswith(".ssm_dt") or name.endswith(".ssm_a"):- tensor = _interleave_qwen35_ssm_heads(tensor)if name.endswith(".ssm_conv1d.weight"):tensor = tensor.unsqueeze(1)new_sd[name] = tensor@@ -124,9 +126,8 @@ def _build_qwen35_gguf_preprocess_sd(tie_output_to_embeddings: bool = False):return preprocess_sd-def _clean_generated_text(text: str) -> str:- text = re.sub(r"<think>.*?</think>", "\n", text, flags=re.DOTALL | re.IGNORECASE)- text = re.sub(r"<think>.*$", "", text, flags=re.DOTALL | re.IGNORECASE)+def _normalize_generated_text(text: str) -> str:+ text = str(text or "")text = text.replace("<|im_end|>", "").replace("<|im_start|>", "")text = text.replace("\r\n", "\n").replace("\r", "\n")text = re.sub(r"[ \t]+\n", "\n", text)@@ -135,6 +136,97 @@ def _clean_generated_text(text: str) -> str:return "\n".join(line for line in lines if line).strip()+def _clean_answer_text(text: str) -> str:+ text = str(text or "").replace("\r\n", "\n").replace("\r", "\n")+ text = re.sub(r"^(?:\s*</think>\s*)+", "", text, flags=re.IGNORECASE)+ text = text.replace("<think>", "\n").replace("</think>", "\n")+ text = re.sub(r"^\s*assistant\s*:?\s*", "", text, flags=re.IGNORECASE)+ text = re.split(+ r"(?:<\|im_start\|>\s*(?:assistant|user|system|tool)\b|<tool_call>\s*|<tool_response>\s*|<tools>\s*|\n\s*(?:assistant|user|system|tool)\s*:)",+ text,+ maxsplit=1,+ flags=re.IGNORECASE,+ )[0]+ cleaned_lines = []+ for line in text.split("\n"):+ stripped = line.strip()+ if len(stripped) == 0:+ continue+ if stripped.lower() == "code interpreter":+ break+ cleaned_lines.append(line)+ return _normalize_generated_text("\n".join(cleaned_lines))+++def _split_generated_text(text: str) -> tuple[str, str]:+ text = str(text or "").replace("\r\n", "\n").replace("\r", "\n")+ think_chunks = [match.group(1) for match in re.finditer(r"<think>\s*(.*?)\s*</think>", text, flags=re.DOTALL | re.IGNORECASE)]+ answer_text = re.sub(r"<think>.*?</think>", "\n", text, flags=re.DOTALL | re.IGNORECASE)+ if len(think_chunks) == 0:+ forced_open_match = re.search(r"</think>", text, flags=re.IGNORECASE)+ if forced_open_match is not None:+ forced_reasoning = text[:forced_open_match.start()]+ forced_reasoning = forced_reasoning.replace("<think>", "\n")+ forced_reasoning = _normalize_generated_text(forced_reasoning)+ if len(forced_reasoning) > 0:+ think_chunks.append(forced_reasoning)+ answer_text = text[forced_open_match.end():]+ if len(think_chunks) == 0:+ timeline_match = re.search(r"(?mi)^\(at\s+[0-9]+(?:\.[0-9]+)?\s+seconds?\s*:", text)+ if timeline_match is not None:+ leading_text = _normalize_generated_text(text[:timeline_match.start()])+ if leading_text.lower().startswith("thinking process"):+ think_chunks.append(leading_text)+ answer_text = text[timeline_match.start():]+ answer_text = re.sub(r"<think>.*$", "\n", answer_text, flags=re.DOTALL | re.IGNORECASE)+ return _normalize_generated_text("\n\n".join(chunk for chunk in think_chunks if chunk.strip())), _clean_answer_text(answer_text)+++def _clean_generated_text(text: str) -> str:+ _thinking_text, answer_text = _split_generated_text(text)+ return answer_text+++def _prompt_enhancer_thinking_enabled(model, thinking_enabled: bool | None = None) -> bool:+ if thinking_enabled is not None:+ return bool(thinking_enabled)+ return bool(getattr(model, "_prompt_enhancer_enable_thinking", QWEN35_PROMPT_ENABLE_THINKING))+++def set_qwen35_prompt_enhancer_thinking(model, enabled: bool) -> None:+ model._prompt_enhancer_enable_thinking = bool(enabled)+ tokenizer = getattr(model, "_prompt_enhancer_tokenizer", None)+ if tokenizer is None:+ return+ base_suppress_token_ids = tuple(_collect_suppressed_token_ids(tokenizer))+ model._prompt_enhancer_base_suppress_token_ids = base_suppress_token_ids+ model._prompt_enhancer_suppress_token_ids = [] if model._prompt_enhancer_enable_thinking else list(base_suppress_token_ids)+ model._prompt_enhancer_suppress_logits_bias = None+++def _resolve_prompt_runtime_extra_tokens(model, thinking_enabled: bool | None = None) -> int:+ if not _prompt_enhancer_thinking_enabled(model, thinking_enabled=thinking_enabled):+ return 0+ extra_tokens = getattr(model, "_prompt_enhancer_thinking_extra_tokens", QWEN35_PROMPT_THINKING_EXTRA_TOKENS)+ try:+ return max(0, int(extra_tokens))+ except Exception:+ return 0+++def _print_thinking_process(message_index: int, total_messages: int, thinking_text: str) -> None:+ if len(thinking_text) == 0:+ return+ print(f"[Prompt Enhancer][Thinking {message_index + 1}/{total_messages}]")+ try:+ print(thinking_text)+ except UnicodeEncodeError:+ encoding = getattr(sys.stdout, "encoding", None) or "utf-8"+ safe_text = thinking_text.encode(encoding, errors="replace").decode(encoding, errors="replace")+ sys.stdout.write(safe_text + "\n")+ sys.stdout.flush()++class _PresencePenaltyState:def __init__(self, presence_penalty: float | None):if presence_penalty is None or float(presence_penalty) <= 0:@@ -173,14 +265,49 @@ class _PresencePenaltyState:return logits+class _ThinkingBudgetState:+ def __init__(self, close_think_token_id: int | None, max_thinking_tokens: int | None):+ try:+ close_think_token_id = int(close_think_token_id)+ except (TypeError, ValueError):+ close_think_token_id = -1+ try:+ max_thinking_tokens = int(max_thinking_tokens)+ except (TypeError, ValueError):+ max_thinking_tokens = 0+ self.close_think_token_id = close_think_token_id+ self.max_thinking_tokens = max_thinking_tokens+ self.in_thinking = close_think_token_id >= 0 and max_thinking_tokens > 0+ self.generated_thinking_tokens = 0++ def enabled(self) -> bool:+ return self.in_thinking++ def update(self, token_id: int) -> None:+ if not self.in_thinking:+ return+ token_id = int(token_id)+ if token_id == self.close_think_token_id:+ self.in_thinking = False+ return+ self.generated_thinking_tokens += 1++ def apply_(self, logits: torch.Tensor) -> torch.Tensor:+ if not self.in_thinking or self.generated_thinking_tokens < self.max_thinking_tokens:+ return logits+ logits.fill_(float("-inf"))+ logits[..., self.close_think_token_id] = 0+ return logits++-def _build_chat_prompt(tokenizer, message):+def _build_chat_prompt(tokenizer, message, enable_thinking: bool = False):text = tokenizer.apply_chat_template(message,tokenize=False,add_generation_prompt=True,- enable_thinking=False,+ enable_thinking=bool(enable_thinking),)return text.rstrip() + "\n"@@ -210,20 +337,70 @@ def _build_presence_penalty_logits_processor(presence_penalty: float | None):return logits_processor, update_state-def _build_suppressed_token_logits_bias(model):- cached_bias = getattr(model, "_prompt_enhancer_suppress_logits_bias", None)- if torch.is_tensor(cached_bias):- return cached_bias- suppress_token_ids = list(getattr(model, "_prompt_enhancer_suppress_token_ids", []) or [])+def _build_prompt_logits_processor(model, thinking_enabled: bool | None = None):+ processors = []+ update_callbacks = []++ presence_processor, presence_update_state = _build_presence_penalty_logits_processor(_resolve_prompt_presence_penalty(model))+ if presence_processor is not None:+ processors.append(presence_processor)+ if presence_update_state is not None:+ update_callbacks.append(presence_update_state)++ if _prompt_enhancer_thinking_enabled(model, thinking_enabled=thinking_enabled):+ thinking_state = _ThinkingBudgetState(+ getattr(model, "_prompt_enhancer_close_think_token_id", None),+ getattr(model, "_prompt_enhancer_thinking_max_tokens", QWEN35_PROMPT_THINKING_MAX_TOKENS),+ )+ if thinking_state.enabled():+ def thinking_logits_processor(_input_ids, logits):+ return thinking_state.apply_(logits)++ processors.append(thinking_logits_processor)+ update_callbacks.append(thinking_state.update)++ if not processors:+ return None, None++ if len(processors) == 1:+ logits_processor = processors[0]+ else:+ def logits_processor(input_ids, logits):+ for processor in processors:+ logits = processor(input_ids, logits)+ return logits++ if len(update_callbacks) == 1:+ update_state = update_callbacks[0]+ else:+ def update_state(token_id: int):+ for callback in update_callbacks:+ callback(token_id)++ return logits_processor, update_state+++def _build_suppressed_token_logits_bias(model, thinking_enabled: bool | None = None):+ if _prompt_enhancer_thinking_enabled(model, thinking_enabled=thinking_enabled):+ return None+ suppress_token_ids = tuple(int(token_id) for token_id in tuple(getattr(model, "_prompt_enhancer_base_suppress_token_ids", ()) or ()) if int(token_id) >= 0)vocab_size = int(getattr(getattr(model, "config", None), "vocab_size", 0) or 0)if vocab_size <= 0 or len(suppress_token_ids) == 0:return None- valid_token_ids = [int(token_id) for token_id in suppress_token_ids if 0 <= int(token_id) < vocab_size]+ valid_token_ids = tuple(token_id for token_id in suppress_token_ids if token_id < vocab_size)if len(valid_token_ids) == 0:return None+ cache = getattr(model, "_prompt_enhancer_suppress_logits_bias_cache", None)+ if not isinstance(cache, dict):+ cache = {}+ model._prompt_enhancer_suppress_logits_bias_cache = cache+ cache_key = (vocab_size, valid_token_ids)+ cached_bias = cache.get(cache_key)+ if torch.is_tensor(cached_bias):+ return cached_biasbias = torch.zeros(vocab_size, dtype=torch.float32)bias[torch.tensor(valid_token_ids, dtype=torch.long)] = float(QWEN35_PROMPT_SUPPRESS_LOGITS_BIAS)- model._prompt_enhancer_suppress_logits_bias = bias+ cache[cache_key] = biasreturn bias@@ -246,6 +423,16 @@ def _resolve_prompt_top_k(model, top_k):return Nonedefault_top_k = int(default_top_k)return default_top_k if default_top_k > 0 else None+++def _resolve_prompt_min_p(model):+ min_p = getattr(model, "_prompt_enhancer_default_min_p", None)+ if min_p is None:+ return None+ min_p = float(min_p)+ return min_p if min_p > 0.0 else None++def _resolve_prompt_enhancer_engine(backend: str, requested_lm_engine: str, runtime_model_path: str | None):del backendif runtime_model_path is None:@@ -345,6 +532,7 @@ def _generate_messages_vllm(top_p=None,top_k=None,seed=None,+ thinking_enabled: bool | None = None,):reset_context()tokenizer = self._prompt_enhancer_tokenizer@@ -353,47 +541,40 @@ def _generate_messages_vllm(engine = _get_or_create_vllm_engine(self, usage_mode="text")outputs = []+ thinking_enabled = _prompt_enhancer_thinking_enabled(self, thinking_enabled=thinking_enabled)+ runtime_extra_tokens = _resolve_prompt_runtime_extra_tokens(self, thinking_enabled=thinking_enabled)progress_desc = ("Qwen3.5 prompt enhancement (legacy)"if _use_legacy_cuda_runner_prompt_enhancer(self)else f"Qwen3.5 prompt enhancement ({getattr(self, '_prompt_enhancer_engine_name', 'vllm')})")for idx, message in enumerate(tqdm(messages, total=len(messages), desc=progress_desc, dynamic_ncols=True, leave=False)):- prompt = _build_chat_prompt(tokenizer, message)+ prompt = _build_chat_prompt(tokenizer, message, enable_thinking=thinking_enabled)try:prompt_len = len(tokenizer.encode(prompt))except Exception:prompt_len = 0- engine.reserve_runtime(prompt_len=prompt_len, max_tokens=int(max_new_tokens), cfg_scale=1.0)+ generation_max_tokens = int(max_new_tokens) + runtime_extra_tokens+ engine.reserve_runtime(prompt_len=prompt_len, max_tokens=generation_max_tokens, cfg_scale=1.0)engine._ensure_llm()if engine._llm is None:raise RuntimeError("Qwen3.5 prompt enhancer vLLM runtime is not available.")- # The shared Qwen text model may have been used by captioning right before prompt- # enhancement. Rebuild the vLLM runtime so CUDA graphs are always captured against- # clean sequence/KV state for the current MMGP-loaded weights.- engine.release_runtime_allocations()- _reset_vllm_sequence_state(self)- engine._llm.model_runner.ensure_runtime_ready()- try:- engine._llm.reset()- except Exception:- pass-temp, normalized_top_p, normalized_top_k = _normalize_vllm_sampling(do_sample=bool(do_sample),temperature=temperature,top_p=top_p,top_k=top_k,)+ logits_bias = _build_suppressed_token_logits_bias(self, thinking_enabled=thinking_enabled)sample_seed = None if seed is None else int(seed) + idx- logits_bias = _build_suppressed_token_logits_bias(self)- logits_processor, logits_processor_update_state = _build_presence_penalty_logits_processor(_resolve_prompt_presence_penalty(self))+ logits_processor, logits_processor_update_state = _build_prompt_logits_processor(self, thinking_enabled=thinking_enabled)sampling_params = SamplingParams(temperature=temp,- max_tokens=int(max_new_tokens),+ max_tokens=generation_max_tokens,cfg_scale=1.0,top_k=normalized_top_k,top_p=normalized_top_p,+ min_p=_resolve_prompt_min_p(self),ignore_eos=False,logits_processor=logits_processor,logits_processor_update_state=logits_processor_update_state,@@ -415,8 +596,17 @@ def _generate_messages_vllm(finally:reset_context()- text, _ = engine._extract_text_and_tokens(batch_outputs[0] if batch_outputs else None)- outputs.append(_clean_generated_text(text))+ text, token_ids = engine._extract_text_and_tokens(batch_outputs[0] if batch_outputs else None)+ raw_text = text+ if token_ids:+ try:+ raw_text = tokenizer.decode(token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)+ except Exception:+ raw_text = text+ thinking_text, answer_text = _split_generated_text(raw_text)+ if thinking_enabled:+ _print_thinking_process(idx, len(messages), thinking_text)+ outputs.append(answer_text)return outputs@@ -429,6 +619,7 @@ def _generate_messages(top_p=None,top_k=None,seed=None,+ thinking_enabled: bool | None = None,):top_k = _resolve_prompt_top_k(self, top_k)if _use_vllm_prompt_enhancer(self) or _use_legacy_cuda_runner_prompt_enhancer(self):@@ -441,6 +632,7 @@ def _generate_messages(top_p=top_p,top_k=top_k,seed=seed,+ thinking_enabled=thinking_enabled,)raise RuntimeError("Qwen3.5 prompt enhancer text runtime is not configured with an available decode engine.")@@ -480,6 +672,7 @@ def _load_local_text_model(preprocess_sd=None,default_dtype: torch.dtype = torch.float16,safe_legacy_mode: bool = False,+ materialize_source_tensors: bool = True,):config = _load_text_config(config_path)config._prompt_enhancer_safe_legacy = bool(safe_legacy_mode)@@ -493,7 +686,8 @@ def _load_local_text_model(writable_tensors=False,default_dtype=default_dtype,)- materialize_module_source_tensors(model)+ if materialize_source_tensors:+ materialize_module_source_tensors(model)return model@@ -503,13 +697,115 @@ def _resolve_legacy_text_execution_device() -> torch.device:return torch.device("cuda", torch.cuda.current_device())-def _configure_qwen35_gguf_text_model(model, model_dtype: torch.dtype):+def _configure_qwen35_gguf_text_model(+ model,+ model_dtype: torch.dtype,+ *,+ v_head_reordered: bool = False,+ ssm_param_reordered: bool = False,+ interleave_ssm_ab: bool = False,+):for module in model.modules():if getattr(module, "layer_type", None) == "linear_attention" and hasattr(module, "_gguf_interleave_ssm_ab"):- module._gguf_interleave_ssm_ab = True+ module._gguf_interleave_ssm_ab = bool(interleave_ssm_ab)+ if getattr(module, "layer_type", None) == "linear_attention" and hasattr(module, "_gguf_v_head_reordered"):+ module._gguf_v_head_reordered = bool(v_head_reordered)+ if getattr(module, "layer_type", None) == "linear_attention" and hasattr(module, "_gguf_ssm_param_reordered"):+ module._gguf_ssm_param_reordered = bool(ssm_param_reordered)model.config.dtype = model_dtypemodel.config.torch_dtype = model_dtype++def _concat_linear_weights(weights):+ if len(weights) == 0:+ raise ValueError("At least one linear weight is required to build a fused projection.")+ first = weights[0]+ if isinstance(first, GGUFWeightTensor):+ tensor_type = getattr(first, "_tensor_type", None)+ dtype = getattr(first, "dtype", torch.float16)+ device = getattr(first, "device", torch.device("cpu"))+ if all(+ isinstance(weight, GGUFWeightTensor)+ and getattr(weight, "_tensor_type", None) == tensor_type+ and int(weight.shape[1]) == int(first.shape[1])+ for weight in weights+ ):+ raw = torch.cat([weight._data for weight in weights], dim=0)+ out_features = sum(int(weight.shape[0]) for weight in weights)+ in_features = int(first.shape[1])+ return GGUFWeightTensor.create(+ raw_tensor=raw,+ size=(out_features, in_features),+ stride=(in_features, 1),+ dtype=dtype,+ device=device,+ requires_grad=False,+ tensor_type=tensor_type,+ tensor_shape=(out_features, in_features),+ )+ return torch.cat([weight.detach() for weight in weights], dim=0)+++def _concat_linear_biases(biases):+ if len(biases) == 0 or any(bias is None for bias in biases):+ return None+ return torch.cat([bias.detach() for bias in biases], dim=0)+++def _build_fused_column_linear(modules):+ modules = [module for module in modules if module is not None]+ if len(modules) <= 1:+ return modules[0] if modules else None+ template = modules[0]+ out_features = sum(int(module.weight.shape[0]) for module in modules)+ fused_kwargs = {}+ for attr_name, kwarg_name in (+ ("weight_qtype", "weights"),+ ("activation_qtype", "activations"),+ ("optimizer", "optimizer"),+ ("quantize_input", "quantize_input"),+ ):+ if hasattr(template, attr_name):+ fused_kwargs[kwarg_name] = getattr(template, attr_name)+ if hasattr(template, "_router_default_dtype"):+ fused_kwargs["dtype"] = template._router_default_dtype+ if hasattr(template, "weight") and torch.is_tensor(template.weight):+ fused_kwargs.setdefault("device", template.weight.device)+ fused_kwargs.setdefault("dtype", template.weight.dtype)+ try:+ fused = template.__class__(int(template.in_features), out_features, bias=all(module.bias is not None for module in modules), **fused_kwargs)+ except TypeError:+ fused = template.__class__(int(template.in_features), out_features, bias=all(module.bias is not None for module in modules))+ fused_weight = _concat_linear_weights([module.weight for module in modules])+ fused._parameters["weight"] = fused_weight+ fused._parameters["bias"] = _concat_linear_biases([module.bias for module in modules])+ if hasattr(fused, "qweight"):+ try:+ fused.qweight = fused_weight+ except Exception:+ pass+ for attr_name in ("weight_qtype", "activation_qtype", "optimizer", "input_scale", "output_scale", "_router_default_dtype", "_router_forward_impl"):+ if hasattr(template, attr_name):+ setattr(fused, attr_name, getattr(template, attr_name))+ if hasattr(template, "_gguf_default_dtype"):+ fused._gguf_default_dtype = template._gguf_default_dtype+ return fused+++def _apply_qwen35_gguf_projection_fusions(model) -> None:+ for block in getattr(model, "blk", ()):+ if getattr(block, "layer_type", None) != "linear_attention":+ continue+ # Real prompt-enhancer benchmarks only kept this fusion: it removes two extra+ # GGUF matmul launches from the hottest decode block without changing the decode path.+ if getattr(block, "attn_gate_ab", None) is None and all(+ getattr(block, name, None) is not None for name in ("attn_gate", "ssm_alpha", "ssm_beta")+ ):+ block.attn_gate_ab = _build_fused_column_linear([block.attn_gate, block.ssm_alpha, block.ssm_beta])+ block.attn_gate = None+ block.ssm_alpha = None+ block.ssm_beta = None+def load_qwen35_text_prompt_enhancer(model_path: str | None = None,assets_dir: str | None = None,@@ -525,7 +821,7 @@ def load_qwen35_text_prompt_enhancer(assets_dir = _resolve_qwen35_assets_dir(assets_dir, variant=variant)spec = get_qwen35_variant_spec(variant)- text_assets_dir = get_qwen35_text_assets_dir(assets_dir, variant=variant)+ text_assets_dir = assets_dirtokenizer_json = _resolve_qwen35_asset_file(assets_dir, "tokenizer.json", variant=variant, error_if_none=False) or os.path.join(assets_dir, "tokenizer.json")tokenizer_config = _resolve_qwen35_asset_file(assets_dir, "tokenizer_config.json", variant=variant, error_if_none=False) or os.path.join(assets_dir, "tokenizer_config.json")text_config_path = _resolve_qwen35_asset_file(text_assets_dir, "config.json", error_if_none=False) or os.path.join(text_assets_dir, "config.json")@@ -541,11 +837,15 @@ def load_qwen35_text_prompt_enhancer(if backend == enhancer_quantization_GGUF:model_path = _resolve_gguf_model_path(model_path, assets_dir, variant=variant)+ gguf_v_head_reordered, gguf_ssm_param_reordered, gguf_interleave_ssm_ab = _resolve_gguf_linear_attention_layout_from_filename(model_path)preprocess_sd = _build_qwen35_gguf_preprocess_sd(tie_output_to_embeddings=bool(spec.get("tie_word_embeddings", False)),)runtime_model_path = text_assets_direlse:+ gguf_v_head_reordered = False+ gguf_ssm_param_reordered = False+ gguf_interleave_ssm_ab = Falseif model_path is None:model_path = get_qwen35_text_quanto_int8_path(assets_dir, variant=variant)preprocess_sd = None@@ -560,6 +860,7 @@ def load_qwen35_text_prompt_enhancer(if not os.path.isfile(model_path):raise FileNotFoundError(f"Qwen3.5 text checkpoint not found: {model_path}")+ print(f"[Prompt Enhancer][{spec['display_name']}][{backend}] Loading text checkpoint: {model_path}")model = _load_local_text_model(model_path,@@ -567,16 +868,31 @@ def load_qwen35_text_prompt_enhancer(preprocess_sd=preprocess_sd,default_dtype=default_dtype,safe_legacy_mode=safe_legacy_mode,+ materialize_source_tensors=backend != enhancer_quantization_GGUF,)if backend == enhancer_quantization_GGUF:- _configure_qwen35_gguf_text_model(model, default_dtype)+ _configure_qwen35_gguf_text_model(+ model,+ default_dtype,+ v_head_reordered=gguf_v_head_reordered,+ ssm_param_reordered=gguf_ssm_param_reordered,+ interleave_ssm_ab=gguf_interleave_ssm_ab,+ )+ _apply_qwen35_gguf_projection_fusions(model)model._prompt_enhancer_tokenizer = tokenizer+ model._prompt_enhancer_gguf_v_head_reordered = bool(gguf_v_head_reordered)+ model._prompt_enhancer_gguf_ssm_param_reordered = bool(gguf_ssm_param_reordered)+ model._prompt_enhancer_thinking_extra_tokens = QWEN35_PROMPT_THINKING_EXTRA_TOKENS+ model._prompt_enhancer_thinking_max_tokens = QWEN35_PROMPT_THINKING_MAX_TOKENS+ model._prompt_enhancer_close_think_token_id = tokenizer.convert_tokens_to_ids("</think>")model._prompt_enhancer_stop_token_ids = _collect_stop_token_ids(tokenizer, model.config)- model._prompt_enhancer_suppress_token_ids = _collect_suppressed_token_ids(tokenizer)+ set_qwen35_prompt_enhancer_thinking(model, QWEN35_PROMPT_ENABLE_THINKING)model._prompt_enhancer_suppress_logits_bias = None+ model._prompt_enhancer_suppress_logits_bias_cache = {}model._prompt_enhancer_default_top_k = QWEN35_PROMPT_DEFAULT_TOP_K- model._prompt_enhancer_enable_presence_penalty = QWEN35_PROMPT_ENABLE_PRESENCE_PENALTY+ model._prompt_enhancer_default_min_p = QWEN35_PROMPT_DEFAULT_MIN_P_GGUF if backend == enhancer_quantization_GGUF else None+ model._prompt_enhancer_enable_presence_penalty = backend != enhancer_quantization_GGUF and QWEN35_PROMPT_ENABLE_PRESENCE_PENALTYmodel._prompt_enhancer_presence_penalty = QWEN35_PROMPT_PRESENCE_PENALTYmodel._prompt_enhancer_min_new_tokens = (QWEN35_PROMPT_MIN_NEW_TOKENS@@ -611,4 +927,5 @@ __all__ = ["get_qwen35_text_quanto_int8_path","load_qwen35_prompt_enhancer","load_qwen35_text_prompt_enhancer",+ "set_qwen35_prompt_enhancer_thinking",]diff --git a/shared/prompt_enhancer/qwen35_vl.py b/shared/prompt_enhancer/qwen35_vl.pyindex 79d3fc1..41ce1cf 100644--- a/shared/prompt_enhancer/qwen35_vl.py+++ b/shared/prompt_enhancer/qwen35_vl.py@@ -27,8 +27,10 @@ enhancer_quantization_GGUF = "gguf"enhancer_quantization_SAFETENSORS = "safetensors"enhancer_quantization_QUANTO_INT8 = "quanto_int8"QWEN35_GGUF_LLAMACPP_ENV = "WGP_GGUF_LLAMACPP_CUDA"+QWEN35_TEXT_GGUF_FILENAME = "Qwen3.5-9B-abliterated-Q4_K_M_bis.gguf"QWEN35_TEXT_GGUF_FILENAME = "Qwen3.5-9B-Abliterated-text-Q4_K_M.gguf"QWEN35_TEXT_INT8_FILENAME = "Qwen3.5-9B-Abliterated_quanto_bf16_int8.safetensors"+# QWEN35_TEXT_INT8_FILENAME = "Qwen3.5-9B-Abliterated_bf16.safetensors"QWEN35_VISION_FILENAME = "Qwen3.5-9B-vision_bf16.safetensors"QWEN35_PROMPT_MIN_NEW_TOKENS = 4QWEN35_ABLITERATED_REPO = "DeepBeepMeep/Wan2.1"@@ -135,14 +137,31 @@ def _resolve_qwen35_asset_file(variant: str | None = None,error_if_none: bool = True,) -> str | None:- resolved_assets_dir = _resolve_qwen35_assets_dir(assets_dir, variant=variant, error_if_none=error_if_none)- if resolved_assets_dir is None:+ del variant+ if assets_dir is None:return None- path = os.path.join(resolved_assets_dir, filename)- located = fl.locate_file(path, error_if_none=False)- if located is None and error_if_none:+ path = os.path.join(assets_dir, filename)+ if not os.path.isfile(path) and error_if_none:raise FileNotFoundError(f"Missing Qwen3.5 asset: {path}")- return located+ return path if os.path.isfile(path) else None+++def _resolve_qwen35_checkpoint_file(+ assets_dir: str | None,+ filename: str,+ variant: str | None = None,+ error_if_none: bool = True,+) -> str | None:+ del variant+ if assets_dir is None:+ return None+ resolved = fl.locate_file(filename, error_if_none=False, extra_paths=[assets_dir])+ if resolved is not None:+ return resolved+ fallback_path = os.path.join(assets_dir, filename)+ if error_if_none:+ raise FileNotFoundError(f"Missing Qwen3.5 checkpoint: {fallback_path}")+ return fallback_pathdef get_qwen35_modeling_path() -> str:@@ -163,7 +182,6 @@ def ensure_qwen35_prompt_enhancer_assets(process_files_def, backend: str = enhandef _load_qwen35_tokenizer(assets_dir: str):- assets_dir = _resolve_qwen35_assets_dir(assets_dir)tokenizer_config_path = _resolve_qwen35_asset_file(assets_dir, "tokenizer_config.json")tokenizer_class = Nonetokenizer_config = {}@@ -205,7 +223,6 @@ def _load_qwen35_tokenizer(assets_dir: str):def _load_qwen35_chat_template(assets_dir: str) -> str | None:- assets_dir = _resolve_qwen35_assets_dir(assets_dir)chat_template_path = _resolve_qwen35_asset_file(assets_dir, "chat_template.jinja", error_if_none=False)if chat_template_path is None or not os.path.isfile(chat_template_path):return None@@ -214,7 +231,6 @@ def _load_qwen35_chat_template(assets_dir: str) -> str | None:def _load_qwen35_image_processor(assets_dir: str):- assets_dir = _resolve_qwen35_assets_dir(assets_dir)preprocessor_config_path = _resolve_qwen35_asset_file(assets_dir, "preprocessor_config.json", error_if_none=False)if preprocessor_config_path is not None:return Qwen2VLImageProcessorFast.from_pretrained(assets_dir)@@ -229,9 +245,8 @@ def _load_qwen35_image_processor(assets_dir: str):def get_qwen35_text_gguf_path(assets_dir: str, variant: str | None = None) -> str:- assets_dir = _resolve_qwen35_assets_dir(assets_dir, variant=variant)filename = get_qwen35_variant_spec(variant)["text_gguf_filename"]- return _resolve_qwen35_asset_file(assets_dir, filename, variant=variant, error_if_none=False) or os.path.join(assets_dir, filename)+ return _resolve_qwen35_checkpoint_file(assets_dir, filename, variant=variant, error_if_none=False)def _build_qwen35_vl_gguf_preprocess_sd(patch_shape):def preprocess_sd(sd, quant_map=None, tied_map=None):new_sd = OrderedDict()@@ -700,13 +715,6 @@ def _generate_image_captions_vllm(self, images):engine._ensure_llm()if engine._llm is None:raise RuntimeError("Qwen3.5 caption vLLM runtime is not available.")- engine.release_runtime_allocations()- qwen35_text_mod._reset_vllm_sequence_state(text_model)- engine._llm.model_runner.ensure_runtime_ready()- try:- engine._llm.reset()- except Exception:- passtemp, normalized_top_p, normalized_top_k = qwen35_text_mod._normalize_vllm_sampling(do_sample=False,temperature=None,@@ -724,7 +732,7 @@ def _generate_image_captions_vllm(self, images):cfg_scale=1.0,seed=None,use_tqdm=True,- release_vram_after=True,+ release_vram_after=False,ignore_eos=False,position_offset=position_offset,)@@ -789,9 +797,8 @@ def _unload_prompt_enhancer_vl_runtime(self):def get_qwen35_vision_path(assets_dir: str, variant: str | None = None) -> str:- assets_dir = _resolve_qwen35_assets_dir(assets_dir, variant=variant)filename = get_qwen35_variant_spec(variant)["vision_filename"]- return _resolve_qwen35_asset_file(assets_dir, filename, variant=variant, error_if_none=False) or os.path.join(assets_dir, filename)+ return _resolve_qwen35_checkpoint_file(assets_dir, filename, variant=variant, error_if_none=False)def load_qwen35_vl_prompt_enhancer(diff --git a/wgp.py b/wgp.pyindex b00377c..4a2ac34 100644--- a/wgp.py+++ b/wgp.py@@ -98,7 +98,7 @@ AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAMECONFIG_FILENAME = "wgp_config.json"PROMPT_VARS_MAX = 10target_mmgp_version = "3.7.6"-WanGP_version = "10.987"+WanGP_version = "10.9871"settings_version = 2.55max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -5467,6 +5467,7 @@ def process_prompt_enhancer(model_def, prompt_enhancer, original_prompts, imagetop_p = enhancer_top_p,seed = enhancer_seed,post_image_caption_hook = post_image_caption_hook,+ thinking_enabled = "K" in prompt_enhancer_mode,)return prompts@@ -8972,6 +8973,20 @@ def del_in_sequence(source_str, letters):ret = ret.replace(letter, "")return ret+def get_prompt_enhancer_letters_filter(prompt_enhancer_def, prompt_enhancer_choices):+ if isinstance(prompt_enhancer_def, dict):+ letters_filter = prompt_enhancer_def.get("letters_filter", "")+ if len(letters_filter): return letters_filter+ letters_filter = ""+ for _label, value in prompt_enhancer_choices:+ letters_filter = add_to_sequence(letters_filter, str(value or ""))+ return letters_filter++def build_prompt_enhancer_value(prompt_enhancer_mode, prompt_enhancer_think):+ if prompt_enhancer_think and len(prompt_enhancer_mode):+ prompt_enhancer_mode = add_to_sequence(prompt_enhancer_mode, "K")+ return prompt_enhancer_mode+def refresh_audio_prompt_type_remux(state, audio_prompt_type, remux):audio_prompt_type = del_in_sequence(audio_prompt_type, "R")audio_prompt_type = add_to_sequence(audio_prompt_type, remux)@@ -10087,9 +10102,9 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonwizard_variables_var = gr.Text(wizard_variables, visible = False)with gr.Row(visible= server_config.get("enhancer_enabled", 0) > 0 ) as prompt_enhancer_row:on_demand_prompt_enhancer = server_config.get("enhancer_mode", 0) == 1- prompt_enhancer_value = ui_get("prompt_enhancer")+ prompt_enhancer_value = str(ui_get("prompt_enhancer") or "")prompt_enhancer_btn_label = str(model_def.get("prompt_enhancer_button_label", "Enhance Prompt"))- prompt_enhancer_btn = gr.Button( value =prompt_enhancer_btn_label, visible= on_demand_prompt_enhancer, size="lg", elem_classes="btn_centered")+ prompt_enhancer_btn = gr.Button( value =prompt_enhancer_btn_label, visible= on_demand_prompt_enhancer, size="lg", scale=1, elem_classes="btn_centered")prompt_enhancer_choices = [] if on_demand_prompt_enhancer else [("Disabled", "")]prompt_enhancer_default = ""prompt_enhancer_default_labels = {@@ -10127,26 +10142,34 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nondisplay_label = prompt_enhancer_default_labels.get(selection_value, selection_value)prompt_enhancer_choices.append((display_label, selection_value))+ prompt_enhancer_letters_filter = get_prompt_enhancer_letters_filter(prompt_enhancer_def, prompt_enhancer_choices)prompt_enhancer_values = [value for _, value in prompt_enhancer_choices]- if prompt_enhancer_value not in prompt_enhancer_values:+ prompt_enhancer_mode_value = filter_letters(prompt_enhancer_value, prompt_enhancer_letters_filter, prompt_enhancer_default)+ prompt_enhancer_mode_value = get_default_value(prompt_enhancer_choices, prompt_enhancer_mode_value, prompt_enhancer_default)+ if prompt_enhancer_mode_value not in prompt_enhancer_values:if prompt_enhancer_default in prompt_enhancer_values:- prompt_enhancer_value = prompt_enhancer_default+ prompt_enhancer_mode_value = prompt_enhancer_defaultelif len(prompt_enhancer_values) > 0:- prompt_enhancer_value = prompt_enhancer_values[0]+ prompt_enhancer_mode_value = prompt_enhancer_values[0]else:- prompt_enhancer_value = ""- elif len(prompt_enhancer_value) == 0 and on_demand_prompt_enhancer and len(prompt_enhancer_values) > 0:+ prompt_enhancer_mode_value = ""+ elif len(prompt_enhancer_mode_value) == 0 and on_demand_prompt_enhancer and len(prompt_enhancer_values) > 0:if prompt_enhancer_default in prompt_enhancer_values:- prompt_enhancer_value = prompt_enhancer_default+ prompt_enhancer_mode_value = prompt_enhancer_defaultelse:- prompt_enhancer_value = prompt_enhancer_values[0]+ prompt_enhancer_mode_value = prompt_enhancer_values[0]- prompt_enhancer = gr.Dropdown(+ prompt_enhancer_think_visible = server_config.get("enhancer_enabled", 0) in (3, 4)+ prompt_enhancer_think_value = prompt_enhancer_think_visible and "K" in prompt_enhancer_value and len(prompt_enhancer_mode_value) > 0+ prompt_enhancer_value = build_prompt_enhancer_value(prompt_enhancer_mode_value, prompt_enhancer_think_value)+ prompt_enhancer = gr.Text(value=prompt_enhancer_value, visible=False)+ prompt_enhancer_mode_dropdown = gr.Dropdown(choices=prompt_enhancer_choices,- value=prompt_enhancer_value,+ value=prompt_enhancer_mode_value,label=model_def.get("prompt_enhancer_button_label", "Enhance Prompt using a LLM") , scale = 5,visible= True, show_label= not on_demand_prompt_enhancer,)+ prompt_enhancer_think = gr.Checkbox(label="Think", value=prompt_enhancer_think_value, visible=prompt_enhancer_think_visible, scale=1, elem_classes="cbx_centered")alt_prompt_def = model_def.get("alt_prompt", None)alt_prompt_label = Nonealt_prompt_placeholder = ""@@ -10888,7 +10911,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonvideo_buttons_row, deleted_video_buttons_row, image_buttons_row, video_postprocessing_tab, audio_remuxing_tab, PP_MMAudio_col, PP_MMAudio_setting, PP_MMAudio_row, PP_custom_audio_row,audio_buttons_row, deleted_audio_buttons_row, video_info_extract_audio_settings_btn, video_info_to_audio_guide_btn, video_info_to_audio_guide2_btn, video_info_to_audio_source_btn, video_info_eject_audio_btn,video_info_to_start_image_btn, video_info_to_end_image_btn, video_info_to_reference_image_btn, video_info_to_image_guide_btn, video_info_to_image_mask_btn,- NAG_col, audio_options_row, remove_background_sound, normalize_audio_volumes, speakers_locations_row, embedded_guidance_row, guidance_phases_row, guidance_row, resolution_group, cfg_free_guidance_col, control_net_weights_row, guide_selection_row, image_mode_tabs,+ NAG_col, audio_options_row, remove_background_sound, normalize_audio_volumes, speakers_locations_row, embedded_guidance_row, guidance_phases_row, guidance_row, resolution_group, cfg_free_guidance_col, control_net_weights_row, guide_selection_row, image_mode_tabs, prompt_enhancer_mode_dropdown, prompt_enhancer_think,min_frames_if_references_col, motion_amplitude_col, video_prompt_type_alignment, prompt_enhancer_btn, tab_inpaint, tab_t2v, resolution_row, loras_tab, post_processing_tab, temperature_row, *custom_settings_rows, top_pk_row,number_frames_row, negative_prompt_row,self_refiner_col, pause_row]+\@@ -10916,6 +10939,8 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonremove_background_sound.change(fn=refresh_remove_background_sound, inputs=[state, audio_prompt_type, remove_background_sound], outputs=[audio_prompt_type])normalize_audio_volumes.change(fn=refresh_normalize_audio_volumes, inputs=[state, audio_prompt_type, normalize_audio_volumes], outputs=[audio_prompt_type])audio_prompt_type_sources.change(fn=refresh_audio_prompt_type_sources, inputs=[state, audio_prompt_type, audio_prompt_type_sources], outputs=[audio_prompt_type, audio_guide, audio_guide2, speakers_locations_row, remove_background_sound, normalize_audio_volumes, audio_options_row, audio_guide_row])+ prompt_enhancer_mode_dropdown.input(fn=build_prompt_enhancer_value, inputs=[prompt_enhancer_mode_dropdown, prompt_enhancer_think], outputs=[prompt_enhancer], show_progress="hidden")+ prompt_enhancer_think.input(fn=build_prompt_enhancer_value, inputs=[prompt_enhancer_mode_dropdown, prompt_enhancer_think], outputs=[prompt_enhancer], show_progress="hidden")image_prompt_type_radio.change(fn=refresh_image_prompt_type_radio, inputs=[state, image_prompt_type, image_prompt_type_radio], outputs=[image_prompt_type, image_start_row, image_end_row, video_source, input_video_strength, keep_frames_video_source, image_prompt_type_endcheckbox], show_progress="hidden" )image_prompt_type_endcheckbox.change(fn=refresh_image_prompt_type_endcheckbox, inputs=[state, image_prompt_type, image_prompt_type_radio, image_prompt_type_endcheckbox], outputs=[image_prompt_type, image_end_row] )video_prompt_type_image_refs.input(fn=refresh_video_prompt_type_image_refs, inputs = [state, video_prompt_type, video_prompt_type_image_refs,image_mode], outputs = [video_prompt_type, image_refs_row, remove_background_images_ref, image_refs_relative_size, frames_positions,video_guide_outpainting_col], show_progress="hidden")