stackformers 5.1.0__tar.gz → 6.0.0rc1__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 (230) hide show
  1. stackformers-6.0.0rc1/.vscode/settings.json +5 -0
  2. {stackformers-5.1.0 → stackformers-6.0.0rc1}/CHANGELOG.md +52 -0
  3. {stackformers-5.1.0 → stackformers-6.0.0rc1}/PKG-INFO +3 -1
  4. {stackformers-5.1.0 → stackformers-6.0.0rc1}/README.md +2 -0
  5. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/README.md +2 -0
  6. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/image_encoder.py +7 -1
  7. stackformers-6.0.0rc1/examples/spatial_encoder.py +108 -0
  8. {stackformers-5.1.0 → stackformers-6.0.0rc1}/pyproject.toml +1 -1
  9. {stackformers-5.1.0 → stackformers-6.0.0rc1}/pyrefly.toml +1 -2
  10. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/DEVLOG.md +13 -0
  11. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/__init__.py +36 -2
  12. stackformers-5.1.0/stackformers/dimension_rounding.py → stackformers-6.0.0rc1/stackformers/alignment.py +1 -1
  13. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/README.md +4 -4
  14. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/config.py +7 -7
  15. stackformers-6.0.0rc1/stackformers/attention2d/README.md +220 -0
  16. stackformers-6.0.0rc1/stackformers/attention2d/__init__.py +21 -0
  17. stackformers-6.0.0rc1/stackformers/attention2d/_geometry_module.py +52 -0
  18. stackformers-6.0.0rc1/stackformers/attention2d/centroid_queries.py +41 -0
  19. stackformers-6.0.0rc1/stackformers/attention2d/coordinates.py +161 -0
  20. stackformers-6.0.0rc1/stackformers/attention2d/cross_attn_pooling.py +104 -0
  21. stackformers-6.0.0rc1/stackformers/attention2d/factory.py +86 -0
  22. stackformers-6.0.0rc1/stackformers/attention2d/figures/window_cross_attention_2d.svg +1 -0
  23. stackformers-6.0.0rc1/stackformers/attention2d/figures/window_self_attention_2d.svg +1 -0
  24. stackformers-6.0.0rc1/stackformers/attention2d/packed_windows.py +135 -0
  25. stackformers-6.0.0rc1/stackformers/attention2d/protocols.py +73 -0
  26. stackformers-6.0.0rc1/stackformers/attention2d/query_anchors.py +98 -0
  27. stackformers-6.0.0rc1/stackformers/attention2d/self_attn.py +82 -0
  28. stackformers-6.0.0rc1/stackformers/attention2d/sequence.py +222 -0
  29. stackformers-6.0.0rc1/stackformers/attention2d/windows.py +113 -0
  30. stackformers-6.0.0rc1/stackformers/encoder2d/README.md +138 -0
  31. stackformers-6.0.0rc1/stackformers/encoder2d/__init__.py +14 -0
  32. stackformers-6.0.0rc1/stackformers/encoder2d/encoder.py +45 -0
  33. stackformers-6.0.0rc1/stackformers/encoder2d/layer.py +55 -0
  34. stackformers-6.0.0rc1/stackformers/encoder2d/protocols.py +37 -0
  35. stackformers-6.0.0rc1/stackformers/encoder2d/tokenwise.py +53 -0
  36. stackformers-6.0.0rc1/stackformers/encoder2d/window_stage.py +74 -0
  37. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/README.md +4 -4
  38. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/config.py +4 -4
  39. stackformers-6.0.0rc1/stackformers/positional/README.md +70 -0
  40. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/config.py +58 -31
  41. stackformers-6.0.0rc1/stackformers/positional/rope2d.py +22 -0
  42. stackformers-6.0.0rc1/stackformers/positional/rope_nd.py +97 -0
  43. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_config.py +7 -7
  44. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_distance_bias.py +1 -1
  45. stackformers-6.0.0rc1/tests/attention2d/conftest.py +41 -0
  46. stackformers-6.0.0rc1/tests/attention2d/test_cross_attn_pooling.py +238 -0
  47. stackformers-6.0.0rc1/tests/attention2d/test_export.py +63 -0
  48. stackformers-6.0.0rc1/tests/attention2d/test_packed_windows.py +30 -0
  49. stackformers-6.0.0rc1/tests/attention2d/test_self_attn.py +142 -0
  50. stackformers-6.0.0rc1/tests/attention2d/test_sequence.py +104 -0
  51. stackformers-6.0.0rc1/tests/attention2d/test_windows.py +24 -0
  52. stackformers-6.0.0rc1/tests/encoder2d/conftest.py +64 -0
  53. stackformers-6.0.0rc1/tests/encoder2d/test_encoder.py +42 -0
  54. stackformers-6.0.0rc1/tests/encoder2d/test_layer.py +68 -0
  55. stackformers-6.0.0rc1/tests/encoder2d/test_window_stage.py +131 -0
  56. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_config.py +6 -8
  57. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/positional/test_cacheable.py +1 -1
  58. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/positional/test_rope.py +9 -6
  59. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/positional/test_rope_nd.py +1 -1
  60. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/presets/test_encoder.py +3 -1
  61. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/presets/test_variable_width_encoder.py +1 -1
  62. stackformers-5.1.0/tests/test_dimension_rounding.py → stackformers-6.0.0rc1/tests/test_alignment.py +4 -4
  63. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_core_results.py +7 -3
  64. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_public_api.py +5 -1
  65. {stackformers-5.1.0 → stackformers-6.0.0rc1}/uv.lock +15 -14
  66. stackformers-5.1.0/.vscode/settings.json +0 -3
  67. stackformers-5.1.0/stackformers/positional/README.md +0 -30
  68. stackformers-5.1.0/stackformers/positional/rope2d.py +0 -81
  69. stackformers-5.1.0/stackformers/positional/rope_nd.py +0 -115
  70. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.claudeignore +0 -0
  71. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  72. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  73. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.github/pull_request_template.md +0 -0
  74. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.github/workflows/check.yml +0 -0
  75. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.gitignore +0 -0
  76. {stackformers-5.1.0 → stackformers-6.0.0rc1}/.python-version +0 -0
  77. {stackformers-5.1.0 → stackformers-6.0.0rc1}/AGENTS.md +0 -0
  78. {stackformers-5.1.0 → stackformers-6.0.0rc1}/CITATION.cff +0 -0
  79. {stackformers-5.1.0 → stackformers-6.0.0rc1}/CONTRIBUTING.md +0 -0
  80. {stackformers-5.1.0 → stackformers-6.0.0rc1}/Justfile +0 -0
  81. {stackformers-5.1.0 → stackformers-6.0.0rc1}/LICENSE +0 -0
  82. {stackformers-5.1.0 → stackformers-6.0.0rc1}/PLAN.md +0 -0
  83. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/api-guide.md +0 -0
  84. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/assets/social-preview.jpg +0 -0
  85. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/assets/social-preview.md +0 -0
  86. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/compatibility.md +0 -0
  87. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/improvement-plan.md +0 -0
  88. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/inference.md +0 -0
  89. {stackformers-5.1.0 → stackformers-6.0.0rc1}/docs/research.md +0 -0
  90. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/causal_language_model.py +0 -0
  91. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/encoder_decoder_onnxruntime.py +0 -0
  92. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/padded_and_packed.py +0 -0
  93. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/point_cloud_encoder.py +0 -0
  94. {stackformers-5.1.0 → stackformers-6.0.0rc1}/examples/subclassed_encoder.py +0 -0
  95. {stackformers-5.1.0 → stackformers-6.0.0rc1}/pytest.ini +0 -0
  96. {stackformers-5.1.0 → stackformers-6.0.0rc1}/ruff.toml +0 -0
  97. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/_decoder_equations.py +0 -0
  98. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/_projection_packing.py +0 -0
  99. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/_result.py +0 -0
  100. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/all_valid_decoder.py +0 -0
  101. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/__init__.py +0 -0
  102. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/all_valid.py +0 -0
  103. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/bias.py +0 -0
  104. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/cache.py +0 -0
  105. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/cache_validation.py +0 -0
  106. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/cached.py +0 -0
  107. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/cross_attn.py +0 -0
  108. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/distance_bias.py +0 -0
  109. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/factory.py +0 -0
  110. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/layout.py +0 -0
  111. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/masking.py +0 -0
  112. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/onnx_backend.py +0 -0
  113. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/ops.py +0 -0
  114. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/packed_cross_attn.py +0 -0
  115. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/packed_self_attn.py +0 -0
  116. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/protocols.py +0 -0
  117. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/self_attn.py +0 -0
  118. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/attention/varlen_backend.py +0 -0
  119. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/config.py +0 -0
  120. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/cross_attender.py +0 -0
  121. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/decoder.py +0 -0
  122. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/decoder_cache.py +0 -0
  123. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/encoder.py +0 -0
  124. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/DEVLOG.md +0 -0
  125. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/__init__.py +0 -0
  126. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/factory.py +0 -0
  127. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/geglu.py +0 -0
  128. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/gelu.py +0 -0
  129. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/hardswish_glu.py +0 -0
  130. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/packed_geglu.py +0 -0
  131. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/packed_hardswish_glu.py +0 -0
  132. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/packed_swiglu.py +0 -0
  133. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/protocols.py +0 -0
  134. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/relu_squared.py +0 -0
  135. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/feedforward/swiglu.py +0 -0
  136. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/layers.py +0 -0
  137. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/README.md +0 -0
  138. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/config.py +0 -0
  139. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/head.py +0 -0
  140. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/head_cosine.py +0 -0
  141. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/masking.py +0 -0
  142. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/protocols.py +0 -0
  143. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/mlm/wrapper.py +0 -0
  144. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/norm/README.md +0 -0
  145. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/norm/__init__.py +0 -0
  146. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/norm/config.py +0 -0
  147. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/norm/factory.py +0 -0
  148. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/norm/protocols.py +0 -0
  149. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/packing.py +0 -0
  150. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/__init__.py +0 -0
  151. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/factory.py +0 -0
  152. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/learned.py +0 -0
  153. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/none.py +0 -0
  154. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/protocols.py +0 -0
  155. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/rope1d.py +0 -0
  156. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/positional/validation.py +0 -0
  157. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/preallocated_decoder.py +0 -0
  158. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/presets/README.md +0 -0
  159. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/presets/__init__.py +0 -0
  160. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/presets/cross_attender.py +0 -0
  161. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/presets/decoder.py +0 -0
  162. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/presets/encoder.py +0 -0
  163. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/presets/variable_width_encoder.py +0 -0
  164. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/py.typed +0 -0
  165. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/result/README.md +0 -0
  166. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/result/__init__.py +0 -0
  167. {stackformers-5.1.0 → stackformers-6.0.0rc1}/stackformers/sequence.py +0 -0
  168. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/__init__.py +0 -0
  169. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/__init__.py +0 -0
  170. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/legacy_api_rc1.json +0 -0
  171. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_all_valid.py +0 -0
  172. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_cached.py +0 -0
  173. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_contracts.py +0 -0
  174. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_cross_attn.py +0 -0
  175. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_cross_attn_cache.py +0 -0
  176. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_empty_rows.py +0 -0
  177. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_factory.py +0 -0
  178. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_geometry.py +0 -0
  179. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_kernels.py +0 -0
  180. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_legacy_api.py +0 -0
  181. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_masking.py +0 -0
  182. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_onnx_backend.py +0 -0
  183. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_ops.py +0 -0
  184. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_packed_cross_attn.py +0 -0
  185. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_packed_self_attn.py +0 -0
  186. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_sdpa_export.py +0 -0
  187. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_self_attn.py +0 -0
  188. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/attention/test_varlen_backend.py +0 -0
  189. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/conftest.py +0 -0
  190. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/export_utils.py +0 -0
  191. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/__init__.py +0 -0
  192. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/legacy_swiglu_4_6.json +0 -0
  193. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_factory.py +0 -0
  194. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_geglu.py +0 -0
  195. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_gelu.py +0 -0
  196. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_hardswish_glu.py +0 -0
  197. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_packed_geglu.py +0 -0
  198. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_packed_hardswish_glu.py +0 -0
  199. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_packed_swiglu.py +0 -0
  200. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_relu_squared.py +0 -0
  201. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/feedforward/test_swiglu.py +0 -0
  202. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/mlm/__init__.py +0 -0
  203. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/mlm/test_empty_selection.py +0 -0
  204. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/mlm/test_head.py +0 -0
  205. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/mlm/test_head_cosine.py +0 -0
  206. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/mlm/test_masking.py +0 -0
  207. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/mlm/test_wrapper.py +0 -0
  208. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/norm_topology_helpers.py +0 -0
  209. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/positional/__init__.py +0 -0
  210. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/positional/test_learned_pos.py +0 -0
  211. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/presets/__init__.py +0 -0
  212. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/presets/test_cross_attender.py +0 -0
  213. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/presets/test_decoder.py +0 -0
  214. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/presets/test_projection_packing.py +0 -0
  215. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_all_valid_decoder.py +0 -0
  216. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_cross_attender.py +0 -0
  217. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_decoder.py +0 -0
  218. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_decoder_cache.py +0 -0
  219. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_decoder_equations.py +0 -0
  220. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_encoder.py +0 -0
  221. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_encoder_decoder_example.py +0 -0
  222. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_examples.py +0 -0
  223. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_export_utils.py +0 -0
  224. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_layers.py +0 -0
  225. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_norm.py +0 -0
  226. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_packing.py +0 -0
  227. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_preallocated_decoder.py +0 -0
  228. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_projection_packing.py +0 -0
  229. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_result.py +0 -0
  230. {stackformers-5.1.0 → stackformers-6.0.0rc1}/tests/test_sequence.py +0 -0
