stackformers 5.0.0rc8__tar.gz → 5.0.0rc11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/AGENTS.md +4 -0
  2. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/CHANGELOG.md +35 -0
  3. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/PKG-INFO +1 -1
  4. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/pyproject.toml +1 -1
  5. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/DEVLOG.md +99 -0
  6. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/__init__.py +9 -0
  7. stackformers-5.0.0rc11/stackformers/_projection_packing.py +72 -0
  8. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/README.md +51 -2
  9. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/__init__.py +7 -0
  10. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/cross_attn.py +70 -9
  11. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/layout.py +26 -4
  12. stackformers-5.0.0rc11/stackformers/attention/masking.py +73 -0
  13. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/ops.py +9 -4
  14. stackformers-5.0.0rc11/stackformers/attention/packed_cross_attn.py +193 -0
  15. stackformers-5.0.0rc11/stackformers/attention/packed_self_attn.py +158 -0
  16. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/protocols.py +18 -3
  17. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/self_attn.py +29 -7
  18. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/cross_attender.py +86 -18
  19. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/decoder.py +106 -25
  20. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/decoder_cache.py +52 -23
  21. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/encoder.py +6 -2
  22. stackformers-5.0.0rc11/stackformers/feedforward/DEVLOG.md +52 -0
  23. stackformers-5.0.0rc11/stackformers/feedforward/README.md +27 -0
  24. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/__init__.py +2 -0
  25. stackformers-5.0.0rc11/stackformers/feedforward/packed_swiglu.py +71 -0
  26. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/swiglu.py +8 -0
  27. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/layers.py +49 -15
  28. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/presets/README.md +27 -0
  29. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/presets/cross_attender.py +10 -2
  30. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/presets/decoder.py +13 -2
  31. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/presets/encoder.py +6 -2
  32. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/presets/variable_width_encoder.py +9 -4
  33. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_cross_attn.py +60 -1
  34. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_legacy_api.py +14 -3
  35. stackformers-5.0.0rc11/tests/attention/test_masking.py +69 -0
  36. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_ops.py +31 -0
  37. stackformers-5.0.0rc11/tests/attention/test_packed_cross_attn.py +155 -0
  38. stackformers-5.0.0rc11/tests/attention/test_packed_self_attn.py +140 -0
  39. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_self_attn.py +69 -0
  40. stackformers-5.0.0rc11/tests/feedforward/legacy_swiglu_4_6.json +47 -0
  41. stackformers-5.0.0rc11/tests/feedforward/test_packed_swiglu.py +130 -0
  42. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/presets/test_encoder.py +22 -0
  43. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/presets/test_variable_width_encoder.py +20 -0
  44. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_cross_attender.py +31 -0
  45. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_decoder.py +203 -0
  46. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_encoder.py +20 -0
  47. stackformers-5.0.0rc11/tests/test_projection_packing.py +82 -0
  48. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/uv.lock +1 -1
  49. stackformers-5.0.0rc8/stackformers/feedforward/DEVLOG.md +0 -27
  50. stackformers-5.0.0rc8/stackformers/feedforward/README.md +0 -13
  51. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/.claudeignore +0 -0
  52. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/.gitignore +0 -0
  53. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/.python-version +0 -0
  54. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/.vscode/settings.json +0 -0
  55. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/Justfile +0 -0
  56. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/LICENSE +0 -0
  57. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/PLAN.md +0 -0
  58. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/README.md +0 -0
  59. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/README.md +0 -0
  60. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/causal_language_model.py +0 -0
  61. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/encoder_decoder_onnxruntime.py +0 -0
  62. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/image_encoder.py +0 -0
  63. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/padded_and_packed.py +0 -0
  64. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/point_cloud_encoder.py +0 -0
  65. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/examples/subclassed_encoder.py +0 -0
  66. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/pyrefly.toml +0 -0
  67. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/pytest.ini +0 -0
  68. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/ruff.toml +0 -0
  69. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/run-remote-tests.sh +0 -0
  70. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/_result.py +0 -0
  71. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/bias.py +0 -0
  72. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/cache.py +0 -0
  73. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/cache_validation.py +0 -0
  74. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/cached.py +0 -0
  75. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/config.py +0 -0
  76. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/distance_bias.py +0 -0
  77. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/factory.py +0 -0
  78. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/attention/varlen_backend.py +0 -0
  79. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/config.py +0 -0
  80. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/config.py +0 -0
  81. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/factory.py +0 -0
  82. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/geglu.py +0 -0
  83. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/gelu.py +0 -0
  84. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/hardswish_glu.py +0 -0
  85. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/protocols.py +0 -0
  86. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/feedforward/relu_squared.py +0 -0
  87. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/README.md +0 -0
  88. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/config.py +0 -0
  89. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/head.py +0 -0
  90. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/head_cosine.py +0 -0
  91. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/masking.py +0 -0
  92. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/protocols.py +0 -0
  93. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/mlm/wrapper.py +0 -0
  94. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/norm/README.md +0 -0
  95. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/norm/__init__.py +0 -0
  96. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/norm/config.py +0 -0
  97. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/norm/factory.py +0 -0
  98. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/norm/protocols.py +0 -0
  99. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/README.md +0 -0
  100. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/__init__.py +0 -0
  101. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/config.py +0 -0
  102. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/factory.py +0 -0
  103. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/learned.py +0 -0
  104. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/none.py +0 -0
  105. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/protocols.py +0 -0
  106. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/rope1d.py +0 -0
  107. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/rope2d.py +0 -0
  108. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/rope_nd.py +0 -0
  109. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/positional/validation.py +0 -0
  110. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/presets/__init__.py +0 -0
  111. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/py.typed +0 -0
  112. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/result/README.md +0 -0
  113. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/result/__init__.py +0 -0
  114. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/stackformers/sequence.py +0 -0
  115. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/__init__.py +0 -0
  116. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/__init__.py +0 -0
  117. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/legacy_api_rc1.json +0 -0
  118. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_contracts.py +0 -0
  119. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_cross_attn_cache.py +0 -0
  120. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_distance_bias.py +0 -0
  121. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_empty_rows.py +0 -0
  122. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_geometry.py +0 -0
  123. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_kernels.py +0 -0
  124. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_sdpa_export.py +0 -0
  125. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/attention/test_varlen_backend.py +0 -0
  126. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/conftest.py +0 -0
  127. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/export_utils.py +0 -0
  128. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/feedforward/__init__.py +0 -0
  129. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/feedforward/test_geglu.py +0 -0
  130. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/feedforward/test_gelu.py +0 -0
  131. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/feedforward/test_hardswish_glu.py +0 -0
  132. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/feedforward/test_relu_squared.py +0 -0
  133. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/feedforward/test_swiglu.py +0 -0
  134. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/mlm/__init__.py +0 -0
  135. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/mlm/test_empty_selection.py +0 -0
  136. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/mlm/test_head.py +0 -0
  137. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/mlm/test_head_cosine.py +0 -0
  138. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/mlm/test_masking.py +0 -0
  139. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/mlm/test_wrapper.py +0 -0
  140. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/norm_topology_helpers.py +0 -0
  141. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/positional/__init__.py +0 -0
  142. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/positional/test_cacheable.py +0 -0
  143. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/positional/test_learned_pos.py +0 -0
  144. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/positional/test_rope.py +0 -0
  145. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/positional/test_rope_nd.py +0 -0
  146. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/presets/__init__.py +0 -0
  147. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/presets/test_cross_attender.py +0 -0
  148. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/presets/test_decoder.py +0 -0
  149. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_core_results.py +0 -0
  150. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_decoder_cache.py +0 -0
  151. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_encoder_decoder_example.py +0 -0
  152. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_examples.py +0 -0
  153. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_layers.py +0 -0
  154. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_norm.py +0 -0
  155. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_public_api.py +0 -0
  156. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_result.py +0 -0
  157. {stackformers-5.0.0rc8 → stackformers-5.0.0rc11}/tests/test_sequence.py +0 -0
