Taykhoom commited on
Commit
fdea0b5
·
verified ·
1 Parent(s): dc3335d

Add opt-in Triton Hyena kernels from vortex PR #77 (@AlphaKhaw)

Browse files
Files changed (6) hide show
  1. README.md +2 -0
  2. configuration_evo2.py +8 -0
  3. engine.py +44 -3
  4. hyena.py +11 -2
  5. kernels.py +724 -0
  6. modeling_evo2.py +8 -0
README.md CHANGED
@@ -93,6 +93,8 @@ See the full Evo 2 collection on the [Arc Institute HF org](https://huggingface.
93
 
94
  > **Note on attention backend.** By HuggingFace convention this model defaults to `attn_implementation="sdpa"` (`F.scaled_dot_product_attention`) since SDPA needs only `torch` and runs on any GPU. The original Arc Institute Evo 2 inference path uses **flash_attention_2**, which is faster on long sequences but requires a separate `flash-attn` install. All usage examples below opt in to `flash_attention_2` explicitly because most real users will want it. Drop the kwarg (or pass `"sdpa"` / `"eager"`) if you don't have `flash-attn` installed.
95
 
 
 
96
  ### Embedding generation (no LM head)
97
 
98
  ```python
 
93
 
94
  > **Note on attention backend.** By HuggingFace convention this model defaults to `attn_implementation="sdpa"` (`F.scaled_dot_product_attention`) since SDPA needs only `torch` and runs on any GPU. The original Arc Institute Evo 2 inference path uses **flash_attention_2**, which is faster on long sequences but requires a separate `flash-attn` install. All usage examples below opt in to `flash_attention_2` explicitly because most real users will want it. Drop the kwarg (or pass `"sdpa"` / `"eager"`) if you don't have `flash-attn` installed.
95
 
96
+ > **Optional Triton kernels.** For faster long-sequence inference, pass `use_hcs_kernel=True, use_hcm_kernel=True, use_hcl_kernel=True` to `from_pretrained` (requires `triton`). These are the Hyena kernels from [vortex PR #77](https://github.com/Zymrael/vortex/pull/77) by [@AlphaKhaw](https://github.com/AlphaKhaw), vendored unchanged in `kernels.py`. On Evo 2 7B (1M) they cut peak memory by ~40% at 64K tokens, fit 131K tokens on a single 80 GB H100, and run ~1.2x faster. They are inference-only and not bit-exact with the default path (top-token agreement >= 99.98% in our tests); upstream notes they regress generation quality on the 1B.
97
+
98
  ### Embedding generation (no LM head)
99
 
100
  ```python
configuration_evo2.py CHANGED
@@ -81,6 +81,11 @@ class Evo2Config(PretrainedConfig):
81
  # TE scaling recipe for those projections: "delayed" matches the original
82
  # Evo 2 (vortex); "current" also works when training across GPUs.
83
  fp8_recipe: str = "delayed",
 
 
 
 
 
84
  # Backend toggles
85
  use_cache: bool = True,
86
  # Vortex used this flag at runtime. Our HF port ignores it entirely
@@ -167,6 +172,9 @@ class Evo2Config(PretrainedConfig):
167
  if fp8_recipe not in ("delayed", "current"):
168
  raise ValueError(f"fp8_recipe must be 'delayed' or 'current', got {fp8_recipe!r}")
169
  self.fp8_recipe = fp8_recipe
 
 
 
170
 
171
  self.use_cache = use_cache
172
  self.use_flash_attn = use_flash_attn
 
81
  # TE scaling recipe for those projections: "delayed" matches the original
82
  # Evo 2 (vortex); "current" also works when training across GPUs.
83
  fp8_recipe: str = "delayed",
84
+ # Opt-in Triton kernels for the Hyena short / medium / long blocks
85
+ # (vortex PR #77). Inference only; not bit-exact with the default path.
86
+ use_hcs_kernel: bool = False,
87
+ use_hcm_kernel: bool = False,
88
+ use_hcl_kernel: bool = False,
89
  # Backend toggles
90
  use_cache: bool = True,
91
  # Vortex used this flag at runtime. Our HF port ignores it entirely
 
172
  if fp8_recipe not in ("delayed", "current"):
173
  raise ValueError(f"fp8_recipe must be 'delayed' or 'current', got {fp8_recipe!r}")
174
  self.fp8_recipe = fp8_recipe
175
+ self.use_hcs_kernel = use_hcs_kernel
176
+ self.use_hcm_kernel = use_hcm_kernel
177
+ self.use_hcl_kernel = use_hcl_kernel
178
 
179
  self.use_cache = use_cache
180
  self.use_flash_attn = use_flash_attn
engine.py CHANGED
@@ -18,9 +18,18 @@ Layout conventions match vortex exactly so checkpoints are bit-identical.
18
 
19
  from __future__ import annotations
20
 
 
 
21
  import torch
22
  import torch.nn.functional as F
23
 
 
 
 
 
 
 
 
24
 
25
  IIR_PREFILL_MODES = ["recurrence", "modal-fft"]
26
 
@@ -76,12 +85,28 @@ class HyenaInferenceEngine:
76
  layer_idx: int | None = None,
77
  iir_prefill_style: str = "modal-fft",
78
  hyena_flip_x1x2: bool = False,
 
 
 
79
  ) -> None:
80
  assert iir_prefill_style in IIR_PREFILL_MODES, iir_prefill_style
81
  self.iir_prefill_style = iir_prefill_style
82
  self.layer_idx = layer_idx
83
  self.low_mem_mode = False