@@ -0,0 +1,5 @@
1
+ {
2
+ "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
3
+ "python.languageServer": "Pylance",
4
+ "python.analysis.diagnosticsSource": "Pylance + Pyrefly"
5
+ }
@@ -6,6 +6,58 @@ 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
+ ## [6.0.0rc1]
10
+
11
+ ### Backwards Incompatible Changes
12
+
13
+ - Replace base-based `RoPE2DConfig` with calibrated physical `r_min`/`r_max`
14
+ bounds. Supply positive finite bounds explicitly; obsolete `base` arguments
15
+ are rejected. RoPE2D and RoPEND now share one continuous-coordinate implementation.
16
+ - Store rotary frequencies as `[coords, bands]`, including when scalar bounds
17
+ broadcast across axes. The frequency buffer remains nonpersistent.
18
+
19
+ ### New Features
20
+
21
+ - Add `WindowEncoderStage2d` to share one partition and coordinate preparation
22
+ across injected 1D encoder blocks, and `Encoder2dLike` for spatial encoder consumers.
23
+ The composition example preserves sandwich normalization, explicit Q/K
24
+ normalization, and HardSwishGLU.
25
+
26
+ - Add `TransformerLayer2d` pre-norm residual blocks and `Encoder2d` for composable
27
+ spatial stages. Reuse injected feed-forward and normalization modules, preserve
28
+ padded/packed spatial records, and place pooling between residual blocks.
29
+
30
+ - Support independent `r_min` and `r_max` tuples per coordinate axis in RoPEND
31
+ and RoPE2D. Scalar bounds explicitly share a scale across axes. Supplied
32
+ physical coordinates may be nonuniform and are never reconstructed from indices.
33
+ - Add `WindowSelfAttention2d` and `CrossAttnPooling2d` for channels-last spatial
34
+ windows, with automatic boundary padding, boolean validity masks, and learned
35
+ rectangular output tiles that preserve channel width.
36
+ - Add `PackedTensor2d` and `PaddedTensor2d` for variable-sized spatial feature grids. Both window layers
37
+ preserve packed layouts without allocating a shared padded spatial canvas.
38
+ Padded records carry validity; packed records store only valid tokens with
39
+ integer grid indices distinct from nonuniform absolute coordinates. Cross-pooling
40
+ preserves its query anchors as output coordinates.
41
+ - Adapt 2D windows to the existing fused 1D self-/cross-attention modules,
42
+ preserving padded/packed backend dispatch and unsupported-GPU fallbacks.
43
+ Cross-pooling uses learned query features with geometry-derived RoPEND anchors.
44
+ - Accept injected positional-encoding modules in 2D layers. Omitted encodings use
45
+ window-calibrated RoPEND with per-window coordinate normalization, preserving
46
+ physical output coordinates across composed stages.
47
+ - Make 2D attention, coordinate preparation, and pooling query placement independently
48
+ injectable through protocols. Bind source/query coordinate frames with closures
49
+ and preserve versioned built-in geometry signatures in checkpoints.
50
+
51
+
52
+ ## [5.1.1]
53
+
54
+ ### Improvements
55
+
56
+ - Rename `DimensionRoundingConfig` to `AlignmentConfig` and the attention/feed-forward
57
+ config field `dimension_rounding` to `alignment`. Import the shared type from
58
+ `stackformers` or `stackformers.alignment`; update existing configuration payloads to
59
+ use `alignment`. Rounding behavior and defaults are unchanged.
60
+
9
61
  ## [5.1.0]
