Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / attention / gated_delta_net / gated_delta_net.py: 79%

172 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""Local Gated DeltaNet training with reversible grouped QKV and convolution rows.""" 

16from __future__ import annotations 

17 

18from copy import deepcopy 

19from typing import Any 

20 

21import torch 

22from torch import nn 

23from torch.nn import functional as F 

24 

25from hyper_parallel.components.checkpoint import InterleaveQKV 

26from hyper_parallel.components.checkpoint.weight_conversion import WeightConverter 

27from hyper_parallel.components.functional.gated_delta_net import chunk_gated_delta_rule 

28from hyper_parallel.components.functional.linear_attention_convolution import ( 

29 validate_causal_convolution, 

30 run_causal_short_conv, validate_conv_backend, 

31) 

32from hyper_parallel.components.modules.attention.linear_attention_utils.layer_adapter import ( 

33 adopt_source_parameters, copy_unbound_linear_attention, prepare_linear_attention_input, 

34) 

35from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import PackedSequenceInfo 

36 

37 

38class GatedDeltaNetRMSNorm(nn.Module): 

39 """Qwen-style per-head RMSNorm followed by SiLU, retaining its rounding order.""" 

40 

41 def __init__(self, width: int, eps: float = 1e-6) -> None: 

42 """Create a direct-scale normalization weight.""" 

43 super().__init__() 

44 self.weight = nn.Parameter(torch.ones(width)) 

45 self.variance_epsilon = eps 

46 

47 def forward(self, hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: 

48 """Normalize in FP32, round, scale and then apply the FP32 output gate. 

49 

50 Args: 

51 hidden_states: Attention output with per-head channels in the last dimension. 

52 gate: Output-gate logits applied after RMS normalization. 