@@ -31,6 +31,10 @@ just check # formatting check, lint, types, and tests
31
31
  - Keep one concept per file; split files that cannot be described in one sentence.
32
32
  - Annotate tensor arguments with jaxtyping shape strings using the dimension vocabulary below.
33
33
  - Type collaborators accepted by `__init__` as protocols rather than concrete implementations.
34
+ - Prefer named intermediate values over nested transformation calls or functional pipelines.
35
+ Separate normalization, attention/feed-forward computation, output normalization, and residual
36
+ addition into readable steps so intermediate values are easy to inspect while debugging.
37
+ Keep trivial expressions inline when naming them would add no meaning.
34
38
 
35
39
  ## Python structured records
36
40
 
@@ -6,6 +6,41 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
6
6
  adheres to [Semantic Versioning](https://semver.org/): MAJOR for breaking public API changes,
7
7
  MINOR for backwards-compatible features, PATCH for bug fixes and internal changes.
8
8
 
9
+ ## [5.0.0rc11]
10
+
11
+ ### New Features
12
+
13
+ - Add `to_packed()` to self-attention, cross-attention and SwiGLU for opt-in packed
14
+ QKV, context KV, and gate/value projections. GQA/MQA retain explicit Q/KV widths.
15
+ - Preserve ordinary forward paths and checkpoint names. Load old checkpoints normally,
16
+ then convert; `packed.unpack()` restores an independently owned ordinary module.
17
+ Convert before creating an optimizer; optimizer state and parameter aliases are not migrated.
18
+
19
+ ## [5.0.0rc10]
20
+
21
+ ### Developers
22
+
23
+ - Expand normalization, attention, feed-forward, and residual branches into named intermediate
24
+ values across transformer layers, decoders, cross-attenders, and cached decoder executors.
25
+ Preserve operation order while making intermediate values easier to inspect when debugging.
26
+ - Record the preference for named transformation steps in repository guidance.
27
+
28
+ ## [5.0.0rc9]
29
+
30
+ ### New Features
31
+
32
+ - Add per-call `self_attn_mask` to encoders and decoders: select initialization defaults,
33
+ global causal or bidirectional attention, or explicit boolean `(n, n)` visibility.
34
+ - Add boolean `(n, s)` `cross_attn_mask` to decoders and cross-attenders. Runtime masks
35
+ preserve padding and packed document isolation; arbitrary masks use padded SDPA fallback.
36
+
37
+ ### Developers
38
+
39
+ - Extend attention protocols and layer forward contracts with keyword-only visibility
40
+ arguments. Custom layers must forward these keywords; custom attention implementations
41
+ need to accept them when an override is requested. Existing built-in configs and checkpoints
42
+ remain compatible. Cached generation retains its existing causal API.
43
+
9
44
  ## [5.0.0rc8]
10
45
 
11
46
  ### New Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stackformers
3
- Version: 5.0.0rc8
3
+ Version: 5.0.0rc11
4
4
  Summary: Typed, composable, SOLID transformer library for PyTorch
5
5
  Project-URL: Homepage, https://github.com/Red-Eyed/stackformers
6
6
  Project-URL: Repository, https://github.com/Red-Eyed/stackformers
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "stackformers"
7
- version = "5.0.0rc8"
7
+ version = "5.0.0rc11"
8
8
  description = "Typed, composable, SOLID transformer library for PyTorch"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -1,5 +1,104 @@
1
1
  # Transformer model development log
2
2
 
3
+ ## 2026-10-18 — Opt-in projection packing (5.0.0rc11)
4
+
5
+ ### Observation
6
+
7
+ Self-attention projects the same input three times; cross-attention projects its context
8
+ twice; SwiGLU projects gate and value independently. QuantSmith's isolated QKV measurements
9
+ suggested packing could reduce integer-projection overhead, but did not establish complete-block gains.
10
+
11
+ ### Decision
12
+
13
+ Add `to_packed()` to the existing attention and SwiGLU classes. Preserve their original forward
14
+ implementations, parameter names, factory dispatch, and cache wrappers. Put experimental
15
+ `PackedSelfAttention`, `PackedCrossAttention`, and `PackedSwiGLU` in separate modules, using
16
+ ordinary `nn.Linear` and explicit split widths. No new protocol or abstract hierarchy is needed.
17
+
18
+ Load old checkpoints into the original classes, then convert. Conversion copies parameters,
19
+ preserves dtype/device, frozen parameters and training modes, and leaves the source untouched.
20
+ `unpack()` returns an independently owned original module with its original checkpoint names.
21
+ Projection groups must share trainability. Convert before creating an optimizer; optimizer
22
+ state, existing gradients, hooks and parameter aliases are not migrated. Sequence packing and
23
+ projection packing are independent: both projection layouts accept padded and packed inputs.
24
+
25
+ ### Verified
26
+
27
+ `just check` passes: 1,614 tests passed, 21 skipped, 172 expected failures, and 111 optional-case
28
+ unexpected passes. New checks cover forward and gradient parity, MHA/GQA/MQA, masks, learned
29
+ bias, local visibility, checkpoint serialization, frozen/tied parameters, training dropout,
30
+ and fresh optimizer steps. Released attention references from 5.0.0rc1 retain exact checkpoint
31
+ keys and output/input-gradient behavior after conversion. A SwiGLU reference captured from
32
+ the installed 4.6.0 wheel verifies the old checkpoint transition independently of current code.
33
+
34
+ All 12 attention dynamic-export tests pass in QuantSmith's PyTorch 2.14 environment. Four
35
+ PyTorch 2.11 GQA cases remain expected failures only after confirming that the ordinary
36
+ implementation encounters the same symbolic stride-guard error. The other new export cases pass.
37
+
38
+ ### Complete-block ORT CPU experiment
39
+
40
+ QuantSmith's existing exporter, integer lowering, profiler and timing runner were reused with
41
+ an experiment adapter under ignored `work_dir/projection_packing/`. This run uses the local
42
+ 5.0.0rc11 source checkout (file hashes recorded in `source.json`), PyTorch 2.14.0, ORT 1.30.0,
43
+ ONNX 1.23.0, arm64 macOS 27.0.1, batch 1, width 768 and 12 heads. The causal encoder has one
44
+ RoPE/RMSNorm/SwiGLU layer and a final norm; cross-attention reprojects a 128-token context.
45
+ Neither workload uses a KV cache. Weights and inputs are identical across projection layouts.
46
+
47
+ Each candidate uses independent native opset-18/21 exports with dynamic sequence axes,
48
+ CPUExecutionProvider, ORT_ENABLE_ALL, one intra/inter-op thread, 10 warmups and three
49
+ alternating-order sweeps of 300 calls. Profiling uses a separate 10-call session. Initialization
50
+ and weight packing are excluded. Values below are opset-18 medians of repetition medians.
51
+
52
+ | Block/layout | Query tokens | FP32 µs | Native dynamic INT8 µs |
53
+ |---|---:|---:|---:|
54
+ | Encoder, unchanged | 1 | 393.90 | 137.10 |
55
+ | Encoder, attention packed | 1 | 389.25 | 125.71 |
56
+ | Encoder, SwiGLU packed | 1 | 391.21 | 120.79 |
57
+ | Encoder, both packed | 1 | 388.06 | 106.85 |
58
+ | Encoder, unchanged | 128 | 1758.96 | 3672.31 |
59
+ | Encoder, attention packed | 128 | 1780.42 | 2950.37 |
60
+ | Encoder, SwiGLU packed | 128 | 1897.25 | 2353.94 |
61
+ | Encoder, both packed | 128 | 1831.33 | 1637.06 |
62
+ | Cross-attention, unchanged | 1 | 241.56 | 727.67 |
63
+ | Cross-attention, KV packed | 1 | 260.29 | 263.67 |
64
+ | Cross-attention, unchanged | 128 | 590.44 | 1135.12 |
65
+ | Cross-attention, KV packed | 128 | 610.44 | 672.44 |
66
+
67
+ Combined packing improves the encoder's native INT8 path by 1.28× at one token and 2.24×
68
+ at 128 tokens, reducing integer projections from seven to four. FP32 improvements are not
69
+ consistent: combined packing is about 4% slower at 128 tokens, and packing context KV also
70
+ regresses FP32 here. Native INT8 cross-attention remains slower than its FP32 baseline despite
71
+ its improvement from packing. Keep all layouts explicit rather than changing defaults.
72
+
73
+ All 144 graph variants execute at query/context pairs (1,1), (2,7), (7,2), and (31,13):
74
+ 576 graph/length validations. FP32 matches PyTorch; native dynamic and four fixed-grid integer
75
+ paths return finite FP32 outputs with correct shapes. All 72 graph pairs have identical hashes
76
+ between the one-token and 128-token measurements. Only FP32/native dynamic candidates are
77
+ timed in this run; fixed-grid integer paths are correctness diagnostics.
78
+
79
+ Native INT8 relative MSE against unchanged FP32 is about 0.000033 for the combined one-token
80
+ encoder and 0.000018 at 128 tokens. These synthetic errors are not task-accuracy budgets.
81
+
82
+ Raw reports, graphs, profiles, the generated adapter, and source fingerprints remain in
83
+ `work_dir/projection_packing/`. Re-run the adapter from that directory with the adjacent
84
+ QuantSmith checkout and its locked example dependencies:
85
+
86
+ ```sh
87
+ PYTHONPATH=../..:../../../QuantSmith \
88
+ uv run --locked --group examples --project ../../../QuantSmith benchmark.py
89
+ ```
90
+
91
+ `environment.json` reports installed distribution metadata (including Stackformers 4.6.0 in
92
+ QuantSmith's pinned environment); `source.json` identifies the actual selected local 5.0.0rc11
93
+ code and its hashes. The QuantSmith dependency pin was not changed.
94
+
95
+ ### Unproven
96
+
97
+ CUDA execution, trained-model task quality, optimizer-state migration, and cached execution of
98
+ the packed variants have not been established. Existing cache wrappers continue to use ordinary
99
+ attention. Quantization and workload-dependent precision selection remain deployment concerns.
100
+
101
+
3
102
  ## 2026-09-26 — Precise cache and vendor input contracts (5.0.0rc7)
4
103
 
5
104
  ### Observation
@@ -18,12 +18,15 @@ from stackformers.attention import (
18
18
  DistanceBiasConfig,
19
19
  NoAttnBias,
20
20
  NoAttnBiasConfig,
21
+ PackedCrossAttention,
22
+ PackedSelfAttention,
21
23
  RelativeDistanceBias,
22
24
  SelfAttention,
23
25
  SelfAttentionConfig,
24
26
  SelfAttn,
25
27
  build_attn_bias,
26
28
  )
29
+ from stackformers.attention.masking import CrossAttentionMask, SelfAttentionMask
27
30
  from stackformers.config import DecoderConfig, EncoderConfig, LayerConfig
28
31
  from stackformers.cross_attender import (
29
32
  CrossAttenderLayer,
@@ -52,6 +55,7 @@ from stackformers.feedforward import (
52
55
  GELUConfig,
53
56
  HardSwishGLU,
54
57
  HardSwishGLUConfig,
58
+ PackedSwiGLU,
55
59
  ReluSquaredConfig,
56
60
  ReluSquaredFF,
57
61
  SwiGLU,
@@ -131,6 +135,8 @@ from stackformers.sequence import (
131
135
  )
132
136
 
133
137
  __all__ = [
138
+ "SelfAttentionMask",
139
+ "CrossAttentionMask",
134
140
  "__version__",
135
141
  "Result",
136
142
  "Ok",
@@ -200,12 +206,15 @@ __all__ = [
200
206
  "RotaryEmbeddingND",
201
207
  "LearnedPosEncoding",
202
208
  # attention
209
+ "PackedSelfAttention",
210
+ "PackedCrossAttention",
203
211
  "SelfAttention",
204
212
  "CrossAttention",
205
213
  "NoAttnBias",
206
214
  "RelativeDistanceBias",
207
215
  # feedforward
208
216
  "HardSwishGLU",
217
+ "PackedSwiGLU",
209
218
  "SwiGLU",
210
219
  "GEGLU",
211
220
  "GELUFFN",
@@ -0,0 +1,72 @@
1
+ """Owned weight conversion between separate and packed projection representations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import torch
8
+
9
+ if TYPE_CHECKING:
10
+ import torch.nn as nn
11
+ from torch import Tensor
12
+
13
+
14
+ def _load_owned_state(
15
+ source: nn.Module,
16
+ target: nn.Module,
17
+ state: dict[str, Tensor],
18
+ trainable: dict[str, bool],
19
+ ) -> None:
20
+ """Restore weights, frozen parameters, and individual module training modes."""
21
+ target.load_state_dict(state, assign=True)
22
+ for name, parameter in target.named_parameters():
23
+ parameter.requires_grad_(trainable[name])
24
+ source_modes = {name: module.training for name, module in source.named_modules()}
25
+ for name, module in target.named_modules():
26
+ module.training = source_modes.get(name, source.training)
27
+
28
+
29
+ def load_packed_state(
30
+ source: nn.Module, target: nn.Module, separate: tuple[str, ...], packed: str
31
+ ) -> None:
32
+ """Copy weights into a new layout; reject incompatible frozen projection groups.
33
+
34
+ Parameter identities, existing gradients, optimizer state, and hooks are not transferred.
35
+ Convert before constructing an optimizer or loading its state.
36
+ """
37
+ trainable = {
38
+ name: parameter.requires_grad
39
+ for name, parameter in source.named_parameters(remove_duplicate=False)
40
+ }
41
+ flags = {trainable[name] for name in separate}
42
+ if len(flags) != 1:
43
+ raise ValueError("packed projections must share requires_grad")
44
+ source_state = source.state_dict()
45
+ state = {name: value.clone() for name, value in source_state.items() if name not in separate}
46
+ state[packed] = torch.cat([source_state[name] for name in separate], dim=0)
47
+ for name in separate:
48
+ del trainable[name]
49
+ trainable[packed] = flags.pop()
50
+ _load_owned_state(source, target, state, trainable)
51
+
52
+
53
+ def load_unpacked_state(
54
+ source: nn.Module,
55
+ target: nn.Module,
56
+ packed: str,
57
+ separate: tuple[str, ...],
58
+ ) -> None:
59
+ """Copy packed rows back to independently owned, checkpoint-compatible parameters."""
60
+ source_state = source.state_dict()
61
+ state = {name: value.clone() for name, value in source_state.items() if name != packed}
62
+ widths = tuple(target.get_parameter(name).shape[0] for name in separate)
63
+ chunks = source_state[packed].split(widths, dim=0)
64
+ trainable = {
65
+ name: parameter.requires_grad
66
+ for name, parameter in source.named_parameters(remove_duplicate=False)
67
+ }
68
+ flag = trainable.pop(packed)
69
+ for name, value in zip(separate, chunks, strict=True):
70
+ state[name] = value.clone()
71
+ trainable[name] = flag
72
+ _load_owned_state(source, target, state, trainable)
@@ -6,7 +6,24 @@ Multi-head self-attention and cross-attention.
6
6
 
7
7
  **Two configs, two modules.** `SelfAttentionConfig` and `CrossAttentionConfig` are separate types because their parameter sets differ: self-attention has `causal` and `window_size`; cross-attention has neither.
8
8
 
9
- **Static vs runtime dispatch.** The attention *type* (global vs sliding-window) is determined at construction time via `window_size: int | None` in `SelfAttentionConfig`. The *backend* (padded vs packed) is determined at runtime: `SelfAttention.forward` and `CrossAttention.forward` dispatch on `SequenceInput` via `match`. This means one model handles both training (packed) and inference (padded) without swapping classes.
9
+ **Defaults vs per-call visibility.** `SelfAttentionConfig.causal` and `window_size` set
10
+ initialization defaults. `self_attn_mask="default"` preserves both; `"causal"` selects global
11
+ causal attention and `"bidirectional"` selects global bidirectional attention. A boolean
12
+ `(n, n)` tensor supplies the full visibility pattern instead. All explicit choices replace
13
+ configured causal/window restrictions without mutating config or parameters. Additive learned
14
+ attention biases still apply. The backend remains a runtime layout decision: padded inputs
15
+ use SDPA and packed inputs try varlen attention.
16
+
17
+ **Mask ownership.** `masking.py` owns the public mask types, validation, and mode resolution;
18
+ layers, stacks, and presets only forward the keyword arguments. `SelfAttention` accepts
19
+ `self_attn_mask`; `CrossAttention` accepts an optional boolean `cross_attn_mask` of shape
20
+ `(n, s)`. True means allowed. Pair masks are shared across batch entries and heads, must be
21
+ on the input device, and combine with key validity. Fully excluded attention rows return
22
+ zero. Padding and document isolation cannot be overridden. With packed inputs, `n` and `s`
23
+ are the query/context `max_seqlen` values and masks apply independently in local document
24
+ coordinates. Arbitrary pair masks deliberately bypass varlen and use padded SDPA; symbolic
25
+ causal/bidirectional choices retain the varlen route. This keeps common training modes from
26
+ allocating a dense pair mask on the packed fast path.
10
27
 
11
28
  **Kernel ops in `ops.py`.** All low-level attention math lives in `attention/ops.py`: mask builders, `padded_sdpa`, the packed↔padded scatter/gather helpers, and `packed_attn_or_fallback`. The modules stay thin dispatchers.
12
29
 
@@ -34,8 +51,40 @@ decoder, preset, and positional classes contain no cache-specific methods.
34
51
 
35
52
  **Why not `flex_attention`.** It fuses the bias into the kernel and would make it O(n) instead of O(n²) — attempted, and parked on the `flex-attention` branch. It needs `dim_head >= 16`; its `score_mod` must lower as a *pointwise* subgraph, which forbids both a `vector_norm` over coordinates and a sum over shells; a captured tensor requiring grad may be indexed exactly once, which forbids unrolling that sum instead; called eagerly it is unfused and catastrophic (measured 64 s/step at n=2048, OOM at n=4096, against ~40 ms for SDPA), so it is viable only inside `torch.compile`; and under `torch.compile` with *dynamic* shapes it bails back to SDPA anyway. With node counts that vary per batch, the fused kernel would rarely be the one that runs.
36
53
 
54
+ ## Packed projection experiments
55
+
56
+ Ordinary attention keeps its original forward path and checkpoint names. Call
57
+ `attention.to_packed()` to create an independent `PackedSelfAttention` or
58
+ `PackedCrossAttention`. These optional modules combine Q/K/V or context K/V with
59
+ `nn.Linear` and explicit splits; GQA/MQA retain unequal query and KV widths.
60
+ They support both padded and packed sequence inputs. No new protocol or base class is required.
61
+
62
+ ```python
63
+ attention.load_state_dict(old_checkpoint)
64
+ packed = attention.to_packed()
65
+ output = packed(sequence)
66
+ ordinary = packed.unpack()
67
+ ordinary_checkpoint = ordinary.state_dict()
68
+ ```
69
+
70
+ Convert after loading ordinary weights and before creating an optimizer. Conversion owns
71
+ new parameters, preserves dtype/device, frozen parameters and training modes, and leaves
72
+ the source untouched. Packing requires all projections in a group to share `requires_grad`.
73
+ Optimizer state, existing gradients, hooks and parameter aliases are not migrated.
74
+ `unpack()` restores ordinary checkpoint names; packed checkpoints load into their matching
75
+ packed class. Configs, factories, presets and cache wrappers retain their existing behavior.
76
+ Use ordinary attention with the existing cache wrappers.
77
+
78
+ Keep another experimental projection layout in its own module, with explicit conversion
79
+ and parity tests against ordinary attention. Measure complete blocks before selecting a
80
+ layout: fewer projections do not guarantee faster FP32 or integer inference. Quantization
81
+ and workload-dependent precision selection belong in deployment tooling.
82
+
37
83
  ## Extending
38
84
 
39
- To add a new attention variant, create a new `nn.Module` that satisfies the `SelfAttn` or `CrossAttn` protocol. No kernel registration or factory changes required.
85
+ To add a new attention variant, create a new `nn.Module` that satisfies the `SelfAttn` or
86
+ `CrossAttn` protocol, including its keyword-only visibility argument. No kernel registration
87
+ or factory changes are required. Default calls preserve legacy attention collaborator calls;
88
+ using an override requires the collaborator to implement the updated protocol.
40
89
 
41
90
  To add a new attention bias, write an `nn.Module` satisfying `AttnBias` (take `PaddedInput`, return a broadcastable `(b, h, n, s)` tensor or `None`), give it a config with a `kind` discriminator, join it to the `AttnBiasConfig` union, and add one `match` arm to `build_attn_bias`.
@@ -15,6 +15,9 @@ from stackformers.attention.config import (
15
15
  from stackformers.attention.cross_attn import CrossAttention
16
16
  from stackformers.attention.distance_bias import RelativeDistanceBias
17
17
  from stackformers.attention.factory import build_attn_bias
18
+ from stackformers.attention.masking import CrossAttentionMask, SelfAttentionMask
19
+ from stackformers.attention.packed_cross_attn import PackedCrossAttention
20
+ from stackformers.attention.packed_self_attn import PackedSelfAttention
18
21
  from stackformers.attention.protocols import (
19
22
  AttnBias,
20
23
  CrossAttn,
@@ -23,6 +26,10 @@ from stackformers.attention.protocols import (
23
26
  from stackformers.attention.self_attn import SelfAttention
24
27
 
25
28
  __all__ = [
29
+ "PackedCrossAttention",
30
+ "PackedSelfAttention",
31
+ "SelfAttentionMask",
32
+ "CrossAttentionMask",
26
33
  "SelfAttentionConfig",
27
34
  "CrossAttentionConfig",
28
35
  "AttnBiasConfig",
@@ -9,11 +9,13 @@ from typing_extensions import override
9
9
 
10
10
  from stackformers._result import unwrap_or_raise
11
11
  from stackformers.attention.layout import matching_layouts
12
+ from stackformers.attention.masking import CrossAttentionMask, validate_cross_mask
12
13
  from stackformers.attention.ops import packed_attn_or_fallback, padded_sdpa
13
14
  from stackformers.sequence import PackedInput, PackedSequence, PaddedInput, SequenceInput
14
15
 
15
16
  if TYPE_CHECKING:
16
17
  from stackformers.attention.config import CrossAttentionConfig
18
+ from stackformers.attention.packed_cross_attn import PackedCrossAttention
17
19
  from stackformers.positional.protocols import PosEncoding
18
20
 
19
21
 
@@ -39,7 +41,13 @@ class CrossAttention(nn.Module):
39
41
  self.k_norm: nn.Module = nn.RMSNorm(dh) if config.qk_norm else nn.Identity()
40
42
  nn.init.normal_(self.to_out.weight, std=0.02)
41
43
 
42
- def _forward_padded(self, x_input: PaddedInput, ctx_input: PaddedInput) -> Tensor:
44
+ def _forward_padded(
45
+ self,
46
+ x_input: PaddedInput,
47
+ ctx_input: PaddedInput,
48
+ *,
49
+ cross_attn_mask: CrossAttentionMask = None,
50
+ ) -> Tensor:
43
51
  cfg = self.config
44
52
  h, kv_h, groups = cfg.heads, cfg.effective_kv_heads, cfg.groups
45
53
  x, context = x_input.x, ctx_input.x
@@ -52,11 +60,29 @@ class CrossAttention(nn.Module):
52
60
  q, k = self.pos_encoding.forward_padded(
53
61
  q, k, x_input.abs_positions, ctx_input.abs_positions
54
62
  )
55
- out = padded_sdpa(q, k, v, ctx_input.mask, causal=False, window_size=None, bias=None)
63
+ allowed = unwrap_or_raise(
64
+ validate_cross_mask(cross_attn_mask, x.shape[1], context.shape[1], x.device)
65
+ )
66
+ out = padded_sdpa(
67
+ q,
68
+ k,
69
+ v,
70
+ ctx_input.mask,
71
+ causal=False,
72
+ window_size=None,
73
+ bias=None,
74
+ allowed_pairs=allowed,
75
+ )
56
76
  projected: Tensor = self.dropout(self.to_out(rearrange(out, "b h n d -> b n (h d)")))
57
77
  return projected * x_input.mask.unsqueeze(-1)
58
78
 
59
- def _forward_packed(self, x_input: PackedInput, ctx_input: PackedInput) -> Tensor:
79
+ def _forward_packed(
80
+ self,
81
+ x_input: PackedInput,
82
+ ctx_input: PackedInput,
83
+ *,
84
+ cross_attn_mask: CrossAttentionMask = None,
85
+ ) -> Tensor:
60
86
  cfg = self.config
61
87
  h, kv_h, groups = cfg.heads, cfg.effective_kv_heads, cfg.groups
62
88
  x, context = x_input.x, ctx_input.x
@@ -71,30 +97,65 @@ class CrossAttention(nn.Module):
71
97
  )
72
98
  x_seq = PackedSequence(cu_seqlens=x_input.cu_seqlens, max_seqlen=x_input.max_seqlen)
73
99
  ctx_seq = PackedSequence(cu_seqlens=ctx_input.cu_seqlens, max_seqlen=ctx_input.max_seqlen)
100
+ allowed = unwrap_or_raise(
101
+ validate_cross_mask(cross_attn_mask, x_input.max_seqlen, ctx_input.max_seqlen, x.device)
102
+ )
74
103
  out = packed_attn_or_fallback(
75
- q, k, v, x_seq, ctx_seq, causal=False, window_size=None, bias=None
104
+ q,
105
+ k,
106
+ v,
107
+ x_seq,
108
+ ctx_seq,
109
+ causal=False,
110
+ window_size=None,
111
+ bias=None,
112
+ allowed_pairs=allowed,
76
113
  )
77
114
  projected: Tensor = self.dropout(self.to_out(rearrange(out, "nt h d -> nt (h d)")))
78
115
  return projected
79
116
 
80
117
  @overload
81
- def forward(self, x_input: PaddedInput, ctx_input: PaddedInput) -> Tensor:
118
+ def forward(
119
+ self,
120
+ x_input: PaddedInput,
121
+ ctx_input: PaddedInput,
122
+ *,
123
+ cross_attn_mask: CrossAttentionMask = None,
124
+ ) -> Tensor:
82
125
  """Attend between padded inputs with independently sized sequence axes."""
83
126
  ...
84
127
 
85
128
  @overload
86
- def forward(self, x_input: PackedInput, ctx_input: PackedInput) -> Tensor:
129
+ def forward(
130
+ self,
131
+ x_input: PackedInput,
132
+ ctx_input: PackedInput,
133
+ *,
134
+ cross_attn_mask: CrossAttentionMask = None,
135
+ ) -> Tensor:
87
136
  """Attend between packed inputs with matching document counts."""
88
137
  ...
89
138
 
90
139
  @override
91
- def forward(self, x_input: SequenceInput, ctx_input: SequenceInput) -> Tensor:
140
+ def forward(
141
+ self,
142
+ x_input: SequenceInput,
143
+ ctx_input: SequenceInput,
144
+ *,
145
+ cross_attn_mask: CrossAttentionMask = None,
146
+ ) -> Tensor:
92
147
  """Attend within one shared layout; raise ValueError for mixed layouts."""
93
148
  match unwrap_or_raise(matching_layouts(x_input, ctx_input)):
94
149
  case PaddedInput() as queries, PaddedInput() as context:
95
- return self._forward_padded(queries, context)
150
+ return self._forward_padded(queries, context, cross_attn_mask=cross_attn_mask)
96
151
  case PackedInput() as queries, PackedInput() as context:
97
- return self._forward_packed(queries, context)
152
+ return self._forward_packed(queries, context, cross_attn_mask=cross_attn_mask)
153
+
154
+ def to_packed(self) -> PackedCrossAttention:
155
+ """Copy weights into packed context KV projections before creating an optimizer."""
156
+ from stackformers.attention.packed_cross_attn import PackedCrossAttention
157
+
158
+ return PackedCrossAttention.from_unpacked(self)
98
159
 
99
160
  if TYPE_CHECKING:
100
161
  # Preserve nn.Module's hook machinery at runtime while exposing the
@@ -3,7 +3,8 @@
3
3
  from torch import Tensor
4
4
 
5
5
  from stackformers._result import unwrap_or_raise
6
- from stackformers.attention.protocols import CrossAttn
6
+ from stackformers.attention.masking import CrossAttentionMask, SelfAttentionMask
7
+ from stackformers.attention.protocols import CrossAttn, SelfAttn
7
8
  from stackformers.result import Err, Ok, Result
8
9
  from stackformers.sequence import PackedInput, PaddedInput, SequenceInput
9
10
 
@@ -22,11 +23,32 @@ def matching_layouts(
22
23
 
23
24
 
24
25
  def call_cross_attention(
25
- attention: CrossAttn, queries: SequenceInput, context: SequenceInput
26
+ attention: CrossAttn,
27
+ queries: SequenceInput,
28
+ context: SequenceInput,
29
+ *,
30
+ cross_attn_mask: CrossAttentionMask = None,
26
31
  ) -> Tensor:
27
32
  """Adapt the layout result to the established tensor/ValueError call contract."""
28
33
  match unwrap_or_raise(matching_layouts(queries, context)):
29
34
  case PaddedInput() as padded_queries, PaddedInput() as padded_context:
30
- return attention(padded_queries, padded_context)
35
+ if cross_attn_mask is None:
36
+ return attention(padded_queries, padded_context)
37
+ return attention(padded_queries, padded_context, cross_attn_mask=cross_attn_mask)
31
38
  case PackedInput() as packed_queries, PackedInput() as packed_context:
32
- return attention(packed_queries, packed_context)
39
+ if cross_attn_mask is None:
40
+ return attention(packed_queries, packed_context)
41
+ return attention(packed_queries, packed_context, cross_attn_mask=cross_attn_mask)
42
+
43
+
44
+ def call_self_attention(
45
+ attention: SelfAttn, input: SequenceInput, *, self_attn_mask: SelfAttentionMask = "default"
46
+ ) -> Tensor:
47
+ """Preserve legacy collaborator calls when no visibility override was requested."""
48
+ match self_attn_mask:
49
+ case Tensor():
50
+ return attention(input, self_attn_mask=self_attn_mask)
51
+ case "default":
52
+ return attention(input)
53
+ case _:
54
+ return attention(input, self_attn_mask=self_attn_mask)
@@ -0,0 +1,73 @@
1
+ """Per-call attention visibility, independent of padding and sequence boundaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, TypeAlias, assert_never
6
+
7
+ import torch
8
+ from jaxtyping import Bool
9
+ from torch import Tensor
10
+
11
+ from stackformers.result import Err, Ok, Result
12
+
13
+ SelfAttentionMask: TypeAlias = Literal["default", "causal", "bidirectional"] | Bool[Tensor, "n n"]
14
+ CrossAttentionMask: TypeAlias = Bool[Tensor, "n s"] | None
15
+
16
+
17
+ def valid_pair_mask(
18
+ mask: Tensor, n: int, s: int, device: torch.device
19
+ ) -> Result[Tensor, TypeError | ValueError]:
20
+ """Admit a shared boolean query/key mask without inspecting tensor values."""
21
+ if mask.dtype != torch.bool:
22
+ return Err(TypeError("attention mask must have boolean dtype (True means allowed)"))
23
+ if mask.ndim != 2 or mask.shape != (n, s):
24
+ return Err(
25
+ ValueError(f"attention mask must have shape ({n}, {s}), got {tuple(mask.shape)}")
26
+ )
27
+ if mask.device != device:
28
+ return Err(ValueError("attention mask must be on the same device as the input"))
29
+ return Ok(mask)
30
+
31
+
32
+ def resolve_self_mask(
33
+ mask: SelfAttentionMask,
34
+ causal: bool,
35
+ window_size: int | None,
36
+ n: int,
37
+ device: torch.device,
38
+ ) -> Result[tuple[bool, int | None, Tensor | None], TypeError | ValueError]:
39
+ """Replace configured visibility only when the caller supplies an explicit override."""
40
+ match mask:
41
+ case Tensor():
42
+ match valid_pair_mask(mask, n, n, device):
43
+ case Ok(value=allowed):
44
+ return Ok((False, None, allowed))
45
+ case Err() as failure:
46
+ return failure
47
+ case _ as unreachable:
48
+ assert_never(unreachable)
49
+ case "default":
50
+ return Ok((causal, window_size, None))
51
+ case "causal":
52
+ return Ok((True, None, None))
53
+ case "bidirectional":
54
+ return Ok((False, None, None))
55
+ case _:
56
+ return Err(ValueError(f"unknown self-attention mask: {mask!r}"))
57
+
58
+
59
+ def validate_cross_mask(
60
+ mask: CrossAttentionMask, n: int, s: int, device: torch.device
61
+ ) -> Result[Tensor | None, TypeError | ValueError]:
62
+ """Admit optional cross visibility without inspecting tensor values."""
63
+ match mask:
64
+ case None:
65
+ return Ok(None)
66
+ case _:
67
+ return valid_pair_mask(mask, n, s, device)
68
+
69
+
70
+ def require_context(has_context: bool, mask: CrossAttentionMask) -> None:
71
+ """Reject cross visibility that would otherwise be silently ignored without context."""
72
+ if not has_context and mask is not None:
73
+ raise ValueError("cross_attn_mask requires context")