10
62
 
11
63
  ### New Features
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stackformers
3
- Version: 5.1.0
3
+ Version: 6.0.0rc1
4
4
  Summary: Composable PyTorch transformers for vision, spatial, and sequence research
5
5
  Project-URL: Homepage, https://github.com/Red-Eyed/stackformers
6
6
  Project-URL: Repository, https://github.com/Red-Eyed/stackformers
@@ -176,6 +176,8 @@ See [compatibility evidence](docs/compatibility.md) and
176
176
  - [Examples and expected behavior](examples/README.md)
177
177
  - [Research reproducibility and citation](docs/research.md)
178
178
  - [API, layouts, configuration, and migration](docs/api-guide.md)
179
+ - [Spatial window attention and pooling](stackformers/attention2d/README.md)
180
+ - [Composable 2D transformer encoders](stackformers/encoder2d/README.md)
179
181
  - [Deployment and inference](docs/inference.md)
180
182
  - [Release history](CHANGELOG.md)
181
183
  - [Contributing](CONTRIBUTING.md)
@@ -125,6 +125,8 @@ See [compatibility evidence](docs/compatibility.md) and
125
125
  - [Examples and expected behavior](examples/README.md)
126
126
  - [Research reproducibility and citation](docs/research.md)
127
127
  - [API, layouts, configuration, and migration](docs/api-guide.md)