53 """ 

54 dtype = hidden_states.dtype 

55 hidden_states = hidden_states.float() 

56 variance = hidden_states.pow(2).mean(-1, keepdim=True) 

57 hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) 

58 hidden_states = self.weight * hidden_states.to(dtype) 

59 return (hidden_states * F.silu(gate.float())).to(dtype) 

60 

61 

62class GatedDeltaNetModule(nn.Module): 

63 """Local GDN projections, convolution, GVA, gates, recurrence and output.""" 

64 

65 def __init__(self, *, config: Any = None, module: nn.Module | None = None, 

66 backend: str = "eager", conv_backend: str | None = None, 

67 chunk_size: int = 64, input_layout: str = "BSH") -> None: 

68 """Construct local parameters or convert source QKV rows, retaining checkpoint names.""" 

69 super().__init__() 

70 if (config is None) == (module is None): 

71 raise ValueError("GDN requires exactly one of config or module") 

72 self.config = config if module is None else getattr(module, "config", None) 

73 self.backend = backend 

74 self.conv_backend = validate_conv_backend(backend if conv_backend is None else conv_backend) 

75 self.chunk_size, self.input_layout = chunk_size, input_layout 

76 self._config_initialization = module is None or getattr(module, "_config_initialization", False) 

77 if module is None: 

78 self._initialize_parameters(config) 

79 else: 

80 self._adopt_source(module) 

81 validate_causal_convolution(self.conv1d) 

82 if self.num_v_heads % self.num_k_heads: 

83 raise ValueError("GDN value heads must be divisible by query heads") 

84 self._configure_qkv_layout(module) 

85 if self.backend not in ("eager", "triton", "ascendc"): 

86 raise ValueError("GDN backend must be eager, triton or ascendc") 

87 if self.backend != "eager" and (self.head_k_dim != 128 or self.head_v_dim != 128 or chunk_size != 64): 

88 raise ValueError("Fused GDN requires K=V=128 and chunk_size=64") 

89 if self.activation not in ("silu", "swish"): 

90 raise NotImplementedError("GDN family implements SiLU/Swish convolution") 

91 

92 def __deepcopy__(self, memo: dict) -> nn.Module: 

93 """Retain pre-binding model-copy behavior without copying process groups.""" 

94 return copy_unbound_linear_attention(self, memo) 

95 

96 def _initialize_parameters(self, config: Any) -> None: 

97 """Create source-compatible projections, gates, convolution and output norm.""" 

98 self.hidden_size = config.hidden_size 

99 self.num_k_heads = config.linear_num_key_heads 

100 self.num_v_heads = config.linear_num_value_heads 

101 self.head_k_dim = config.linear_key_head_dim 

102 self.head_v_dim = config.linear_value_head_dim 

103 self.key_dim = self.num_k_heads * self.head_k_dim 

104 self.value_dim = self.num_v_heads * self.head_v_dim 

105 self.conv_dim = 2 * self.key_dim + self.value_dim 

106 self.conv_kernel_size = getattr(config, "linear_conv_kernel_dim", 4) 

107 self.activation = getattr(config, "hidden_act", "silu") 

108 self.layer_idx = getattr(config, "layer_idx", 0) 

109 self.in_proj_qkv = nn.Linear(self.hidden_size, self.conv_dim, bias=False) 

110 self.in_proj_z = nn.Linear(self.hidden_size, self.value_dim, bias=False) 

111 self.in_proj_b = nn.Linear(self.hidden_size, self.num_v_heads, bias=False) 

112 self.in_proj_a = nn.Linear(self.hidden_size, self.num_v_heads, bias=False) 

113 self.conv1d = nn.Conv1d(self.conv_dim, self.conv_dim, self.conv_kernel_size, 

114 padding=self.conv_kernel_size - 1, groups=self.conv_dim, bias=False) 

115 self.dt_bias = nn.Parameter(torch.ones(self.num_v_heads)) 

116 # A_log is the source model checkpoint key. 

117 self.A_log = nn.Parameter(torch.empty(self.num_v_heads).uniform_(0, 16).log()) # pylint: disable=invalid-name 

118 self.norm = GatedDeltaNetRMSNorm(self.head_v_dim, getattr(config, "rms_norm_eps", 1e-6)) 

119 self.out_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False) 

120 

121 def _adopt_source(self, module: nn.Module) -> None: 

122 """Adopt source parameters and dimensions without changing checkpoint keys.""" 

123 owners = ("in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a", "conv1d", "A_log", "dt_bias", 

124 "norm", "out_proj", "out_proj_input") 

125 dimensions = ("num_k_heads", "num_v_heads", "head_k_dim", "head_v_dim", "key_dim", "value_dim", "conv_dim") 

126 missing = [name for name in owners[:-1] + dimensions if not hasattr(module, name)] 

127 if missing: 

128 raise TypeError(f"GDN source is missing {missing}") 

129 adopt_source_parameters(self, module, owners) 

130 for name in dimensions: 

131 setattr(self, name, getattr(module, name)) 

132 self.hidden_size = self.in_proj_qkv.in_features 

133 self.layer_idx = getattr(module, "layer_idx", None) 

134 self.activation = getattr(module, "activation", "silu") 

135 self.conv_kernel_size = self.conv1d.kernel_size[0] 

136 

137 def _configure_qkv_layout(self, module: nn.Module | None) -> None: 

138 """Keep global conversion dimensions when a grouped local member becomes CP.""" 

139 self.num_value_groups = self.num_v_heads // self.num_k_heads 

140 self.qkv_group_width = 2 * self.head_k_dim + self.num_value_groups * self.head_v_dim 

141 self._source_qkv_heads = getattr(module, "_source_qkv_heads", self.num_k_heads) 

142 self._convert_source_qkv = module is not None and getattr(module, "_convert_source_qkv", True) 

143 if module is not None and not isinstance(module, GatedDeltaNetModule): 

144 self._group_source_parameters() 

145 

146 def _qkv_conversion(self) -> InterleaveQKV: 

147 """Group one Q/K head with all value heads sharing that key.""" 

148 return InterleaveQKV(self._source_qkv_heads, 1, self.head_k_dim, 

149 self.num_value_groups * self.head_v_dim, source_is_fused=True) 

150 

151 def _group_source_parameters(self) -> None: 

152 """Convert loaded source rows without mutating the original projection or convolution.""" 

153 conversion = self._qkv_conversion() 

154 for name in ("in_proj_qkv", "conv1d"): 

155 child = deepcopy(getattr(self, name)) 

156 for suffix in ("weight", "bias"): 

157 parameter = getattr(child, suffix, None) 

158 if parameter is not None: 

159 grouped = conversion.convert({suffix: parameter}, [suffix], [suffix])[suffix] 

160 with torch.no_grad(): 

161 parameter.copy_(grouped) 

162 setattr(self, name, child) 

163 

164 def make_transforms(self) -> list[WeightConverter]: 

165 """Declare reversible source-QKV and depthwise-convolution row conversion. 

