Download code/te_ops.py from aqualaguna/MOSS-Image-Edit-OpenVINO: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/aqualaguna/MOSS-Image-Edit-OpenVINO/resolve/main/code/te_ops.py
- Command line
-
hf download hf://aqualaguna/MOSS-Image-Edit-OpenVINO/code/te_ops.py
-
curl -L -o te_ops.py https://huggingface.co/aqualaguna/MOSS-Image-Edit-OpenVINO/resolve/main/code/te_ops.py
10 kB
| """OpenVINO-convertible Qwen3.5 (Gated DeltaNet) decoder layers, no KV/recurrent cache (prefill only). | |
| The GatedDeltaNet recurrence and its OpenVINO conversion rule are taken from huggingface/optimum-intel | |
| (optimum/exporters/openvino/model_patcher.py `patched_recurrent_gated_delta_rule`, `RecurrentAttentionCell`, | |
| `qwen3_5_gated_delta_net_forward`; optimum/exporters/openvino/_ov_ops.py `convert_recurrent_attention_cell`), | |
| Apache-2.0, (c) The HuggingFace Team. Adapted here to run without optimum so that the text encoder of | |
| MOSS-Image (a stock Qwen3.5-9B language model) can be exported as plain no-cache IRs that return the final | |
| hidden state. | |
| """ | |
| import types | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| class RecurrentAttentionCell(torch.nn.Module): | |
| """Placeholder module, replaced in the OV graph by `convert_recurrent_attention_cell` (an ov::Loop).""" | |
| def forward(self, query, key, value, g, beta, last_recurrent_state): | |
| _, _, sequence_length, _ = key.shape | |
| core_attn_out = torch.zeros_like(value) | |
| for i in range(sequence_length): | |
| q_t = query[:, :, i] | |
| k_t = key[:, :, i] | |
| v_t = value[:, :, i] | |
| g_t = g[:, :, i].exp().unsqueeze(-1).unsqueeze(-1) | |
| beta_t = beta[:, :, i].unsqueeze(-1) | |
| last_recurrent_state = last_recurrent_state * g_t | |
| kv_mem = (last_recurrent_state * k_t.unsqueeze(-1)).sum(dim=-2) | |
| delta = (v_t - kv_mem) * beta_t | |
| last_recurrent_state = last_recurrent_state + k_t.unsqueeze(-1) * delta.unsqueeze(-2) | |
| core_attn_out[:, :, i] = (last_recurrent_state * q_t.unsqueeze(-1)).sum(dim=-2) | |
| return torch.cat([core_attn_out.flatten(), last_recurrent_state.flatten()], dim=0) | |
| def convert_recurrent_attention_cell(context): | |
| import openvino as ov | |
| import openvino.opset14 as ops | |
| query = context.get_input(0) | |
| key = context.get_input(1) | |
| value = context.get_input(2) | |
| g = context.get_input(3) | |
| beta = context.get_input(4) | |
| last_recurrent_state_old = context.get_input(5) | |
| value_shape = ops.shape_of(value) | |
| const_zero = ops.constant(0, dtype=np.float32) | |
| core_attn_out = ops.broadcast(const_zero, value_shape) | |
| const_two_out = ops.constant(2, dtype=np.int32) | |
| const_zero_out = ops.constant(0, dtype=np.int32) | |
| seq_len = ops.gather(value_shape, const_two_out, const_zero_out) | |
| timestep_param = ops.parameter([], np.int32, "timestep") | |
| q_t_param = ops.parameter([-1, -1, 1, -1], np.float32, "q_t") | |
| k_t_param = ops.parameter([-1, -1, 1, -1], np.float32, "k_t") | |
| v_t_param = ops.parameter([-1, -1, 1, -1], np.float32, "v_t") | |
| g_t_param = ops.parameter([-1, -1, 1], np.float32, "g_t") | |
| beta_t_param = ops.parameter([-1, -1, 1], np.float32, "beta_t") | |
| last_recurrent_state_t = ops.parameter([-1, -1, -1, -1], np.float32, "last_recurrent_state_t") | |
| core_attn_out_t = ops.parameter([-1, -1, -1, -1], np.float32, "core_attn_out_t") | |
| const_two = ops.constant(2, dtype=np.int32) | |
| q_t = ops.squeeze(q_t_param, const_two) | |
| k_t = ops.squeeze(k_t_param, const_two) | |
| v_t = ops.squeeze(v_t_param, const_two) | |
| const_minus_one = ops.constant(-1, dtype=np.int32) | |
| g_t = ops.unsqueeze(ops.exp(g_t_param), const_minus_one) | |
| beta_t = beta_t_param | |
| last_recurrent_state_in = ops.multiply(last_recurrent_state_t, g_t) | |
| const_minus_two = ops.constant(-2, dtype=np.int32) | |
| kv_mem = ops.multiply(last_recurrent_state_in, ops.unsqueeze(k_t, const_minus_one)) | |
| kv_mem = ops.reduce_sum(kv_mem, const_minus_two, False) | |
| delta = ops.multiply(ops.subtract(v_t, kv_mem), beta_t) | |
| last_recurrent_state_delta = ops.multiply( | |
| ops.unsqueeze(k_t, const_minus_one), ops.unsqueeze(delta, const_minus_two) | |
| ) | |
| last_recurrent_state_in = ops.add(last_recurrent_state_in, last_recurrent_state_delta) | |
| core_attn_update = ops.multiply(last_recurrent_state_in, ops.unsqueeze(q_t, const_minus_one)) | |
| core_attn_update = ops.reduce_sum(core_attn_update, const_minus_two, True) | |
| const_zero = ops.constant(0, dtype=np.int32) | |
| timestep = ops.unsqueeze(timestep_param, const_zero) | |
| core_attn_out_res = ops.scatter_update(core_attn_out_t, timestep, core_attn_update, const_two) | |
| last_recurrent_state_res = last_recurrent_state_in | |
| body_cond = ops.constant([True], dtype=bool) | |
| body_model = ov.Model( | |
| [body_cond, last_recurrent_state_res, core_attn_out_res], | |
| [timestep_param, q_t_param, k_t_param, v_t_param, g_t_param, beta_t_param, last_recurrent_state_t, core_attn_out_t], | |
| "body_model", | |
| ) | |
| seq_len = ops.convert(seq_len, "i32") | |
| loop = ops.loop(seq_len, ops.constant(True, dtype="bool")) | |
| loop.set_function(body_model) | |
| loop.set_sliced_input(q_t_param, query, 0, 1, 1, -1, 2) | |
| loop.set_sliced_input(k_t_param, key, 0, 1, 1, -1, 2) | |
| loop.set_sliced_input(v_t_param, value, 0, 1, 1, -1, 2) | |
| loop.set_sliced_input(g_t_param, g, 0, 1, 1, -1, 2) | |
| loop.set_sliced_input(beta_t_param, beta, 0, 1, 1, -1, 2) | |
| loop.set_merged_input(last_recurrent_state_t, last_recurrent_state_old, last_recurrent_state_res.output(0)) | |
| loop.set_merged_input(core_attn_out_t, core_attn_out.output(0), core_attn_out_res.output(0)) | |
| loop.set_special_body_ports([0, 0]) | |
| core_attn_out_new = loop.get_iter_value(core_attn_out_res.output(0), -1) | |
| last_recurrent_state_new = loop.get_iter_value(last_recurrent_state_res.output(0), -1) | |
| flatten_shape = ops.constant([-1], dtype=np.int32) | |
| core_attn_out_new = ops.reshape(core_attn_out_new, flatten_shape, False) | |
| last_recurrent_state_new = ops.reshape(last_recurrent_state_new, flatten_shape, False) | |
| final_output = ops.concat([core_attn_out_new, last_recurrent_state_new], 0) | |
| return [final_output.output(0)] | |
| def patched_recurrent_gated_delta_rule(self, query, key, value, g, beta, initial_state, output_final_state, use_qk_l2norm_in_kernel=False): | |
| def l2norm(x, dim=-1, eps=1e-6): | |
| inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps) | |
| return x * inv_norm | |
| initial_dtype = query.dtype | |
| if use_qk_l2norm_in_kernel: | |
| query = l2norm(query, dim=-1, eps=1e-6) | |
| key = l2norm(key, dim=-1, eps=1e-6) | |
| query, key, value, beta, g = [x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)] | |
| batch_size, num_heads, sequence_length, k_head_dim = key.shape | |
| v_head_dim = value.shape[-1] | |
| scale = 1 / (query.shape[-1] ** 0.5) | |
| query = query * scale | |
| last_recurrent_state = ( | |
| torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim).to(value) if initial_state is None else initial_state.to(value) | |
| ) | |
| output_cell = self.recurrent_attention_cell(query, key, value, g, beta, last_recurrent_state) | |
| num_elems = value.numel() | |
| core_attn_out = output_cell[:num_elems].reshape(value.shape) | |
| last_recurrent_state = output_cell[num_elems:].reshape(last_recurrent_state.shape) | |
| if not output_final_state: | |
| last_recurrent_state = None | |
| core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype) | |
| return core_attn_out, last_recurrent_state | |
| def gated_delta_net_forward_nocache(self, hidden_states, cache_params=None, attention_mask=None, **kwargs): | |
| """Qwen3_5GatedDeltaNet.forward without cache; recurrence via the OV-convertible cell.""" | |
| batch_size, seq_len, _ = hidden_states.shape | |
| mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2) | |
| z = self.in_proj_z(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim) | |
| b = self.in_proj_b(hidden_states) | |
| a = self.in_proj_a(hidden_states) | |
| mixed_qkv = F.silu(self.conv1d(mixed_qkv)[:, :, :seq_len]) | |
| mixed_qkv = mixed_qkv.transpose(1, 2) | |
| query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1) | |
| query = query.reshape(query.shape[0], query.shape[1], -1, self.head_k_dim) | |
| key = key.reshape(key.shape[0], key.shape[1], -1, self.head_k_dim) | |
| value = value.reshape(value.shape[0], value.shape[1], -1, self.head_v_dim) | |
| beta = b.sigmoid() | |
| g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias) | |
| if self.num_v_heads // self.num_k_heads > 1: | |
| query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2) | |
| key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2) | |
| core_attn_out, _ = self.recurrent_gated_delta_rule( | |
| self, query, key, value, g=g, beta=beta, initial_state=None, output_final_state=False, use_qk_l2norm_in_kernel=True | |
| ) | |
| core_attn_out = core_attn_out.reshape(-1, self.head_v_dim) | |
| z = z.reshape(-1, self.head_v_dim) | |
| core_attn_out = self.norm(core_attn_out, z) | |
| core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1) | |
| return self.out_proj(core_attn_out) | |
| def patch_linear_attn(layer): | |
| la = layer.linear_attn | |
| la.forward = types.MethodType(gated_delta_net_forward_nocache, la) | |
| la.recurrent_gated_delta_rule = patched_recurrent_gated_delta_rule | |
| la.recurrent_attention_cell = RecurrentAttentionCell() | |
| class TEPart(torch.nn.Module): | |
| """A run of decoder layers (+ optional final norm): (hidden, cos, sin) -> hidden. No cache, causal, batch 1. | |
| Inputs/outputs are float32 at the IR boundary; the layers run in `dtype`.""" | |
| def __init__(self, layers, norm=None, dtype=torch.float32, cast_io=False): | |
| super().__init__() | |
| self.layers = torch.nn.ModuleList(layers) | |
| self.norm = norm | |
| self.dtype = dtype | |
| self.cast_io = cast_io | |
| def forward(self, hidden, cos, sin): | |
| if self.cast_io: | |
| hidden, cos, sin = hidden.to(self.dtype), cos.to(self.dtype), sin.to(self.dtype) | |
| for layer in self.layers: | |
| hidden = layer(hidden, position_embeddings=(cos, sin), attention_mask=None, position_ids=None, past_key_values=None) | |
| if self.norm is not None: | |
| hidden = self.norm(hidden) | |
| return hidden.float() if self.cast_io else hidden | |