128
+ - [Spatial window attention and pooling](stackformers/attention2d/README.md)
129
+ - [Composable 2D transformer encoders](stackformers/encoder2d/README.md)
128
130
  - [Deployment and inference](docs/inference.md)
129
131
  - [Release history](CHANGELOG.md)
130
132
  - [Contributing](CONTRIBUTING.md)
@@ -7,6 +7,7 @@ on CPU and avoid external datasets, tokenizers, or model downloads.
7
7
  | --- | --- |
8
8
  | [`padded_and_packed.py`](padded_and_packed.py) | One encoder and one set of weights processing equivalent padded and packed variable-length batches. |
9
9
  | [`causal_language_model.py`](causal_language_model.py) | A decoder-only language model with token embeddings, causal attention, next-token loss, and an optimizer step. |
10
+ | [`spatial_encoder.py`](spatial_encoder.py) | Shared window partitions across sandwich-normalized blocks with explicit Q/K normalization and HardSwishGLU, plus rectangular pooling and nonuniform coordinates. |
10
11
  | [`image_encoder.py`](image_encoder.py) | Image patch projection, explicit row/column positions, RoPE-2D, pooling, and classification. |
11
12
  | [`point_cloud_encoder.py`](point_cloud_encoder.py) | Continuous 3-D positions, coordinate centering, RoPE-ND, and translation invariance. |
12
13
  | [`subclassed_encoder.py`](subclassed_encoder.py) | A focused preset-hook override and a fully user-owned `TransformerEncoderBase` subclass. |