166 

167 Returns: 

168 Source-checkpoint transforms; native construction already uses grouped rows. 

169 """ 

170 if not self._convert_source_qkv: 

171 return [] 

172 names = [f"{owner}.{suffix}" for owner in ("in_proj_qkv", "conv1d") 

173 for suffix in ("weight", "bias") if getattr(getattr(self, owner), suffix, None) is not None] 

174 return [WeightConverter(source_patterns=name, target_patterns=name, 

175 operations=[self._qkv_conversion()]) for name in names] 

176 

177 def reset_parameters(self) -> None: 

178 """Initialize direct/meta parameters without resetting converted sources.""" 

179 if not self._config_initialization: 

180 return 

181 for child in self.children(): 

182 if isinstance(child, (nn.Linear, nn.Conv1d)): 

183 child.reset_parameters() 

184 with torch.no_grad(): 

185 self.A_log.uniform_(0, 16).log_() 

186 self.dt_bias.fill_(1) 

187 self.norm.weight.fill_(1) 

188 

189 def project_inputs(self, hidden_states: torch.Tensor) -> tuple: 

190 """Keep output-gate tokens local while producing raw recurrence operands. 

191 

192 Args: 

193 hidden_states: Local hidden activations in BSH or flat TH layout. 

194 """ 

195 mixed_qkv = self.in_proj_qkv(hidden_states) 

196 gate = self.in_proj_z(hidden_states).reshape(*hidden_states.shape[:2], self.num_v_heads, self.head_v_dim) 

197 return (mixed_qkv, self.in_proj_b(hidden_states), self.in_proj_a(hidden_states)), gate 

198 

199 def prepare_core_inputs(self, mixed_qkv: torch.Tensor, beta_logits: torch.Tensor, 

200 decay_logits: torch.Tensor, degree: int = 1, 

201 a_log: torch.Tensor | None = None, dt_bias: torch.Tensor | None = None) -> tuple: 

202 """Apply GVA and source gate arithmetic after convolution/layout exchange. 

203 

204 Args: 

205 mixed_qkv: Packed query, key and value projection output. 

206 beta_logits: Raw delta-rule update logits. 

207 decay_logits: Raw decay projection output. 

208 degree: Number of ranks participating in the head/sequence exchange. 

209 a_log: Log decay-rate parameter. 

210 dt_bias: Per-key time-step bias. 

211 """ 

212 grouped = mixed_qkv.unflatten(-1, (self.num_k_heads // degree, self.qkv_group_width)) 

213 query, key, value = grouped.split((self.head_k_dim, self.head_k_dim, 

214 self.num_value_groups * self.head_v_dim), dim=-1) 

215 batch, tokens = mixed_qkv.shape[:2] 

216 query = query.reshape(batch, tokens, self.num_k_heads // degree, self.head_k_dim) 

217 key = key.reshape_as(query) 

218 value = value.reshape(batch, tokens, self.num_v_heads // degree, self.head_v_dim) 

219 a_log = self.A_log if a_log is None else a_log 

220 dt_bias = self.dt_bias if dt_bias is None else dt_bias 

221 beta = beta_logits.sigmoid() 

222 decay = -a_log.float().exp() * F.softplus(decay_logits.float() + dt_bias) 

223 groups = self.num_v_heads // self.num_k_heads 

224 if groups > 1 and self.backend != "ascendc": 

225 # The native GVA kernels index shared Q/K directly. Existing eager 

226 # and Triton state kernels still require matched head counts. 

227 query = query.repeat_interleave(groups, dim=2) 

228 key = key.repeat_interleave(groups, dim=2) 

229 return query, key, value, decay, beta 

230 

231 def run_local_core(self, operands: tuple, info: PackedSequenceInfo | None) -> torch.Tensor: 

232 """Call the explicit local backend with immutable document metadata. 