84
  self.hyena_flip_x1x2 = hyena_flip_x1x2
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  # ---------------------------------------------------------------- FIR
87
  def parallel_fir(
@@ -110,11 +135,16 @@ class HyenaInferenceEngine:
110
  x2, x1, v = u.split([hidden_size, hidden_size, hidden_size], dim=1)
111
  if self.hyena_flip_x1x2:
112
  x1, x2 = x2, x1
 
 
 
 
113
  u = x1 * v
114
 
115
  if fir_length >= 128:
 
116
  with torch.autocast("cuda"):
117
- z = fftconv_func(
118
  u.to(torch.float32),
119
  weight[:, :, :L].to(torch.float32),
120
  bias,
@@ -191,7 +221,17 @@ class HyenaInferenceEngine:
191
  x1v = x1 * v
192
 
193
  X_s = None
194
- if inference_params is not None and prefill_style == "recurrence":
 
 
 
 
 
 
 
 
 
 
195
  y = self.prefill_via_direct_recurrence(
196
  inference_params=inference_params, x1v=x1v, L=L,
197
  poles=poles, residues=residues,
@@ -220,7 +260,8 @@ class HyenaInferenceEngine:
220
  )[..., :L]
221
 
222
  y = y.to(dtype=x1v.dtype)
223
- y = (y + x1v * D.unsqueeze(-1)) * x2
 
224
 
225
  if inference_params is not None and prefill_style == "fft":
226
  self.prefill_via_modal_fft(
 
18
 
19
  from __future__ import annotations
20
 
21
+ import warnings
22
+
23
  import torch
24
  import torch.nn.functional as F
25
 
26
+ # Optional Triton kernels (use_hc{s,m,l}_kernel); import is guarded so the
27
+ # model still loads where triton is unavailable.
28
+ try:
29
+ from .kernels import hcl_fft_conv, hcm_fft_conv, hcs_conv
30
+ except ImportError:
31
+ hcs_conv = hcm_fft_conv = hcl_fft_conv = None
32
+
33
 
34
  IIR_PREFILL_MODES = ["recurrence", "modal-fft"]
35
 
 
85
  layer_idx: int | None = None,
86
  iir_prefill_style: str = "modal-fft",
87
  hyena_flip_x1x2: bool = False,
88
+ use_hcs_kernel: bool = False,
89
+ use_hcm_kernel: bool = False,
90
+ use_hcl_kernel: bool = False,
91
  ) -> None:
92
  assert iir_prefill_style in IIR_PREFILL_MODES, iir_prefill_style
93
  self.iir_prefill_style = iir_prefill_style
94
  self.layer_idx = layer_idx
95
  self.low_mem_mode = False
96
  self.hyena_flip_x1x2 = hyena_flip_x1x2
97
+ self.use_hcs_kernel = use_hcs_kernel
98
+ self.use_hcm_kernel = use_hcm_kernel
99
+ self.use_hcl_kernel = use_hcl_kernel
100
+ for flag, requested, kernel in (
101
+ ("use_hcs_kernel", use_hcs_kernel, hcs_conv),
102
+ ("use_hcm_kernel", use_hcm_kernel, hcm_fft_conv),
103
+ ("use_hcl_kernel", use_hcl_kernel, hcl_fft_conv),
104
+ ):
105
+ if requested and kernel is None:
106
+ warnings.warn(
107
+ f"{flag}=True but triton is unavailable; using the standard path.",
108
+ RuntimeWarning, stacklevel=2,
109
+ )
110
 
111
  # ---------------------------------------------------------------- FIR
112
  def parallel_fir(
 
135
  x2, x1, v = u.split([hidden_size, hidden_size, hidden_size], dim=1)
136
  if self.hyena_flip_x1x2:
137
  x1, x2 = x2, x1
138
+ if self.use_hcs_kernel and hcs_conv is not None and fir_length < 128 and groups:
139
+ z = hcs_conv(x1, x2, v, weight, bias, gated_bias=gated_bias, padding_mask=padding_mask)
140
+ fir_state = (x1 * v)[..., -fir_length + 1 :] if inference_params is not None else None
141
+ return z, fir_state
142
  u = x1 * v
143
 
144
  if fir_length >= 128:
145
+ fftconv = hcm_fft_conv if self.use_hcm_kernel and hcm_fft_conv is not None else fftconv_func
146
  with torch.autocast("cuda"):
147
+ z = fftconv(
148
  u.to(torch.float32),
149
  weight[:, :, :L].to(torch.float32),
150
  bias,
 
221
  x1v = x1 * v
222
 
223
  X_s = None
224
+ # The HCL kernel also applies the (y + x1v * D) * x2 epilogue below.
225
+ use_hcl = (
226
+ self.use_hcl_kernel
227
+ and hcl_fft_conv is not None
228
+ and inference_params is None
229
+ and long_fir_threshold is None
230
+ and not (use_flashfft and L % 2 == 0)
231
+ )
232
+ if use_hcl:
233
+ y = hcl_fft_conv(h, x1v, x2, D, L, fft_size)
234
+ elif inference_params is not None and prefill_style == "recurrence":
235
  y = self.prefill_via_direct_recurrence(
236
  inference_params=inference_params, x1v=x1v, L=L,
237
  poles=poles, residues=residues,
 
260
  )[..., :L]
261
 
262
  y = y.to(dtype=x1v.dtype)
263
+ if not use_hcl:
264
+ y = (y + x1v * D.unsqueeze(-1)) * x2
265
 
266
  if inference_params is not None and prefill_style == "fft":
267
  self.prefill_via_modal_fft(
hyena.py CHANGED
@@ -26,7 +26,7 @@ import torch.nn as nn
26
  import torch.nn.functional as F
27
 
28
  from .attention import MHA
29
- from .engine import HyenaInferenceEngine
30
  from .layers import ParallelGatedMLP, RMSNorm, TELinear
31
  from .rotary import restore_rotary_inv_freq, swap_mha_rope
32
 
@@ -196,6 +196,9 @@ class HyenaCascade(nn.Module):
196
  self.engine = HyenaInferenceEngine(
197
  layer_idx=layer_idx,
198
  hyena_flip_x1x2=config.get("hyena_flip_x1x2", False),
 
 
 
199
  )
200
  self.fir_fn = F.conv1d
201
  self.fir_inner_fn = F.conv1d
@@ -372,7 +375,13 @@ class HyenaCascade(nn.Module):
372
  filter_dtype = torch.float32
373
  residues = self.residues.to(filter_dtype)
374
  log_poles = self.log_poles.to(filter_dtype)
375
- h = (residues[..., None] * (log_poles * self.t).exp()).sum(1)[None] # B, D, L
 
 
 
 
 
 
376
  return h, filter_dtype, log_poles, residues
377
 
378
 
 
26
  import torch.nn.functional as F
27
 
28
  from .attention import MHA
29
+ from .engine import HyenaInferenceEngine, hcl_fft_conv
30
  from .layers import ParallelGatedMLP, RMSNorm, TELinear
31
  from .rotary import restore_rotary_inv_freq, swap_mha_rope
32
 
 
196
  self.engine = HyenaInferenceEngine(
197
  layer_idx=layer_idx,
198
  hyena_flip_x1x2=config.get("hyena_flip_x1x2", False),
199
+ use_hcs_kernel=config.get("use_hcs_kernel", False),
200
+ use_hcm_kernel=config.get("use_hcm_kernel", False),
201
+ use_hcl_kernel=config.get("use_hcl_kernel", False),
202
  )
203
  self.fir_fn = F.conv1d
204
  self.fir_inner_fn = F.conv1d
 
375
  filter_dtype = torch.float32
376
  residues = self.residues.to(filter_dtype)
377
  log_poles = self.log_poles.to(filter_dtype)
378
+ if self.engine.use_hcl_kernel and hcl_fft_conv is not None:
379
+ # Tiled build; never materializes the (D, state_size, L) intermediate.
380
+ from .kernels import _hcl_compute_filter
381
+ D, S = residues.shape[0], residues.shape[1]
382
+ h = _hcl_compute_filter(residues, log_poles.reshape(D, S), self.t.reshape(-1).float())[None]
383
+ else:
384
+ h = (residues[..., None] * (log_poles * self.t).exp()).sum(1)[None] # B, D, L
385
  return h, filter_dtype, log_poles, residues
386
 
387
 
kernels.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional Triton kernels for the Hyena short / medium / long blocks (inference only).
2
+
3
+ These kernels were written by @AlphaKhaw for vortex in
4
+ https://github.com/Zymrael/vortex/pull/77. They are vendored unchanged from
5
+ Zymrael/vortex@9c54bb31c7 (vortex/ops/{triton_common,hcs_interface,
6
+ hcm_interface,hcl_interface}.py, Apache-2.0), merged into one file. Enabled
7
+ per block type with the use_hc{s,m,l}_kernel config flags; off by default.
8
+ """
9
+
10
+ from collections.abc import Callable
11
+
12
+ import torch
13
+ import triton
14
+ import triton.language as tl
15
+
16
+
17
+ # triton_common.py
18
+
19
+ # 2-D (BLOCK_D, BLOCK_L) tile sweep for memory-bound elementwise kernels over
20
+ # a (D, L) plane. Re-benchmarked per shape key by each decorated kernel.
21
+ BDL_TILE_CONFIGS: list[triton.Config] = [
22
+ triton.Config({"BLOCK_D": 32, "BLOCK_L": 64}, num_warps=2),
23
+ triton.Config({"BLOCK_D": 64, "BLOCK_L": 64}, num_warps=4),
24
+ triton.Config({"BLOCK_D": 64, "BLOCK_L": 128}, num_warps=4),
25
+ triton.Config({"BLOCK_D": 128, "BLOCK_L": 64}, num_warps=4),
26
+ triton.Config({"BLOCK_D": 64, "BLOCK_L": 256}, num_warps=8),
27
+ triton.Config({"BLOCK_D": 128, "BLOCK_L": 128}, num_warps=8),
28
+ ]
29
+
30
+
31
+ def bdl_grid_3d(B: int, D: int, L: int) -> Callable[[dict], tuple[int, int, int]]:
32
+ """
33
+ Standard (B, cdiv(D, BLOCK_D), cdiv(L, BLOCK_L)) grid for the HC bias-residual
34
+ and HCS conv kernels. Reads tile sizes from the autotune meta-dict.
35
+ """
36
+ return lambda meta: (
37
+ B,
38
+ triton.cdiv(D, meta["BLOCK_D"]),
39
+ triton.cdiv(L, meta["BLOCK_L"]),
40
+ )
41
+
42
+
43
+ def bdl_grid_2d(D: int, L: int) -> Callable[[dict], tuple[int, int]]:
44
+ """
45
+ 2-D (cdiv(D, BLOCK_D), cdiv(L, BLOCK_L)) grid for kernels without a batch
46
+ axis (the HCL filter build).
47
+ """
48
+ return lambda meta: (
49
+ triton.cdiv(D, meta["BLOCK_D"]),
50
+ triton.cdiv(L, meta["BLOCK_L"]),
51
+ )
52
+
53
+
54
+ # hcs_interface.py
55
+
56
+ @triton.autotune(configs=BDL_TILE_CONFIGS, key=["D", "L", "FIR_LEN"])
57
+ @triton.jit
58
+ def _hcs_depthwise_conv_kernel(
59
+ u_ptr,
60
+ w_ptr,
61
+ z_ptr,
62
+ D,
63
+ L,
64
+ stride_ub,
65
+ stride_ud,
66
+ stride_ul,
67
+ stride_wd,
68
+ stride_wk,
69
+ FIR_LEN: tl.constexpr,
70
+ BLOCK_D: tl.constexpr,
71
+ BLOCK_L: tl.constexpr,
72
+ ):
73
+ """
74
+ Depthwise causal conv: z[b, d, t] = sum_k w[d, k] * u[b, d, t - FIR_LEN + 1 + k].
75
+
76
+ One program covers a (BLOCK_D, BLOCK_L) tile of one batch element. The
77
+ FIR_LEN tap loop is unrolled at compile time. Input positions before 0
78
+ are masked to zero, giving a causal (left-padded) convolution.
79
+ """
80
+ pid_b = tl.program_id(0)
81
+ pid_d = tl.program_id(1)
82
+ pid_l = tl.program_id(2)
83
+
84
+ offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
85
+ offs_l = pid_l * BLOCK_L + tl.arange(0, BLOCK_L)
86
+ mask_d = offs_d < D
87
+ mask_l = offs_l < L
88
+ tile_mask = mask_d[:, None] & mask_l[None, :]
89
+
90
+ u_base = u_ptr + pid_b * stride_ub + offs_d[:, None] * stride_ud
91
+ acc = tl.zeros((BLOCK_D, BLOCK_L), dtype=tl.float32)
92
+
93
+ # hcs_conv forces fp32 before launch, so loaded tiles are already fp32 --
94
+ # the .to(tl.float32) calls are no-ops at runtime.
95
+ for k in tl.static_range(FIR_LEN):
96
+ w_k = tl.load(
97
+ w_ptr + offs_d * stride_wd + k * stride_wk, mask=mask_d, other=0.0
98
+ )
99
+ pos = offs_l - (FIR_LEN - 1) + k
100
+ mask_pos = tile_mask & (pos[None, :] >= 0) & (pos[None, :] < L)
101
+ u_tile = tl.load(u_base + pos[None, :] * stride_ul, mask=mask_pos, other=0.0)
102
+ acc += w_k[:, None] * u_tile
103
+
104
+ z_ptrs = (
105
+ z_ptr
106
+ + pid_b * stride_ub
107
+ + offs_d[:, None] * stride_ud
108
+ + offs_l[None, :] * stride_ul
109
+ )
110
+ tl.store(z_ptrs, acc, mask=tile_mask)
111
+
112
+
113
+ def hcs_depthwise_conv(u: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
114
+ """
115
+ Depthwise causal 1D convolution, the HCS short-filter time-mixing op.
116
+
117
+ Equivalent to F.conv1d(u, weight, padding=fir_length - 1, groups=D)
118
+ trimmed to length L, but in a single fused Triton launch.
119
+
120
+ Args:
121
+ u (torch.Tensor): Input activations, shape (B, D, L), contiguous.
122
+ weight (torch.Tensor): Depthwise filter, shape (D, 1, fir_length),
123
+ contiguous. Every channel has its own filter.
124
+
125
+ Returns:
126
+ torch.Tensor: Convolved output, shape (B, D, L), same dtype as u.
127
+ """
128
+ u = u.contiguous()
129
+ weight = weight.contiguous()
130
+ if u.dim() != 3 or weight.dim() != 3:
131
+ raise ValueError(f"expected 3-D u and weight, got {u.shape} and {weight.shape}")
132
+
133
+ B, D, L = u.shape
134
+ Dw, in_per_group, fir_length = weight.shape
135
+ if Dw != D or in_per_group != 1:
136
+ raise ValueError(f"weight {tuple(weight.shape)} is not depthwise for D={D}")
137
+
138
+ z: torch.Tensor = torch.empty_like(u)
139
+ _hcs_depthwise_conv_kernel[bdl_grid_3d(B, D, L)](
140
+ u,
141
+ weight,
142
+ z,
143
+ D,
144
+ L,
145
+ u.stride(0),
146
+ u.stride(1),
147
+ u.stride(2),
148
+ weight.stride(0),
149
+ weight.stride(2),
150
+ FIR_LEN=fir_length,
151
+ )
152
+ return z
153
+
154
+
155
+ def hcs_conv(
156
+ x1: torch.Tensor,
157
+ x2: torch.Tensor,
158
+ v: torch.Tensor,
159
+ weight: torch.Tensor,
160
+ bias: torch.Tensor | None = None,
161
+ *,
162
+ gated_bias: bool = False,
163
+ padding_mask: torch.Tensor | None = None,
164
+ ) -> torch.Tensor:
165
+ """
166
+ Fully-gated HCS short conv: z = x2 * (conv(x1 * v, weight) + bias).
167
+
168
+ Drop-in for the gated fir_length < 128 branch of
169
+ HyenaInferenceEngine.parallel_fir. Conv runs in fp32 for parity with
170
+ F.conv1d, then casts back to x1.dtype.
171
+
172
+ Args:
173
+ x1 (torch.Tensor): Pre-gate "key" stream, shape (B, D, L).
174
+ x2 (torch.Tensor): Post-gate stream, shape (B, D, L).
175
+ v (torch.Tensor): "Value" stream, shape (B, D, L).
176
+ weight (torch.Tensor): Depthwise filter, shape (D, 1, fir_length).
177
+ bias (torch.Tensor | None): Per-channel skip-gain, shape (D,).
178
+ gated_bias (bool): If True, bias is applied multiplicatively
179
+ (bias * x1 * v); HCS uses additive (False).
180
+ padding_mask (torch.Tensor | None): If set, zeros masked positions
181
+ after the conv, shape (B, L).
182
+
183
+ Returns:
184
+ torch.Tensor: Gated HCS output, shape (B, D, L), x1's dtype.
185
+ """
186
+ u: torch.Tensor = x1 * v
187
+ z: torch.Tensor = hcs_depthwise_conv(u=u.float(), weight=weight.float())
188
+ z = z.to(u.dtype)
189
+
190
+ if bias is not None:
191
+ if gated_bias:
192
+ z = z + bias[None, :, None] * u
193
+ else:
194
+ z = z + bias[None, :, None]
195
+
196
+ if isinstance(padding_mask, torch.Tensor):
197
+ z = z * padding_mask[:, None]
198
+
199
+ return x2 * z
200
+
201
+
202
+ # hcm_interface.py
203
+
204
+ # 1-D BLOCK sweep for the complex multiply -- the only HC kernel that flattens
205
+ # (D, F) to a single axis, so it can't share BDL_TILE_CONFIGS.
206
+ _COMPLEX_MUL_CONFIGS: list[triton.Config] = [
207
+ triton.Config({"BLOCK": 256}, num_warps=2),
208
+ triton.Config({"BLOCK": 512}, num_warps=4),
209
+ triton.Config({"BLOCK": 1024}, num_warps=4),
210
+ triton.Config({"BLOCK": 2048}, num_warps=8),
211
+ ]
212
+
213
+
214
+ @triton.autotune(configs=_COMPLEX_MUL_CONFIGS, key=["DF"])
215
+ @triton.jit
216
+ def _hcm_complex_mul_kernel(
217
+ u_ptr,
218
+ k_ptr,
219
+ y_ptr,
220
+ DF,
221
+ inv_fft_size,
222
+ stride_batch,
223
+ BLOCK: tl.constexpr,
224
+ ):
225
+ """
226
+ Broadcast complex multiply: y[b] = u_f[b] * k_f[0] * inv_fft_size.
227
+
228
+ One program covers a BLOCK-element slice of the flattened (D, F) plane
229
+ of one batch element. Complex values are stored interleaved (real, imag)
230
+ -- view_as_real's layout -- so element n's real part is at offset 2n and
231
+ its imag part at 2n + 1. The filter k_f carries no batch stride: every
232
+ batch element multiplies against the same spectrum.
233
+
234
+ The flat (D, F) tile is grid axis 0: cdiv(DF, BLOCK) overruns the 65535
235
+ cap on axes 1 and 2 at long context, so the small batch sits on axis 1.
236
+ """
237
+ pid = tl.program_id(0)
238
+ pid_b = tl.program_id(1)
239
+
240
+ offs = pid * BLOCK + tl.arange(0, BLOCK)
241
+ mask = offs < DF
242
+
243
+ u_base = u_ptr + pid_b * stride_batch
244
+ y_base = y_ptr + pid_b * stride_batch
245
+
246
+ u_re = tl.load(u_base + 2 * offs, mask=mask, other=0.0)
247
+ u_im = tl.load(u_base + 2 * offs + 1, mask=mask, other=0.0)
248
+ k_re = tl.load(k_ptr + 2 * offs, mask=mask, other=0.0)
249
+ k_im = tl.load(k_ptr + 2 * offs + 1, mask=mask, other=0.0)
250
+
251
+ y_re = (u_re * k_re - u_im * k_im) * inv_fft_size
252
+ y_im = (u_re * k_im + u_im * k_re) * inv_fft_size
253
+
254
+ tl.store(y_base + 2 * offs, y_re, mask=mask)
255
+ tl.store(y_base + 2 * offs + 1, y_im, mask=mask)
256
+
257
+
258
+ def _hcm_complex_mul(
259
+ u_f: torch.Tensor, k_f: torch.Tensor, fft_size: int
260
+ ) -> torch.Tensor:
261
+ """
262
+ Fused broadcast complex multiply with the 1/fft_size filter scale.
263
+
264
+ Computes u_f * k_f / fft_size -- stage 3 of fftconv_func, with stage 1's
265
+ filter normalisation folded in. u_f is the activation spectrum; k_f is
266
+ the *unscaled* filter spectrum, already shaped for broadcast over the
267
+ batch by adjust_filter_shape_for_broadcast.
268
+
269
+ Args:
270
+ u_f (torch.Tensor): Activation spectrum, complex, shape (B, D, F).
271
+ k_f (torch.Tensor): Filter spectrum, complex, shape (1, D, F), shared
272
+ across the batch and not yet scaled by 1/fft_size.
273
+ fft_size (int): The FFT length n = 2 * seqlen; its reciprocal folds
274
+ in as the filter normalisation.
275
+
276
+ Returns:
277
+ torch.Tensor: The scaled product u_f * k_f / fft_size, complex, shape
278
+ (B, D, F), u_f's dtype.
279
+
280
+ Raises:
281
+ ValueError: If the tensors are not 3-D complex, or k_f is not
282
+ broadcastable over the batch of u_f.
283
+ """
284
+ if u_f.dim() != 3 or k_f.dim() != 3:
285
+ raise ValueError(
286
+ f"expected 3-D u_f and k_f, got {tuple(u_f.shape)} and {tuple(k_f.shape)}"
287
+ )
288
+ if not u_f.is_complex() or not k_f.is_complex():
289
+ raise ValueError("u_f and k_f must be complex tensors")
290
+
291
+ B, D, F = u_f.shape
292
+ if tuple(k_f.shape) != (1, D, F):
293
+ raise ValueError(
294
+ f"k_f {tuple(k_f.shape)} is not broadcastable over u_f {tuple(u_f.shape)}"
295
+ )
296
+
297
+ u_f = u_f.contiguous()
298
+ k_f = k_f.contiguous()
299
+ y_f: torch.Tensor = torch.empty_like(u_f)
300
+
301
+ # Triton has no complex dtype: operate on the (..., 2) real/imag view.
302
+ u_r = torch.view_as_real(u_f)
303
+ k_r = torch.view_as_real(k_f)
304
+ y_r = torch.view_as_real(y_f)
305
+
306
+ DF = D * F
307
+ grid: Callable[[dict], tuple[int, int]] = lambda meta: (
308
+ triton.cdiv(DF, meta["BLOCK"]),
309
+ B,
310
+ )
311
+ _hcm_complex_mul_kernel[grid](
312
+ u_r,
313
+ k_r,
314
+ y_r,
315
+ DF,
316
+ 1.0 / fft_size,
317
+ u_r.stride(0),
318
+ )
319
+ return y_f
320
+
321
+
322
+ @triton.autotune(configs=BDL_TILE_CONFIGS, key=["D", "L"])
323
+ @triton.jit
324
+ def _hcm_bias_residual_kernel(
325
+ y_ptr,
326
+ u_ptr,
327
+ bias_ptr,
328
+ out_ptr,
329
+ D,
330
+ L,
331
+ stride_b,
332
+ stride_d,
333
+ stride_l,
334
+ BLOCK_D: tl.constexpr,
335
+ BLOCK_L: tl.constexpr,
336
+ ):
337
+ """
338
+ Skip-residual add: out[b, d, l] = y[b, d, l] + u[b, d, l] * bias[d].
339
+
340
+ One program covers a (BLOCK_D, BLOCK_L) tile of one batch element. y, u
341
+ and out share a contiguous (B, D, L) layout; bias is per-channel, shape
342
+ (D,), broadcast over batch and length. The fp32 accumulator is cast to
343
+ out's dtype on the store -- fftconv_func's stage-6 .to(u.dtype) cast.
344
+ """
345
+ pid_b = tl.program_id(0)
346
+ pid_d = tl.program_id(1)
347
+ pid_l = tl.program_id(2)
348
+
349
+ offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
350
+ offs_l = pid_l * BLOCK_L + tl.arange(0, BLOCK_L)
351
+ mask_d = offs_d < D
352
+ mask_l = offs_l < L
353
+ mask = mask_d[:, None] & mask_l[None, :]
354
+
355
+ offs = pid_b * stride_b + offs_d[:, None] * stride_d + offs_l[None, :] * stride_l
356
+ y = tl.load(y_ptr + offs, mask=mask, other=0.0).to(tl.float32)
357
+ u = tl.load(u_ptr + offs, mask=mask, other=0.0).to(tl.float32)
358
+ bias = tl.load(bias_ptr + offs_d, mask=mask_d, other=0.0).to(tl.float32)
359
+
360
+ acc = y + u * bias[:, None]
361
+ tl.store(out_ptr + offs, acc, mask=mask)
362
+
363
+
364
+ def _hcm_bias_residual(
365
+ y: torch.Tensor, u: torch.Tensor, bias: torch.Tensor
366
+ ) -> torch.Tensor:
367
+ """
368
+ Fused skip-residual add -- stage 5 of fftconv_func.
369
+
370
+ Computes y + u * bias[:, None] and writes it at u's dtype, fusing
371
+ fftconv_func's broadcast multiply and residual add (and its stage-6
372
+ dtype cast) into a single Triton launch.
373
+
374
+ Args:
375
+ y (torch.Tensor): The irfft output, shape (B, D, L).
376
+ u (torch.Tensor): The activations, shape (B, D, L); its dtype is the
377
+ output dtype -- fftconv_func's stage-6 cast target.
378
+ bias (torch.Tensor): Per-channel skip gain, shape (D,), broadcast
379
+ over batch and length.
380
+
381
+ Returns:
382
+ torch.Tensor: y + u * bias[:, None], shape (B, D, L), u's dtype.
383
+
384
+ Raises:
385
+ ValueError: If y and u are not matching 3-D tensors, or bias is not
386
+ 1-D of length D.
387
+ """
388
+ if y.dim() != 3 or u.dim() != 3:
389
+ raise ValueError(
390
+ f"expected 3-D y and u, got {tuple(y.shape)} and {tuple(u.shape)}"
391
+ )
392
+ if y.shape != u.shape:
393
+ raise ValueError(f"y {tuple(y.shape)} and u {tuple(u.shape)} must match")
394
+
395
+ B, D, L = u.shape
396
+ if bias.dim() != 1 or bias.shape[0] != D:
397
+ raise ValueError(f"bias {tuple(bias.shape)} must be 1-D of length D={D}")
398
+
399
+ y = y.contiguous()
400
+ u = u.contiguous()
401
+ bias = bias.contiguous()
402
+ out: torch.Tensor = torch.empty_like(u)
403
+ _hcm_bias_residual_kernel[bdl_grid_3d(B, D, L)](
404
+ y,
405
+ u,
406
+ bias,
407
+ out,
408
+ D,
409
+ L,
410
+ u.stride(0),
411
+ u.stride(1),
412
+ u.stride(2),
413
+ )
414
+ return out
415
+
416
+
417
+ def hcm_fft_conv(
418
+ u: torch.Tensor,
419
+ k: torch.Tensor,
420
+ D: torch.Tensor,
421
+ dropout_mask: torch.Tensor | None,
422
+ gelu: bool = False,
423
+ k_rev: torch.Tensor | None = None,
424
+ bidirectional: bool = False,
425
+ print_activations: bool = False,
426
+ layer_idx: int | None = None,
427
+ **kwargs,
428
+ ) -> torch.Tensor:
429
+ """
430
+ Fused HCM FFT-convolution -- drop-in for fftconv_func.
431
+
432
+ cuFFT keeps the three transforms; _hcm_complex_mul does stage 3 (scaled
433
+ spectral product), _hcm_bias_residual does stage 5 (skip-residual add).
434
+ Trailing kwargs exist only for signature parity with fftconv_func so the
435
+ engine dispatch is a one-line swap. gelu and dropout_mask are part of that
436
+ parity surface but unsupported -- the kernel has no activation or dropout
437
+ stage, so a set value raises instead of being silently dropped.
438
+
439
+ Args:
440
+ u (torch.Tensor): Input activations, shape (B, D, L).
441
+ k (torch.Tensor): Filter, shape (D, 1, K).
442
+ D (torch.Tensor): Per-channel skip-connection bias, shape (D,).
443
+ dropout_mask (torch.Tensor | None): Unsupported; must be None (parity only).
444
+ gelu (bool): Unsupported; must be False; the kernel has no activation stage.
445
+
446
+ Returns:
447
+ torch.Tensor: y + u * D[:, None], shape (B, D, L), u's dtype.
448
+
449
+ Raises:
450
+ NotImplementedError: If bidirectional is True, k_rev is set, gelu is
451
+ True, or dropout_mask is not None -- the HCM
452
+ kernel implements none of these.
453
+ """
454
+ if bidirectional or k_rev is not None:
455
+ raise NotImplementedError(
456
+ "hcm_fft_conv handles only the causal, non-reverse path"
457
+ )
458
+ if gelu or dropout_mask is not None:
459
+ raise NotImplementedError(
460
+ "hcm_fft_conv implements only the gelu=False, dropout_mask=None "
461
+ "path used by evo2; the kernel has no activation or dropout stage."
462
+ )
463
+
464
+ seqlen = u.shape[-1]
465
+ fft_size = 2 * seqlen
466
+
467
+ # rfft(k) reshaped to (1, D, F) for the batch broadcast -- inlined to avoid
468
+ # the adjust_filter_shape_for_broadcast import cycle. squeeze(1) drops only
469
+ # the channel-group axis; .squeeze() with no arg would also collapse a D=1
470
+ # case and break the (1, D, F) broadcast contract.
471
+ k_f = torch.fft.rfft(k, n=fft_size).squeeze(1).unsqueeze(0)
472
+ u_f = torch.fft.rfft(u.to(dtype=k.dtype), n=fft_size)
473
+
474
+ prod = _hcm_complex_mul(u_f, k_f, fft_size)
475
+ y = torch.fft.irfft(prod, n=fft_size, norm="forward")[..., :seqlen]
476
+ return _hcm_bias_residual(y, u, D)
477
+
478
+
479
+ # hcl_interface.py
480
+
481
+ @triton.autotune(configs=BDL_TILE_CONFIGS, key=["D", "L"])
482
+ @triton.jit
483
+ def _hcl_compute_filter_kernel(
484
+ residues_ptr,
485
+ log_poles_ptr,
486
+ t_ptr,
487
+ h_ptr,
488
+ D,
489
+ L,
490
+ stride_rs_d,
491
+ stride_rs_s,
492
+ stride_h_d,
493
+ stride_h_l,
494
+ S: tl.constexpr,
495
+ BLOCK_D: tl.constexpr,
496
+ BLOCK_L: tl.constexpr,
497
+ ):
498
+ """
499
+ Modal filter: h[d, l] = sum_s residues[d, s] * exp(log_poles[d, s] * t[l]).
500
+
501
+ One program covers a (BLOCK_D, BLOCK_L) tile of h; the state-size sum (S
502
+ terms) runs in a fp32 register accumulator so the (D, S, L) intermediate
503
+ that OOMs the stock compute_filter at L=131k never exists.
504
+ """
505
+ pid_d = tl.program_id(0)
506
+ pid_l = tl.program_id(1)
507
+
508
+ offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
509
+ offs_l = pid_l * BLOCK_L + tl.arange(0, BLOCK_L)
510
+ mask_d = offs_d < D
511
+ mask_l = offs_l < L
512
+
513
+ t_tile = tl.load(t_ptr + offs_l, mask=mask_l, other=0.0).to(tl.float32)
514
+
515
+ acc = tl.zeros((BLOCK_D, BLOCK_L), dtype=tl.float32)
516
+ for s in tl.static_range(S):
517
+ rs_offs = offs_d * stride_rs_d + s * stride_rs_s
518
+ r_s = tl.load(residues_ptr + rs_offs, mask=mask_d, other=0.0).to(tl.float32)
519
+ lp_s = tl.load(log_poles_ptr + rs_offs, mask=mask_d, other=0.0).to(tl.float32)
520
+ acc += r_s[:, None] * tl.exp(lp_s[:, None] * t_tile[None, :])
521
+
522
+ h_ptrs = h_ptr + offs_d[:, None] * stride_h_d + offs_l[None, :] * stride_h_l
523
+ tl.store(h_ptrs, acc, mask=mask_d[:, None] & mask_l[None, :])
524
+
525
+
526
+ def _hcl_compute_filter(
527
+ residues: torch.Tensor, log_poles: torch.Tensor, t: torch.Tensor
528
+ ) -> torch.Tensor:
529
+ """
530
+ Tiled modal-filter build -- the HCL compute_filter without the OOM.
531
+
532
+ Computes h[d, l] = sum_s residues[d, s] * exp(log_poles[d, s] * t[l]), the
533
+ (D, L) filter compute_filter builds, with the state-size sum done
534
+ in-register so the (D, state_size, L) intermediate never exists.
535
+
536
+ Args:
537
+ residues (torch.Tensor): Modal residues, shape (D, S).
538
+ log_poles (torch.Tensor): Modal log-poles, shape (D, S); negative for
539
+ a stable (decaying) filter.
540
+ t (torch.Tensor): Time index [0, 1, ..., L-1], shape (L,).
541
+
542
+ Returns:
543
+ torch.Tensor: The modal filter h, shape (D, L), fp32.
544
+
545
+ Raises:
546
+ ValueError: If residues and log_poles are not matching 2-D tensors,
547
+ or t is not 1-D.
548
+ """
549
+ if residues.dim() != 2 or log_poles.dim() != 2:
550
+ raise ValueError(
551
+ f"expected 2-D residues and log_poles, got {tuple(residues.shape)} "
552
+ f"and {tuple(log_poles.shape)}"
553
+ )
554
+ if residues.shape != log_poles.shape:
555
+ raise ValueError(
556
+ f"residues {tuple(residues.shape)} and log_poles "
557
+ f"{tuple(log_poles.shape)} must match"
558
+ )
559
+ if t.dim() != 1:
560
+ raise ValueError(f"expected 1-D t, got {tuple(t.shape)}")
561
+
562
+ D, S = residues.shape
563
+ L: int = t.shape[0]
564
+
565
+ residues = residues.contiguous().float()
566
+ log_poles = log_poles.contiguous().float()
567
+ t = t.contiguous().float()
568
+ h: torch.Tensor = torch.empty(D, L, dtype=torch.float32, device=residues.device)
569
+
570
+ _hcl_compute_filter_kernel[bdl_grid_2d(D, L)](
571
+ residues,
572
+ log_poles,
573
+ t,
574
+ h,
575
+ D,
576
+ L,
577
+ residues.stride(0),
578
+ residues.stride(1),
579
+ h.stride(0),
580
+ h.stride(1),
581
+ S,
582
+ )
583
+ return h
584
+
585
+
586
+ @triton.autotune(configs=BDL_TILE_CONFIGS, key=["D", "L"])
587
+ @triton.jit
588
+ def _hcl_bias_residual_gate_kernel(
589
+ y_ptr,
590
+ x1v_ptr,
591
+ bias_ptr,
592
+ x2_ptr,
593
+ out_ptr,
594
+ D,
595
+ L,
596
+ stride_b,
597
+ stride_d,
598
+ stride_l,
599
+ BLOCK_D: tl.constexpr,
600
+ BLOCK_L: tl.constexpr,
601
+ ):
602
+ """
603
+ Bias-residual + gate: out[b,d,l] = (y[b,d,l] + x1v[b,d,l]*bias[d]) * x2[b,d,l].
604
+
605
+ One program covers a (BLOCK_D, BLOCK_L) tile of one batch element. y, x1v,
606
+ x2 and out share a contiguous (B, D, L) layout; bias is per-channel, shape
607
+ (D,), broadcast over batch and length. The fp32 accumulator is cast to
608
+ out's dtype on the store -- parallel_iir's y.to(x1v.dtype) cast.
609
+ """
610
+ pid_b = tl.program_id(0)
611
+ pid_d = tl.program_id(1)
612
+ pid_l = tl.program_id(2)
613
+
614
+ offs_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
615
+ offs_l = pid_l * BLOCK_L + tl.arange(0, BLOCK_L)
616
+ mask_d = offs_d < D
617
+ mask_l = offs_l < L
618
+ mask = mask_d[:, None] & mask_l[None, :]
619
+
620
+ offs = pid_b * stride_b + offs_d[:, None] * stride_d + offs_l[None, :] * stride_l
621
+ y = tl.load(y_ptr + offs, mask=mask, other=0.0).to(tl.float32)
622
+ x1v = tl.load(x1v_ptr + offs, mask=mask, other=0.0).to(tl.float32)
623
+ x2 = tl.load(x2_ptr + offs, mask=mask, other=0.0).to(tl.float32)
624
+ bias = tl.load(bias_ptr + offs_d, mask=mask_d, other=0.0).to(tl.float32)
625
+
626
+ acc = (y + x1v * bias[:, None]) * x2
627
+ tl.store(out_ptr + offs, acc, mask=mask)
628
+
629
+
630
+ def _hcl_bias_residual_gate(
631
+ y: torch.Tensor, x1v: torch.Tensor, bias: torch.Tensor, x2: torch.Tensor
632
+ ) -> torch.Tensor:
633
+ """
634
+ Fused bias-residual + gate -- the HCL FFT-conv epilogue.
635
+
636
+ Computes (y + x1v * bias[:, None]) * x2 and writes it at x1v's dtype --
637
+ parallel_iir's post-conv `y = (y + x1v * D.unsqueeze(-1)) * x2`, fusing the
638
+ broadcast multiply, the residual add, the gate and the dtype cast into one
639
+ Triton launch.
640
+
641
+ Args:
642
+ y (torch.Tensor): The irfft output, shape (B, D, L).
643
+ x1v (torch.Tensor): The conv input, shape (B, D, L); its dtype is the
644
+ output dtype.
645
+ bias (torch.Tensor): Per-channel skip gain, shape (D,), broadcast over
646
+ batch and length.
647
+ x2 (torch.Tensor): The post-gate stream, shape (B, D, L).
648
+
649
+ Returns:
650
+ torch.Tensor: (y + x1v * bias[:, None]) * x2, shape (B, D, L), x1v's
651
+ dtype.
652
+
653
+ Raises:
654
+ ValueError: If y, x1v and x2 are not matching 3-D tensors, or bias is
655
+ not 1-D of length D.
656
+ """
657
+ if y.dim() != 3 or x1v.dim() != 3 or x2.dim() != 3:
658
+ raise ValueError(
659
+ f"expected 3-D y, x1v, x2, got {tuple(y.shape)}, "
660
+ f"{tuple(x1v.shape)}, {tuple(x2.shape)}"
661
+ )
662
+ if not (y.shape == x1v.shape == x2.shape):
663
+ raise ValueError(
664
+ f"y {tuple(y.shape)}, x1v {tuple(x1v.shape)}, x2 {tuple(x2.shape)} "
665
+ f"must all match"
666
+ )
667
+
668
+ B, D, L = x1v.shape
669
+ if bias.dim() != 1 or bias.shape[0] != D:
670
+ raise ValueError(f"bias {tuple(bias.shape)} must be 1-D of length D={D}")
671
+
672
+ y = y.contiguous()
673
+ x1v = x1v.contiguous()
674
+ x2 = x2.contiguous()
675
+ bias = bias.contiguous()
676
+ out: torch.Tensor = torch.empty_like(x1v)
677
+ _hcl_bias_residual_gate_kernel[bdl_grid_3d(B, D, L)](
678
+ y,
679
+ x1v,
680
+ bias,
681
+ x2,
682
+ out,
683
+ D,
684
+ L,
685
+ x1v.stride(0),
686
+ x1v.stride(1),
687
+ x1v.stride(2),
688
+ )
689
+ return out
690
+
691
+
692
+ def hcl_fft_conv(
693
+ h: torch.Tensor,
694
+ x1v: torch.Tensor,
695
+ x2: torch.Tensor,
696
+ D: torch.Tensor,
697
+ L: int,
698
+ fft_size: int,
699
+ ) -> torch.Tensor:
700
+ """
701
+ Fused HCL FFT-convolution epilogue.
702
+
703
+ Reproduces parallel_iir's long_fir_threshold-is-None branch. cuFFT keeps
704
+ the three transforms; _hcm_complex_mul does the spectral product X*H
705
+ scaled by 1/fft_size; _hcl_bias_residual_gate does the post-conv
706
+ (y + x1v*D[:, None]) * x2. Uses rfft (half the bins of fft on real input).
707
+
708
+ Args:
709
+ h (torch.Tensor): The modal filter, shape (1, D, L).
710
+ x1v (torch.Tensor): The conv input, shape (1, D, L).
711
+ x2 (torch.Tensor): The post-gate stream, shape (1, D, L).
712
+ D (torch.Tensor): Per-channel skip-connection bias, shape (D,).
713
+ L (int): Sequence length.
714
+ fft_size (int): The FFT length, n = 2 * L.
715
+
716
+ Returns:
717
+ torch.Tensor: (y + x1v*D[:, None]) * x2, shape (1, D, L), x1v's dtype.
718
+ """
719
+ H = torch.fft.rfft(h.to(dtype=torch.float32), n=fft_size)
720
+ X = torch.fft.rfft(x1v.to(dtype=torch.float32), n=fft_size)
721
+
722
+ prod = _hcm_complex_mul(X, H, fft_size)
723
+ y = torch.fft.irfft(prod, n=fft_size, norm="forward")[..., :L]
724
+ return _hcl_bias_residual_gate(y, x1v, D, x2)
modeling_evo2.py CHANGED
@@ -52,6 +52,10 @@ from .rotary import ( # noqa: F401
52
  RotaryEmbedding as _RotaryEmbedding,
53
  restore_rotary_inv_freq,
54
  )
 
 
 
 
55
 
56
  logger = logging.get_logger(__name__)
57
 
@@ -74,6 +78,10 @@ class StripedHyena2(nn.Module):
74
  fixup_te_workspace()
75
 
76
  self.config = config
 
 
 
 
77
  self.embedding_layer = VocabParallelEmbedding(config)
78
  self.norm = RMSNorm(config) if config.get("final_norm", True) else None
79
 
 
52
  RotaryEmbedding as _RotaryEmbedding,
53
  restore_rotary_inv_freq,
54
  )
55
+ try: # optional; needs triton
56
+ from .kernels import hcs_conv as _hcs_conv # noqa: F401
57
+ except ImportError:
58
+ pass
59
 
60
  logger = logging.get_logger(__name__)
61
 
 
78
  fixup_te_workspace()
79
 
80
  self.config = config
81
+ kernels = ("use_hcs_kernel", "use_hcm_kernel", "use_hcl_kernel")
82
+ if config.hidden_size == 1920 and any(config.get(k, False) for k in kernels):
83
+ # Same caveat as vortex: the kernels regress generation quality on the 1B.
84
+ logger.warning("use_hc*_kernel regresses generation quality on Evo 2 1B; disable it if that matters.")
85
  self.embedding_layer = VocabParallelEmbedding(config)
86
  self.norm = RMSNorm(config) if config.get("final_norm", True) else None
87