@@ -17,6 +18,7 @@ Run any example from the repository root:
17
18
  ```bash
18
19
  uv run examples/padded_and_packed.py
19
20
  uv run examples/causal_language_model.py
21
+ uv run examples/spatial_encoder.py
20
22
  uv run examples/image_encoder.py
21
23
  uv run examples/point_cloud_encoder.py
22
24
  uv run examples/subclassed_encoder.py
@@ -38,7 +38,13 @@ class ImagePatchEncoder(nn.Module):
38
38
  super().__init__()
39
39
  self.patch_projection = nn.Conv2d(3, DIM, kernel_size=PATCH_SIZE, stride=PATCH_SIZE)
40
40
  config = plain_encoder_config(dim=DIM, heads=1, num_layers=2, ff_mult=3.0)
41
- config = config.model_copy(update={"pos_encoding": RoPE2DConfig(dim_head=DIM)})
41
+ extent = float(IMAGE_SIZE // PATCH_SIZE - 1)
42
+ position_config = RoPE2DConfig(
43
+ dim_head=DIM,
44
+ r_min=(1.0, 1.0),
45
+ r_max=(extent, extent),
46
+ )
47
+ config = config.model_copy(update={"pos_encoding": position_config})
42
48
  self.encoder = TransformerEncoder(config)
43
49
  self.classifier = nn.Linear(DIM, NUM_CLASSES)
44
50
 
@@ -0,0 +1,108 @@
1
+ """Compose spatial stages with sandwich norms, Q/K normalization, and HardSwishGLU."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, NamedTuple
6
+
7
+ import torch
8
+ from torch import nn
9
+
10
+ from stackformers import (
11
+ CrossAttnPooling2d,
12
+ Encoder,
13
+ Encoder2d,
14
+ HardSwishGLUConfig,
15
+ NormalizedWindowCoordinates,
16
+ PackedCrossAttentionConfig,
17
+ PackedSelfAttentionConfig,
18
+ PaddedTensor2d,
19
+ RoPENDConfig,
20
+ SandwichNormTransformerLayer,
21
+ WindowEncoderStage2d,
22
+ build_cross_attn,
23
+ build_ff,
24
+ build_pos_encoding,
25
+ build_self_attn,
26
+ )
27
+
28
+ if TYPE_CHECKING:
29
+ from jaxtyping import Float
30
+ from torch import Tensor
31
+
32
+
33
+ class SpatialEncoderResult(NamedTuple):
34
+ """Storage shapes produced by the same model on padded and packed spatial inputs."""
35
+
36
+ padded_shape: tuple[int, ...]
37
+ packed_shape: tuple[int, ...]
38
+
39
+
40
+ def build_stage(dim: int, heads: int, depth: int, window: tuple[int, int]) -> WindowEncoderStage2d:
41
+ """Keep deliberate model choices in composition, outside the reusable stage adapter."""
42
+ if dim <= 0 or heads <= 0 or dim % heads or depth <= 0:
43
+ raise ValueError("require positive dim, heads, and depth, with dim divisible by heads")
44
+ position = RoPENDConfig(
45
+ dim_head=dim // heads,
46
+ r_min=(1.0, 1.0),
47
+ r_max=(float(max(2, window[0] - 1)), float(max(2, window[1] - 1))),
48
+ )
49
+ blocks = [
50
+ SandwichNormTransformerLayer(
51
+ self_attn=build_self_attn(
52
+ PackedSelfAttentionConfig(
53
+ dim=dim, heads=heads, dim_head=dim // heads, qk_norm=True
54
+ ),
55
+ build_pos_encoding(position),
56
+ ),
57
+ ff=build_ff(HardSwishGLUConfig(dim=dim)),
58
+ norm_attn_pre=nn.RMSNorm(dim),
59
+ norm_attn_post=nn.RMSNorm(dim),
60
+ norm_ff_pre=nn.RMSNorm(dim),
61
+ norm_ff_post=nn.RMSNorm(dim),
62
+ )
63
+ for _ in range(depth)
64
+ ]
65
+ encoder = Encoder(blocks, final_norm=nn.Identity())
66
+ return WindowEncoderStage2d(encoder, window, NormalizedWindowCoordinates(window))
67
+
68
+
69
+ def build_encoder() -> Encoder2d:
70
+ """Compose independently prepared stages around a pure attention-pooling transition."""
71
+ dim, window = 96, (4, 4)
72
+ pooling_attention = build_cross_attn(
73
+ PackedCrossAttentionConfig(dim=dim, heads=1, dim_head=dim, qk_norm=True),
74
+ build_pos_encoding(RoPENDConfig(dim_head=dim, r_min=1.0, r_max=3.0)),
75
+ )
76
+ pooling = CrossAttnPooling2d(
77
+ dim,
78
+ window,
79
+ output_window_size=(1, 2),
80
+ attention=pooling_attention,
81
+ coordinates=NormalizedWindowCoordinates(window),
82
+ )
83
+ return Encoder2d(
84
+ [build_stage(dim, 4, 2, window), pooling, build_stage(dim, 4, 2, window)],
85
+ final_norm=nn.RMSNorm(dim),
86
+ )
87
+
88
+
89
+ def run_example() -> SpatialEncoderResult:
90
+ """Process nonuniform physical coordinates without resizing ragged feature grids."""
91
+ torch.manual_seed(0)
92
+ grids: list[Float[Tensor, "height width d"]] = [torch.randn(8, width, 96) for width in (17, 23)]
93
+ positions: list[Float[Tensor, "height width 2"]] = []
94
+ for grid in grids:
95
+ y, x = torch.meshgrid(
96
+ torch.arange(grid.shape[0]), torch.arange(grid.shape[1]), indexing="ij"
97
+ )
98
+ positions.append(torch.stack((y.float(), x.float().square() / 10), dim=-1))
99
+ source = PaddedTensor2d.from_list(grids, abs_positions=positions)
100
+ model = build_encoder().eval()
101
+ with torch.no_grad():
102
+ padded = model(source)
103
+ packed = model(source.to_packed())
104
+ return SpatialEncoderResult(tuple(padded.x.shape), tuple(packed.x.shape))
105
+
106
+
107
+ if __name__ == "__main__":
108
+ print(run_example())
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "stackformers"
7
- version = "5.1.0"
7
+ version = "6.0.0rc1"
8
8
  description = "Composable PyTorch transformers for vision, spatial, and sequence research"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -1,8 +1,7 @@
1
1
  required-version = ">=1.3.1"
2
2
  python-version = "3.11"
3
3
  preset = "strict"
4
- # Point at the uv venv so pyrefly finds torch and other installed packages
5
- python-interpreter-path = ".venv/bin/python"
4
+ python-interpreter-find-command = ["uv", "python", "find"]
6
5
  # Check every maintained Python entry point alongside the library and tests.
7
6
  project-includes = ["stackformers", "tests", "examples"]
8
7
  # Do not infer types from first-use (stricter)
@@ -822,3 +822,16 @@ and 252 expected failures on this machine.
822
822
 
823
823
  No throughput benchmark or training ablation establishes a speed or quality benefit. Rounding
824
824
  only selects internal geometry; other matrix dimensions and the workload still affect efficiency.
825
+
826
+
827
+ ## Alignment configuration naming
828
+
829
+ Rename the shared policy to `AlignmentConfig` in `alignment.py` and its config field to
830
+ `alignment`, reflecting the hardware goal while retaining `rounding_mode` for the mechanism.
831
+ Update imports, config payloads, tests, and module documentation together. The floor/ceil
832
+ behavior, zero-width rejection, and disabled defaults remain unchanged. This is the requested
833
+ 5.1.1 patch naming correction; callers using the previous names must update them.
834
+
835
+ Validation: repository formatting, lint, and type checks pass; 264 focused alignment,
836
+ attention/feed-forward config, factory, and projection-packing tests pass. Runtime version
837
+ reports 5.1.1.
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING
5
5
 
6
6
  __version__ = version("stackformers")
7
7
 
8
+ from stackformers.alignment import AlignmentConfig
8
9
  from stackformers.all_valid_decoder import (
9
10
  AllValidCachedDecoderWrapper,
10
11
  AllValidCrossAttentionCacheBuilder,
@@ -39,6 +40,18 @@ from stackformers.attention import (
39
40
  build_self_attn,
40
41
  )
41
42
  from stackformers.attention.masking import CrossAttentionMask, SelfAttentionMask
43
+ from stackformers.attention2d import (
44
+ CentroidQueryPositions,
45
+ CrossAttnPooling2d,
46
+ NormalizedWindowCoordinates,
47
+ PackedTensor2d,
48
+ PaddedTensor2d,
49
+ PhysicalCoordinates,
50
+ QueryPositions,
51
+ SelfAttn2d,
52
+ WindowCoordinates,
53
+ WindowSelfAttention2d,
54
+ )
42
55
  from stackformers.config import DecoderConfig, EncoderConfig, LayerConfig
43
56
  from stackformers.cross_attender import (
44
57
  CrossAttenderLayer,
@@ -65,8 +78,14 @@ from stackformers.decoder_cache import (
65
78
  CachedSandwichNormDecoderLayer,
66
79
  DecoderCrossAttentionCacheBuilder,
67
80
  )
68
- from stackformers.dimension_rounding import DimensionRoundingConfig
69
81
  from stackformers.encoder import Encoder
82
+ from stackformers.encoder2d import (
83
+ Encoder2d,
84
+ Encoder2dLike,
85
+ SpatialTransform2d,
86
+ TransformerLayer2d,
87
+ WindowEncoderStage2d,
88
+ )
70
89
  from stackformers.feedforward import (
71
90
  GEGLU,
72
91
  GELUFFN,
@@ -176,7 +195,22 @@ from stackformers.sequence import (
176
195
  )
177
196
 
178
197
  __all__ = [
179
- "DimensionRoundingConfig",
198
+ "Encoder2d",
199
+ "Encoder2dLike",
200
+ "WindowEncoderStage2d",
201
+ "TransformerLayer2d",
202
+ "SpatialTransform2d",
203
+ "SelfAttn2d",
204
+ "CentroidQueryPositions",
205
+ "NormalizedWindowCoordinates",
206
+ "PhysicalCoordinates",
207
+ "QueryPositions",
208
+ "WindowCoordinates",
209
+ "PackedTensor2d",
210
+ "PaddedTensor2d",
211
+ "CrossAttnPooling2d",
212
+ "WindowSelfAttention2d",
213
+ "AlignmentConfig",
180
214
  "AllValid",
181
215
  "materialize_padding_mask",
182
216
  "AllValidCachedDecoderWrapper",
@@ -7,7 +7,7 @@ from pydantic import BaseModel, Field
7
7
  from stackformers.result import Err, Ok, Result
8
8
 
9
9
 
10
- class DimensionRoundingConfig(BaseModel, frozen=True):
10
+ class AlignmentConfig(BaseModel, frozen=True):
11
11
  """Choose a width multiple and direction; this changes parameter shapes, not padding."""
12
12
 
13
13
  multiple_of: int = Field(gt=0, description="Positive multiple required of the rounded width.")
@@ -148,16 +148,16 @@ retain mask-only metadata for compatibility with existing exported cache structu
148
148
 
149
149
  ## Optional dimension rounding
150
150
 
151
- Every variant accepts `dimension_rounding: DimensionRoundingConfig | None`, imported from
151
+ Every variant accepts `alignment: AlignmentConfig | None`, imported from
152
152
  `stackformers`. The default `None` preserves existing widths and warnings. For example:
153
153
 
154
154
  ```python
