feat(kda): integrate KDA attention with tokamax backend and CP support - #1
Open
chiaotung97 wants to merge 4 commits into
Open
feat(kda): integrate KDA attention with tokamax backend and CP support#1chiaotung97 wants to merge 4 commits into
chiaotung97 wants to merge 4 commits into
Conversation
- Add KimiDeltaAttention layer (attention_kda.py) with QKV projections, ShortConvolution, gate/beta/output-gate projections - Add KDA kernel dispatch (kernels/kda/__init__.py) delegating to tokamax - Add tokamax backend adapter (kernels/kda/tokamax.py) with layout translation - Add CP utilities (cp_utils.py) for halo exchange and AG-CP support - Add KdaAttention config class (types.py) with kda_backend field - Add base.yml config entry for kda_backend - Add comprehensive unit tests (kda_attention_test.py) - Add KDA+CP support design doc (docs/design/kda_cp_support.md)
P0 fixes: - Replace all AG-CP/All-Gather CP references with CP (23 occurrences) - Remove tops/pallas-kernel references from base.yml and types.py - Add comment explaining tokamax's pallas_tpu implementation name P1 fixes: - Remove unused kda_backend parameter from chunk_kda and config - Update design doc scope to reflect one-time KDA+CP integration P2 fixes: - Replace assert statements with raise (NotImplementedError, ValueError, ImportError) - Fix misleading test name (test_kda_cp_no_load_balance_ok -> test_kda_no_cp_without_load_balance_ok)
- Fix test method name: test_kda_ag_cp_equivalence -> test_kda_cp_equivalence - Add warning when kda_lower_bound is set but safe_gate=False - Add ge=0 constraint on linear_conv_kernel_dim in types.py - Add field_validator for kda_lower_bound to reject NaN/Inf
Collaborator
Author
Unit Test Results30/30 passed on a 4-chip TPU v6e VM (113s). Test VM Setup# 1. Install Python 3.12
sudo apt-get update -qq && sudo apt-get install -y -qq python3.12 python3.12-venv
# 2. Install uv
pip install uv
# 3. Clone maxtext KDA branch
git clone --depth=1 --branch=feature_kda_integration \
https://github.com/antgroup/maxtext.git maxtext
# 4. Create venv + install maxtext TPU deps
cd maxtext
uv venv --python 3.12 --seed ../maxtext_venv
source ../maxtext_venv/bin/activate
uv pip install -e ".[tpu]"
# 5. Install tokamax from PR branch (required until openxla/tokamax#1103 is merged)
uv pip install git+https://github.com/antgroup/tokamax.git@antgroup/kda-pallas-kernel
Run Testssource ../maxtext_venv/bin/activate
cd ~/maxtext
python -m pytest tests/unit/kda_attention_test.py -vResultsEnvironment
Key Coverage
|
- Apply pyink auto-formatting (line-length=122, indent=2) - Fix design doc: Assert -> raise ImportError for CPContext check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR integrates KDA (Kimi Delta Attention) into MaxText with tokamax backend and context parallelism (CP) support.
KimiDeltaAttentionlayer with QKV/beta/gate projections and depthwise causal 1D convolution[B,T,H,D]↔[H,B,T,D]layout translationCPContext,shard_mapwrapping, and ppermute-based halo exchangeKdaAttention) with kernel dim, safe-gate, lower-bound, and LoRA controlsDependency: Requires openxla/tokamax#1103 to be merged into tokamax main branch first — until then, tokamax must be installed from the PR branch.
Motivation
KDA is a recurrent linear-attention operator that augments the standard Delta Rule with a learned gating mechanism and depthwise convolution for local dependency modeling. Integrating KDA into MaxText enables:
The integration follows the Megatron KDA reference and delegates kernel execution to tokamax's Pallas TPU implementation, keeping MaxText free of low-level kernel code.
Public API
KimiDeltaAttention(nnx.Module)chunk_kda(kernel entry point)halo_exchange_for_conv(CP utility)Configuration (
KdaAttention)linear_conv_kernel_dimint(≥0)40disablesuse_kda_loraboolFalseuse_kda_safe_gateboolFalsekda_lower_boundfloat0.0Implementation Details
Layer architecture (
layers/attention_kda.py)The
KimiDeltaAttentionforward pass follows a six-stage pipeline:ShortConvolution) with SiLU activation, modeling local (kernel_dim) token dependenciesg; gate activation (sigmoid fromA_log,dt_bias) is handled inside tokamaxchunk_kda→ tokamaxkimi_delta_attention(implementation="pallas_tpu")Delta Rule formulation:
tokamax backend adapter (
kernels/kda/tokamax.py)[B, T, H, D]to head-first tokamax layout[H, B, T, D]segment_idsdirectly as[B, T](tokamax accepts this natively — no per-batch offset needed)CPContextfor context-parallel executionContext parallelism (
utils/cp_utils.py)Two independent
jax.shard_mapinvocations provide per-op sharding:halo_exchange_for_convuses ppermute-based forward ring to fetchkernel_dim-1tokens from the left neighbor, enabling correct causal convolution at rank boundarieschunk_kdawith explicit partition specs so tokamax kernels (not auto-partitionable) receive correctly sharded tensorsCP metadata flow:
_inject_context_on_Tensures the T axis carries"context"sharding (overrides size-1 stripping)with_sharding_constraintapplies explicit pspecs to Q/K/V/G and beta before entering shard_mapCPContext(mesh, axis_name="context")is constructed outside shard_map and passed to tokamax, which derives per-rank chain fields internallyRuntime guards
CP + load_balanceraisesValueError— recurrent state depends on exact token order;DUAL_CHUNK_SWAPreorder breaks sequential dependencykda_lower_boundwithsafe_gate=Falseemits a warning (value ignored without clamping)Test Coverage
tests/unit/kda_attention_test.py(914 lines, 30 tests) covers:Naive KDA Reference
A pure-XLA recurrent reference implementation (
_naive_kda_recurrent) is embedded in the test suite. It implements the Delta Rule one token at a time with no chunking, providing an independent correctness baseline for the chunked tokamax kernel. Tests compare output against this reference at both FP32 and BF16.TPU Results
Environment:
Documentation
docs/design/kda_cp_support.mdcovers:Scope and Compatibility
ImportErroris raised with a clear message if tokamax is missinginitial_stateandoutput_final_stateare not yet supported, which only for inference (raiseNotImplementedError)Checklist
Co-authors
Co-authored-by: chiaotung97 qt533360@antgroup.com