233 

234 Args: 

235 operands: Projected inputs consumed by this attention stage. 

236 info: Immutable packed-sequence metadata, or None for dense input. 

237 """ 

238 offsets = None 

239 if info is not None: 

240 offsets = (info.local_offsets if self.backend in ("eager", "ascendc") else 

241 info.materialize(operands[0].device, self.chunk_size).cu_seqlens) 

242 return chunk_gated_delta_rule(*operands, initial_state=None, output_final_state=False, 

243 chunk_size=self.chunk_size, use_qk_l2norm_in_kernel=True, 

244 backend=self.backend, cu_seqlens=offsets)[0] 

245 

246 def execute_attention_pipeline(self, operands: tuple, info: PackedSequenceInfo | None) -> torch.Tensor: 

247 """Execute the local convolution and state recurrence. 

248 

249 Args: 

250 operands: Projected inputs consumed by this attention stage. 

251 info: Immutable packed-sequence metadata, or None for dense input. 

252 """ 

253 mixed, beta, decay = operands 

254 mixed = run_causal_short_conv(mixed, self.conv1d, sequence_info=info, backend=self.conv_backend) 

255 return self.run_local_core(self.prepare_core_inputs(mixed, beta, decay), info) 

256 

257 def project_output(self, output: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: 

258 """Preserve the source norm and optional output-input adapter. 

259 

260 Args: 

261 output: Local attention output before its final projection. 

262 gate: Output-gate logits applied after normalization. 

263 """ 

264 batch, tokens = output.shape[:2] 

265 output = self.norm(output.reshape(-1, self.head_v_dim), gate.reshape(-1, self.head_v_dim)) 

266 output = output.reshape(batch, tokens, self.value_dim) 

267 if hasattr(self, "out_proj_input"): 

268 output = self.out_proj_input(output) 

269 return self.out_proj(output) 

270 

271 def prepare_input(self, hidden_states: torch.Tensor, options: dict) -> tuple: 

272 """Adapt local dense/flat input; CP members resolve their own token interval. 

273 

274 Args: 

275 hidden_states: Local dense or flat hidden activations. 

276 options: Explicit backend options or invocation document metadata. 

277 """ 

278 return prepare_linear_attention_input(hidden_states, options) 

279 

280 def forward(self, *args: Any, **kwargs: Any) -> torch.Tensor: 

281 """Accept the source model's decorated positional and keyword call contract. 

282 

283 Args: 

284 *args: Hidden states, optional cache and optional padding mask. 

285 **kwargs: Named inputs and per-invocation packed metadata. 

286 """ 

287 # HF's accelerate wrapper exposes only (*args, **kwargs). The typed 

288 # training implementation still rejects missing or extra arguments. 

289 return self._forward_training(*args, **kwargs) 

290 

291 def _forward_training(self, hidden_states: torch.Tensor, cache_params: Any = None, 

292 attention_mask: torch.Tensor | None = None, **kwargs: Any) -> torch.Tensor: 

293 """Run training GDN on dense or flat packed tokens. 

294 

295 Args: 

296 hidden_states: Local hidden activations in BSH or flat TH layout. 

297 cache_params: Inference cache; training-family execution requires None. 

298 attention_mask: Optional source-model mask; packed boundaries carry document resets. 

299 """ 

300 if cache_params is not None or kwargs.get("use_cache", False): 

301 raise NotImplementedError("GDN family supports training without recurrent cache") 

302 hidden_states, info, is_flat_input = self.prepare_input(hidden_states, kwargs) 

303 if attention_mask is not None: 

304 if attention_mask.ndim != 2 or tuple(attention_mask.shape) != tuple(hidden_states.shape[:2]): 

305 raise ValueError("GDN expects a local two-dimensional padding mask") 

306 hidden_states = hidden_states * attention_mask[:, :, None].to(hidden_states.dtype) 

307 operands, gate = self.project_inputs(hidden_states) 

308 del hidden_states 

309 output = self.execute_attention_pipeline(operands, info) 

310 del operands 

311 output = self.project_output(output, gate) 

312 return output.squeeze(0) if is_flat_input else output