155
- from stackformers import DimensionRoundingConfig
155
+ from stackformers import AlignmentConfig
156
156
 
157
- rounding = DimensionRoundingConfig(multiple_of=64, rounding_mode="ceil")
157
+ rounding = AlignmentConfig(multiple_of=64, rounding_mode="ceil")
158
158
  ```
159
159
 
160
- Pass `dimension_rounding=rounding` to the config to round `dim_head`.
160
+ Pass `alignment=rounding` to the config to round `dim_head`.
161
161
  `"floor"` rounds down; `"ceil"` rounds up and is the default. Exact multiples stay unchanged;
162
162
  a result of zero is rejected during config validation. The external model width stays unchanged.
163
163
  This selects actual parameter shapes rather than padding tensors, so enabling it can change
@@ -16,7 +16,7 @@ from pydantic import (
16
16
  )
17
17
 
18
18
  from stackformers._result import unwrap_or_raise
19
- from stackformers.dimension_rounding import DimensionRoundingConfig
19
+ from stackformers.alignment import AlignmentConfig
20
20
  from stackformers.result import Err, Ok, Result
21
21
 
22
22
  _ALIGN = 64 # tensor-core alignment for FP16/BF16
@@ -61,7 +61,7 @@ class _SelfAttentionConfigBase(BaseModel, frozen=True):
61
61
  description="Model (embedding) dimension — input and output width of the attention sublayer.", # noqa: E501
62
62
  )
63
63
  heads: int = Field(default=8, gt=0, description="Number of query heads.")
64
- dimension_rounding: DimensionRoundingConfig | None = None
64
+ alignment: AlignmentConfig | None = None
65
65
  dim_head: int = Field(
66
66
  default=64,
67
67
  validate_default=True,
@@ -109,8 +109,8 @@ class _SelfAttentionConfigBase(BaseModel, frozen=True):
109
109
  @classmethod
110
110
  def _round_dim_head(cls, value: int, info: ValidationInfo) -> int:
111
111
  """Resolve head geometry before admission, warnings, and module construction."""
112
- match info.data.get("dimension_rounding"):
113
- case DimensionRoundingConfig() as rounding:
112
+ match info.data.get("alignment"):
113
+ case AlignmentConfig() as rounding:
114
114
  return unwrap_or_raise(rounding.round_dimension(value))
115
115
  case _:
116
116
  return value
@@ -211,7 +211,7 @@ class _CrossAttentionConfigBase(BaseModel, frozen=True):
211
211
  description="Model (embedding) dimension — input and output width of the attention sublayer.", # noqa: E501
212
212
  )
213
213
  heads: int = Field(default=8, gt=0, description="Number of query heads.")
214
- dimension_rounding: DimensionRoundingConfig | None = None
214
+ alignment: AlignmentConfig | None = None
215
215
  dim_head: int = Field(
216
216
  default=64,
217
217
  validate_default=True,
@@ -246,8 +246,8 @@ class _CrossAttentionConfigBase(BaseModel, frozen=True):
246
246
  @classmethod
247
247
  def _round_dim_head(cls, value: int, info: ValidationInfo) -> int:
248
248
  """Resolve head geometry before admission, warnings, and module construction."""
249
- match info.data.get("dimension_rounding"):
250
- case DimensionRoundingConfig() as rounding:
249
+ match info.data.get("alignment"):
250
+ case AlignmentConfig() as rounding:
251
251
  return unwrap_or_raise(rounding.round_dimension(value))
252
252
  case _:
253
253
  return value
@@ -0,0 +1,220 @@
1
+ # Spatial window attention
2
+
3
+ The public API uses `PaddedTensor2d` and `PackedTensor2d`, mirroring the existing
4
+ one-dimensional padded/packed API. Both layers return the same layout they receive.
5
+ Validity, physical coordinates, and spatial topology travel with feature values;
6
+ there is no separate public tensor or mask argument.
7
+
8
+ ```python
9
+ from stackformers import (
10
+ CrossAttnPooling2d,
11
+ PackedTensor2d,
12
+ PaddedTensor2d,
13
+ WindowSelfAttention2d,
14
+ )
15
+
16
+ padded = PaddedTensor2d.from_list(grids, abs_positions=positions)
17
+ packed = PackedTensor2d.from_list(grids, abs_positions=positions)
18
+
19
+ attention = WindowSelfAttention2d(
20
+ 96,
21
+ window_size=(4, 4),
22
+ num_heads=4,
23
+ )
24
+ pooling = CrossAttnPooling2d(
25
+ 96,
26
+ window_size=(4, 4),
27
+ output_window_size=(2, 2),
28
+ )
29
+
30
+ padded_output = pooling(attention(padded)) # PaddedTensor2d
31
+ packed_output = pooling(attention(packed)) # PackedTensor2d
32
+ ```
33
+
34
+ ## Layer illustrations
35
+
36
+ ![Window self-attention](figures/window_self_attention_2d.svg)
37
+
38
+ ![Cross-attention pooling](figures/window_cross_attention_2d.svg)
39
+
40
+ See [spatial encoders](../encoder2d/README.md) for residual blocks and staged pooling.
41
+
42
+ ## Topology and physical coordinates
43
+
44
+ `abs_positions` are floating point coordinate pairs. They may be nonuniform,
45
+ translated, or otherwise unrelated to integer row/column indices. Supplied
46
+ coordinates are preserved rather than inferred from tensor shape. Omitted
47
+ coordinates use regular row/column positions as a factory default only.
48
+
49
+ `PaddedTensor2d` stores `x: [b,H,W,d]`, `mask: [b,H,W] | AllValid`,
50
+ `abs_positions: [b,H,W,2]`, and `spatial_shapes: [b,2]`. True means a valid slot.
51
+ Ragged grids are padded on the right and bottom with their extents retained.
52
+
53
+ `PackedTensor2d` stores only valid tokens: `x: [nt,d]`, `cu_seqlens: [b+1]`,
54
+ `abs_positions: [nt,2]`, and `grid_indices: [nt,2]`, together with per-grid
55
+ `spatial_shapes` and `max_spatial_shape` for dense conversion. Integer indices
56
+ retain holes left by excluded tokens and never substitute for physical positions.
57
+ Every stored packed token is valid; empty grids have repeated boundaries.
58
+
59
+ Both records provide `from_list`, `to_padded`, `to_packed`, and `to_list`.
60
+ Factories infer validity from extents unless optional boolean masks exclude
61
+ interior slots. Zero feature values are valid. Packing removes invalid values
62
+ and coordinates; dense conversion fills those slots with padding values and
63
+ zero coordinates. Conversions preserve valid-token gradients. List adapters are
64
+ eager-only; direct record construction trusts metadata.
65
+
66
+ ## Existing 1D attention and RoPEND
67
+
68
+ By default, `WindowSelfAttention2d` calls the fused-QKV `PackedSelfAttention` module.
69
+ By default, `CrossAttnPooling2d` calls the fused-KV `PackedCrossAttention` module,
70
+ with one attention head. Their padded/packed dispatch, optimized kernels, and
71
+ CPU/unsupported-GPU fallbacks remain in the existing 1D implementations. The
72
+ spatial adapters contain no attention-score, softmax, or attention-weighted
73
+ reduction implementation. Cross-attention uses standard Q/K/V projections;
74
+ there is no separate compact scorer or learned positional-bias matrix.
75
+
76
+ `rope` accepts an optional positional-encoding module through the existing
77
+ `PosEncoding` protocol, rather than a config or concrete implementation type.
78
+ The intended injected encoding is `RotaryEmbeddingND`. It receives original physical
79
+ coordinates by default; the caller selects matching head dimensions and two coordinate axes.
80
+
81
+ With `rope=None`, a construction-time factory supplies RoPEND and a separate
82
+ window-coordinate normalizer. The attention adapters depend on their protocols.
83
+ The default uses unit minimum separation and maximum separation
84
+ `(max(2, wh-1), max(2, ww-1))`, with head dimension derived from the layer.
85
+
86
+ For default attention only, each window is centered at its valid-coordinate
87
+ centroid. Each coordinate axis is divided by its mean absolute separation between
88
+ immediate valid topology neighbours: row neighbours for the first coordinate and
89
+ column neighbours for the second. Missing neighbours are excluded; an axis with
90
+ no pairs or zero mean separation uses scale one. Nonuniform spacing remains
91
+ nonuniform. Packed geometry uses stored tokens without a padded canvas.
92
+
93
+ This removes overall per-window translation and axis scale from default attention.
94
+ For example, source coordinates `[0, 1, 2, 3]` and pooled coordinates
95
+ `[0.5, 2.5, 4.5, 6.5]` have the same normalized offsets. Successive pooling stages
96
+ therefore do not need explicit accumulated-spacing metadata. All returned physical
97
+ coordinates stay in their original units, including the pooling query anchors.
98
+
99
+ For physical-scale-sensitive attention, inject a calibrated module explicitly:
100
+
101
+ ```python
102
+ from stackformers import RoPENDConfig, RotaryEmbeddingND
103
+
104
+ attention = WindowSelfAttention2d(
105
+ 96,
106
+ window_size=(4, 4),
107
+ num_heads=4,
108
+ rope=RotaryEmbeddingND(
109
+ RoPENDConfig(dim_head=24, coords=2, r_min=(0.5, 2.0), r_max=(32.0, 2048.0))
110
+ ),
111
+ )
112
+ ```
113
+
114
+ The minimum bounds describe the finest meaningful physical separation on each
115
+ axis; maximum bounds cover expected within-window offsets across the stages
116
+ using that calibration. Cross-pooling is single-head and needs `dim_head=dim`.
117
+ An injected encoding defaults to physical coordinates; an explicit `coordinates`
118
+ policy can independently select normalization. The encoding is registered inside
119
+ the existing attention module so device moves include its buffers.
120
+
121
+ ## Pooling query anchors
122
+
123
+ The default `CentroidQueryPositions` policy places learned query features shared
124
+ across windows. Each output query
125
+ is anchored at the mean of valid physical source coordinates in its corresponding
126
+ integer output region. For a `4x4 -> 2x2` window, the four anchors come from the
127
+ four `2x2` source regions. Irregular sizes assign source row `r` to output row
128
+ `floor(r*oh/wh)`, and likewise for columns. Each query still attends to every valid
129
+ source token in the whole window: region membership determines only its anchor.
130
+
131
+ An empty region uses the window's valid-coordinate centroid. A fully empty window
132
+ has invalid queries, yielding zero padded output tiles or no packed output tokens.
133
+ Anchors are computed before attention from geometry alone and remain the output
134
+ `abs_positions`. They are not recomputed using feature-dependent attention weights.
135
+ Coordinates retain their floating point dtype under AMP. The integer output tile
136
+ is row-major, with extents `ceil(H/wh)*oh` by `ceil(W/ww)*ow` and unchanged channels.
137
+
138
+ ## Independent extension points
139
+
140
+ Both layers accept `attention` and `coordinates`; pooling additionally accepts
141
+ `query_positions`. Constructor collaborators are typed against protocols:
142
+
143
+ | Dependency | Contract | Default implementation |
144
+ | --- | --- | --- |
145
+ | Self-attention | Existing `SelfAttn` | Existing fused-QKV 1D attention |
146
+ | Cross-attention | Existing `CrossAttn` | Existing fused-KV single-head 1D attention |
147
+ | Coordinate preparation | `WindowCoordinates` | `NormalizedWindowCoordinates` |
148
+ | Pooling query placement | `QueryPositions` | `CentroidQueryPositions` |
149
+
150
+ Default construction belongs to `factory.py`. The adapters do not import concrete
151
+ attention implementations, RoPEND configs, or centroid computation functions.
152
+ No optional dependency checks occur in `forward()`.
153
+
154
+ Each coordinate policy returns prepared sources and a closure bound to the same
155
+ coordinate transformation for queries. Pooling constructs physical output queries
156
+ once, transforms them for attention, then merges the attended features with the
157
+ original physical query positions. Custom nonlinear anchor rules therefore run
158
+ once in their intended physical frame, independently of normalization.
159
+
160
+ ```python
161
+ from stackformers import NormalizedWindowCoordinates
162
+
163
+ pooling = CrossAttnPooling2d(
164
+ 96,
165
+ window_size=(4, 4),
166
+ output_window_size=(2, 2),
167
+ attention=custom_cross_attention,
168
+ coordinates=NormalizedWindowCoordinates((4, 4)),
169
+ query_positions=custom_query_positions,
170
+ )
171
+ ```
172
+
173
+ An injected attention module owns its positional encoding; passing both
174
+ `attention` and `rope` is rejected rather than silently ignoring either one.
175
+ Custom attention defaults to `PhysicalCoordinates` unless `coordinates` is explicit.
176
+ An injected module can use another head count while retaining the same model width.
177
+ For reproducibility, explicitly supply all collaborators when experimenting with
178
+ alternative geometry or attention.
179
+
180
+ Implementations must honor the protocol contracts: preserve window ordering and
181
+ source validity, support padded and packed layouts, emit row-major full output
182
+ tiles for nonempty windows, and keep fully empty windows finite. Coordinate
183
+ policies preserve features and boundaries. Packed source slots are sorted within
184
+ each window. Attention returns feature tensors in query order with model width
185
+ unchanged. Use `nn.Module` for collaborators with parameters or buffers so PyTorch
186
+ registers them for optimization, device moves, and checkpoints. Custom strategies
187
+ remain responsible for compile/export compatibility of their operators.
188
+
189
+ To add a variant, implement the owning protocol in a separate file and inject it;
190
+ no edits to the adapters or their dispatch are needed. The default normalizer's
191
+ axis-aligned spacing assumption is a replaceable policy, not a tensor invariant.
192
+ Shifted or overlapping window topology would require a separate partition/merge
193
+ implementation; arbitrary window topology is not a supported injection point here.
194
+
195
+ ## Checkpoint compatibility
196
+
197
+ Built-in geometry modules store a persistent integer signature containing policy
198
+ identity, behavior revision, and relevant window/tile topology. Loading a different
199
+ policy or topology rejects the checkpoint rather than silently changing geometry.
200
+ Future behavior changes must retain the previous implementation as an injectable
201
+ variant or provide an explicit checkpoint migration and increment its revision.
202
+ Signature checks execute only during checkpoint loading.
203
+
204
+ A `state_dict` does not reconstruct an architecture. Save the construction recipe
205
+ alongside weights, including layer dimensions, explicit RoPEND calibration, and
206
+ custom collaborator configurations. RoPEND frequency buffers are nonpersistent;
207
+ geometry signatures do not encode an injected encoding's calibration or backend.
208
+ Custom modules own their state and compatibility checks. This guard protects the
209
+ built-in geometry policies, not arbitrary injected implementations.
210
+
211
+ ## Export and readiness
212
+
213
+ Padded records are the intended dynamic-width ONNX path. Values, validity,
214
+ coordinates, and extents are graph inputs and outputs. Packed token counts depend
215
+ on validity and metadata; packed export is not currently supported.
216
+
217
+ The API and rotary integration are being revised. Previous export results do not
218
+ validate this revision. Tests will be run only after the user declares the
219
+ implementation ready. Test sources and vector figures describe the projected cross-attention and
220
+ query-anchor contract; compute and export behavior still require validation.
@@ -0,0 +1,21 @@
1
+ """Spatial records, window adapters, and replaceable geometry policies."""
2
+
3
+ from stackformers.attention2d.centroid_queries import CentroidQueryPositions
4
+ from stackformers.attention2d.coordinates import NormalizedWindowCoordinates, PhysicalCoordinates
5
+ from stackformers.attention2d.cross_attn_pooling import CrossAttnPooling2d
6
+ from stackformers.attention2d.protocols import QueryPositions, SelfAttn2d, WindowCoordinates
7
+ from stackformers.attention2d.self_attn import WindowSelfAttention2d
8
+ from stackformers.attention2d.sequence import PackedTensor2d, PaddedTensor2d
9
+
10
+ __all__ = [
11
+ "CentroidQueryPositions",
12
+ "CrossAttnPooling2d",
13
+ "NormalizedWindowCoordinates",
14
+ "PackedTensor2d",
15
+ "PaddedTensor2d",
16
+ "PhysicalCoordinates",
17
+ "QueryPositions",
18
+ "SelfAttn2d",
19
+ "WindowCoordinates",
20
+ "WindowSelfAttention2d",
21
+ ]