# SPDX-License-Identifier: Apache-2.0 """Causal depthwise conv1d of arbitrary width for LFM3's short-conv layers. vLLM's Triton ``causal_conv1d_fn`` / ``causal_conv1d_update`` are hand-unrolled for widths <= 4 / <= 6, and LFM3 uses width 7. This module provides: * ``*_torch``: vectorized PyTorch implementations (no per-sequence Python loop, no host sync), used as reference and fallback; * ``*_triton``: Triton kernels (work on XPU through triton-xpu), the default. Layouts (token-major, like vLLM's ShortConv after ``in_proj``): x (num_tokens, dim) weight (dim, width) conv_state (num_blocks, width - 1, dim) -- vLLM's "SD" conv state layout; any strides are accepted, so a transposed "DS" cache works as well. Row ``width - 2`` holds the most recent input. All accumulation is done in fp32. """ import os import torch try: import triton import triton.language as tl HAS_TRITON = True except ImportError: # pragma: no cover HAS_TRITON = False # LFM3_CONV_IMPL=torch forces the PyTorch path (debugging / kernel A/B tests). _IMPL = os.environ.get("LFM3_CONV_IMPL", "triton") def use_triton() -> bool: return HAS_TRITON and _IMPL == "triton" # --------------------------------------------------------------------------- # PyTorch implementations # --------------------------------------------------------------------------- def _prefill_source_indices( query_start_loc: torch.Tensor, num_tokens: int, state_len: int, width: int, ): """Per-token indices into ``cat([initial_states.flatten(0, 1), x])``. Returns (tap_idx (num_tokens, width), new_state_idx (num_seqs, state_len)). """ device = query_start_loc.device qsl = query_start_loc.long() num_seqs = qsl.numel() - 1 lens = qsl[1:] - qsl[:-1] seq_id = torch.repeat_interleave( torch.arange(num_seqs, device=device), lens, output_size=num_tokens ) tok = torch.arange(num_tokens, device=device) pos = tok - qsl[seq_id] x_base = num_seqs * state_len # tap k reads relative position p = pos + k - (width - 1) rel = torch.arange(width, device=device) - (width - 1) p = pos[:, None] + rel[None, :] tap_idx = torch.where( p >= 0, x_base + tok[:, None] + rel[None, :], seq_id[:, None] * state_len + state_len + p, ) # the new state is the last state_len inputs of (initial_state ++ x_seq) q = lens[:, None] - state_len + torch.arange(state_len, device=device)[None, :] seqs = torch.arange(num_seqs, device=device)[:, None] new_state_idx = torch.where( q >= 0, x_base + qsl[:-1, None] + q, seqs * state_len + state_len + q ) return tap_idx, new_state_idx def causal_conv1d_prefill_torch( x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None, conv_state: torch.Tensor, query_start_loc: torch.Tensor, state_indices: torch.Tensor, has_initial_state: torch.Tensor, ) -> torch.Tensor: num_tokens, dim = x.shape width = weight.shape[1] state_len = width - 1 num_seqs = query_start_loc.numel() - 1 slots = state_indices.long() init = conv_state[slots].to(x.dtype) # (S, L, D) init = init * has_initial_state.view(-1, 1, 1).to(init.dtype) src = torch.cat([init.reshape(num_seqs * state_len, dim), x], dim=0) tap_idx, new_state_idx = _prefill_source_indices( query_start_loc, num_tokens, state_len, width ) w = weight.float() out = torch.zeros(num_tokens, dim, dtype=torch.float32, device=x.device) for k in range(width): out += src[tap_idx[:, k]].float() * w[:, k] if bias is not None: out += bias.float() conv_state[slots] = src[new_state_idx].to(conv_state.dtype) return out.to(x.dtype) def causal_conv1d_decode_torch( x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None, conv_state: torch.Tensor, state_indices: torch.Tensor, ) -> torch.Tensor: # padded rows (PAD_SLOT_ID = -1) are redirected to the null block 0 slots = state_indices.long().clamp_min(0) window = torch.cat([conv_state[slots].to(x.dtype), x[:, None, :]], dim=1) out = torch.einsum("nkd,dk->nd", window.float(), weight.float()) if bias is not None: out += bias.float() conv_state[slots] = window[:, 1:].to(conv_state.dtype) return out.to(x.dtype) # --------------------------------------------------------------------------- # Triton implementations # --------------------------------------------------------------------------- if HAS_TRITON: @triton.jit def _prefill_kernel( X, W, BIAS, STATE, SLOTS, HAS_INIT, QSL, SEQ_ID, Y, T, D, sx_t, sx_d, sw_d, sw_k, ss_b, ss_l, ss_d, sy_t, sy_d, K: tl.constexpr, HAS_BIAS: tl.constexpr, BLOCK_T: tl.constexpr, BLOCK_D: tl.constexpr, ): t = tl.program_id(0) * BLOCK_T + tl.arange(0, BLOCK_T) d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D) tm = t < T dm = d < D seq = tl.load(SEQ_ID + t, mask=tm, other=0) start = tl.load(QSL + seq, mask=tm, other=0) pos = t - start slot = tl.load(SLOTS + seq, mask=tm, other=0).to(tl.int64) init = tl.load(HAS_INIT + seq, mask=tm, other=0) != 0 acc = tl.zeros((BLOCK_T, BLOCK_D), dtype=tl.float32) for k in tl.static_range(K): p = pos + (k - (K - 1)) from_x = p >= 0 from_s = (p < 0) & init xv = tl.load( X + (t + (k - (K - 1)))[:, None].to(tl.int64) * sx_t + d[None, :] * sx_d, mask=(tm & from_x)[:, None] & dm[None, :], other=0.0, ).to(tl.float32) sv = tl.load( STATE + slot[:, None] * ss_b + (K - 1 + p)[:, None] * ss_l + d[None, :] * ss_d, mask=(tm & from_s)[:, None] & dm[None, :], other=0.0, ).to(tl.float32) w = tl.load(W + d * sw_d + k * sw_k, mask=dm, other=0.0).to(tl.float32) acc += (xv + sv) * w[None, :] if HAS_BIAS: acc += tl.load(BIAS + d, mask=dm, other=0.0).to(tl.float32)[None, :] tl.store( Y + t[:, None].to(tl.int64) * sy_t + d[None, :] * sy_d, acc.to(Y.dtype.element_ty), mask=tm[:, None] & dm[None, :], ) @triton.jit def _prefill_state_kernel( X, STATE, SLOTS, HAS_INIT, QSL, D, sx_t, sx_d, ss_b, ss_l, ss_d, L: tl.constexpr, L_PAD: tl.constexpr, BLOCK_D: tl.constexpr, ): s = tl.program_id(0) d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D) dm = d < D l = tl.arange(0, L_PAD) lm = l < L start = tl.load(QSL + s) length = tl.load(QSL + s + 1) - start slot = tl.load(SLOTS + s).to(tl.int64) init = tl.load(HAS_INIT + s) != 0 # new row l holds relative position q = length - L + l q = length - L + l from_x = q >= 0 xv = tl.load( X + (start + q)[:, None].to(tl.int64) * sx_t + d[None, :] * sx_d, mask=(lm & from_x)[:, None] & dm[None, :], other=0.0, ) sv = tl.load( STATE + slot * ss_b + (L + q)[:, None] * ss_l + d[None, :] * ss_d, mask=(lm & (q < 0) & init)[:, None] & dm[None, :], other=0.0, ) new = tl.where(from_x[:, None], xv, sv) # all loads above happen before the store: in-place update is safe tl.store( STATE + slot * ss_b + l[:, None] * ss_l + d[None, :] * ss_d, new.to(STATE.dtype.element_ty), mask=lm[:, None] & dm[None, :], ) @triton.jit def _decode_kernel( X, W, BIAS, STATE, SLOTS, Y, D, sx_n, sx_d, sw_d, sw_k, ss_b, ss_l, ss_d, sy_n, sy_d, L: tl.constexpr, L_PAD: tl.constexpr, HAS_BIAS: tl.constexpr, BLOCK_D: tl.constexpr, ): n = tl.program_id(0) d = tl.program_id(1) * BLOCK_D + tl.arange(0, BLOCK_D) dm = d < D l = tl.arange(0, L_PAD) lm = l < L slot = tl.load(SLOTS + n).to(tl.int64) slot = tl.where(slot < 0, 0, slot) # PAD_SLOT_ID -> null block base = STATE + slot * ss_b + d[None, :] * ss_d old = tl.load(base + l[:, None] * ss_l, mask=lm[:, None] & dm[None, :], other=0.0) nxt = tl.load( base + (l + 1)[:, None] * ss_l, mask=((l + 1) < L)[:, None] & dm[None, :], other=0.0, ) x = tl.load(X + n * sx_n + d * sx_d, mask=dm, other=0.0) w_state = tl.load( W + d[None, :] * sw_d + l[:, None] * sw_k, mask=lm[:, None] & dm[None, :], other=0.0, ).to(tl.float32) w_last = tl.load(W + d * sw_d + L * sw_k, mask=dm, other=0.0).to(tl.float32) acc = tl.sum(old.to(tl.float32) * w_state, axis=0) + x.to(tl.float32) * w_last if HAS_BIAS: acc += tl.load(BIAS + d, mask=dm, other=0.0).to(tl.float32) new = tl.where((l == L - 1)[:, None], x[None, :].to(old.dtype), nxt) tl.store(base + l[:, None] * ss_l, new, mask=lm[:, None] & dm[None, :]) tl.store(Y + n * sy_n + d * sy_d, acc.to(Y.dtype.element_ty), mask=dm) def causal_conv1d_prefill_triton( x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None, conv_state: torch.Tensor, query_start_loc: torch.Tensor, state_indices: torch.Tensor, has_initial_state: torch.Tensor, ) -> torch.Tensor: num_tokens, dim = x.shape width = weight.shape[1] state_len = width - 1 num_seqs = query_start_loc.numel() - 1 lens = query_start_loc[1:] - query_start_loc[:-1] seq_id = torch.repeat_interleave( torch.arange(num_seqs, device=x.device, dtype=torch.int32), lens, output_size=num_tokens, ) has_init = has_initial_state.to(torch.int8) out = torch.empty_like(x) BLOCK_T, BLOCK_D = 32, 64 grid = (triton.cdiv(num_tokens, BLOCK_T), triton.cdiv(dim, BLOCK_D)) _prefill_kernel[grid]( x, weight, bias, conv_state, state_indices, has_init, query_start_loc, seq_id, out, num_tokens, dim, *x.stride(), *weight.stride(), *conv_state.stride(), *out.stride(), K=width, HAS_BIAS=bias is not None, BLOCK_T=BLOCK_T, BLOCK_D=BLOCK_D, ) # the conv above read the old states; now overwrite them _prefill_state_kernel[(num_seqs, triton.cdiv(dim, 256))]( x, conv_state, state_indices, has_init, query_start_loc, dim, *x.stride(), *conv_state.stride(), L=state_len, L_PAD=triton.next_power_of_2(state_len), BLOCK_D=256, ) return out def causal_conv1d_decode_triton( x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None, conv_state: torch.Tensor, state_indices: torch.Tensor, ) -> torch.Tensor: num_rows, dim = x.shape state_len = weight.shape[1] - 1 out = torch.empty_like(x) BLOCK_D = 256 _decode_kernel[(num_rows, triton.cdiv(dim, BLOCK_D))]( x, weight, bias, conv_state, state_indices, out, dim, *x.stride(), *weight.stride(), *conv_state.stride(), *out.stride(), L=state_len, L_PAD=triton.next_power_of_2(state_len), HAS_BIAS=bias is not None, BLOCK_D=BLOCK_D, ) return out def causal_conv1d_prefill(*args, **kwargs) -> torch.Tensor: if use_triton(): return causal_conv1d_prefill_triton(*args, **kwargs) return causal_conv1d_prefill_torch(*args, **kwargs) def causal_conv1d_decode(*args, **kwargs) -> torch.Tensor: if use_triton(): return causal_conv1d_decode_triton(*args, **kwargs) return causal_conv1d_decode_torch(*args, **kwargs)