stackformers 5.1.1__tar.gz → 6.0.0rc2__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 (234) hide show
  1. stackformers-6.0.0rc2/.vscode/settings.json +5 -0
  2. {stackformers-5.1.1 → stackformers-6.0.0rc2}/CHANGELOG.md +54 -0
  3. {stackformers-5.1.1 → stackformers-6.0.0rc2}/PKG-INFO +3 -1
  4. {stackformers-5.1.1 → stackformers-6.0.0rc2}/README.md +2 -0
  5. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/README.md +2 -0
  6. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/image_encoder.py +7 -1
  7. stackformers-6.0.0rc2/examples/spatial_encoder.py +108 -0
  8. {stackformers-5.1.1 → stackformers-6.0.0rc2}/pyproject.toml +1 -1
  9. {stackformers-5.1.1 → stackformers-6.0.0rc2}/pyrefly.toml +1 -2
  10. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/__init__.py +34 -0
  11. stackformers-6.0.0rc2/stackformers/attention2d/README.md +243 -0
  12. stackformers-6.0.0rc2/stackformers/attention2d/__init__.py +21 -0
  13. stackformers-6.0.0rc2/stackformers/attention2d/_geometry_module.py +52 -0
  14. stackformers-6.0.0rc2/stackformers/attention2d/centroid_queries.py +41 -0
  15. stackformers-6.0.0rc2/stackformers/attention2d/coordinates.py +171 -0
  16. stackformers-6.0.0rc2/stackformers/attention2d/cross_attn_pooling.py +104 -0
  17. stackformers-6.0.0rc2/stackformers/attention2d/factory.py +86 -0
  18. stackformers-6.0.0rc2/stackformers/attention2d/figures/window_cross_attention_2d.svg +1 -0
  19. stackformers-6.0.0rc2/stackformers/attention2d/figures/window_self_attention_2d.svg +1 -0
  20. stackformers-6.0.0rc2/stackformers/attention2d/geometry_precision.py +17 -0
  21. stackformers-6.0.0rc2/stackformers/attention2d/packed_windows.py +135 -0
  22. stackformers-6.0.0rc2/stackformers/attention2d/protocols.py +73 -0
  23. stackformers-6.0.0rc2/stackformers/attention2d/query_anchors.py +102 -0
  24. stackformers-6.0.0rc2/stackformers/attention2d/self_attn.py +82 -0
  25. stackformers-6.0.0rc2/stackformers/attention2d/sequence.py +222 -0
  26. stackformers-6.0.0rc2/stackformers/attention2d/windows.py +113 -0
  27. stackformers-6.0.0rc2/stackformers/encoder2d/README.md +147 -0
  28. stackformers-6.0.0rc2/stackformers/encoder2d/__init__.py +14 -0
  29. stackformers-6.0.0rc2/stackformers/encoder2d/_callable_stage.py +36 -0
  30. stackformers-6.0.0rc2/stackformers/encoder2d/encoder.py +51 -0
  31. stackformers-6.0.0rc2/stackformers/encoder2d/layer.py +55 -0
  32. stackformers-6.0.0rc2/stackformers/encoder2d/protocols.py +37 -0
  33. stackformers-6.0.0rc2/stackformers/encoder2d/tokenwise.py +53 -0
  34. stackformers-6.0.0rc2/stackformers/encoder2d/window_stage.py +74 -0
  35. stackformers-6.0.0rc2/stackformers/positional/README.md +70 -0
  36. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/config.py +58 -31
  37. stackformers-6.0.0rc2/stackformers/positional/rope2d.py +22 -0
  38. stackformers-6.0.0rc2/stackformers/positional/rope_nd.py +97 -0
  39. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_distance_bias.py +1 -1
  40. stackformers-6.0.0rc2/tests/attention2d/conftest.py +41 -0
  41. stackformers-6.0.0rc2/tests/attention2d/test_coordinates.py +68 -0
  42. stackformers-6.0.0rc2/tests/attention2d/test_cross_attn_pooling.py +238 -0
  43. stackformers-6.0.0rc2/tests/attention2d/test_export.py +63 -0
  44. stackformers-6.0.0rc2/tests/attention2d/test_packed_windows.py +30 -0
  45. stackformers-6.0.0rc2/tests/attention2d/test_query_anchors.py +75 -0
  46. stackformers-6.0.0rc2/tests/attention2d/test_self_attn.py +142 -0
  47. stackformers-6.0.0rc2/tests/attention2d/test_sequence.py +104 -0
  48. stackformers-6.0.0rc2/tests/attention2d/test_windows.py +24 -0
  49. stackformers-6.0.0rc2/tests/encoder2d/conftest.py +64 -0
  50. stackformers-6.0.0rc2/tests/encoder2d/test_encoder.py +91 -0
  51. stackformers-6.0.0rc2/tests/encoder2d/test_layer.py +68 -0
  52. stackformers-6.0.0rc2/tests/encoder2d/test_window_stage.py +131 -0
  53. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/positional/test_cacheable.py +1 -1
  54. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/positional/test_rope.py +9 -6
  55. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/positional/test_rope_nd.py +1 -1
  56. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/presets/test_encoder.py +3 -1
  57. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/presets/test_variable_width_encoder.py +1 -1
  58. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_core_results.py +7 -3
  59. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_public_api.py +5 -1
  60. {stackformers-5.1.1 → stackformers-6.0.0rc2}/uv.lock +15 -14
  61. stackformers-5.1.1/.vscode/settings.json +0 -3
  62. stackformers-5.1.1/stackformers/positional/README.md +0 -30
  63. stackformers-5.1.1/stackformers/positional/rope2d.py +0 -81
  64. stackformers-5.1.1/stackformers/positional/rope_nd.py +0 -115
  65. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.claudeignore +0 -0
  66. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  67. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  68. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.github/pull_request_template.md +0 -0
  69. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.github/workflows/check.yml +0 -0
  70. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.gitignore +0 -0
  71. {stackformers-5.1.1 → stackformers-6.0.0rc2}/.python-version +0 -0
  72. {stackformers-5.1.1 → stackformers-6.0.0rc2}/AGENTS.md +0 -0
  73. {stackformers-5.1.1 → stackformers-6.0.0rc2}/CITATION.cff +0 -0
  74. {stackformers-5.1.1 → stackformers-6.0.0rc2}/CONTRIBUTING.md +0 -0
  75. {stackformers-5.1.1 → stackformers-6.0.0rc2}/Justfile +0 -0
  76. {stackformers-5.1.1 → stackformers-6.0.0rc2}/LICENSE +0 -0
  77. {stackformers-5.1.1 → stackformers-6.0.0rc2}/PLAN.md +0 -0
  78. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/api-guide.md +0 -0
  79. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/assets/social-preview.jpg +0 -0
  80. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/assets/social-preview.md +0 -0
  81. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/compatibility.md +0 -0
  82. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/improvement-plan.md +0 -0
  83. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/inference.md +0 -0
  84. {stackformers-5.1.1 → stackformers-6.0.0rc2}/docs/research.md +0 -0
  85. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/causal_language_model.py +0 -0
  86. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/encoder_decoder_onnxruntime.py +0 -0
  87. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/padded_and_packed.py +0 -0
  88. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/point_cloud_encoder.py +0 -0
  89. {stackformers-5.1.1 → stackformers-6.0.0rc2}/examples/subclassed_encoder.py +0 -0
  90. {stackformers-5.1.1 → stackformers-6.0.0rc2}/pytest.ini +0 -0
  91. {stackformers-5.1.1 → stackformers-6.0.0rc2}/ruff.toml +0 -0
  92. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/DEVLOG.md +0 -0
  93. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/_decoder_equations.py +0 -0
  94. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/_projection_packing.py +0 -0
  95. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/_result.py +0 -0
  96. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/alignment.py +0 -0
  97. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/all_valid_decoder.py +0 -0
  98. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/README.md +0 -0
  99. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/__init__.py +0 -0
  100. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/all_valid.py +0 -0
  101. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/bias.py +0 -0
  102. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/cache.py +0 -0
  103. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/cache_validation.py +0 -0
  104. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/cached.py +0 -0
  105. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/config.py +0 -0
  106. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/cross_attn.py +0 -0
  107. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/distance_bias.py +0 -0
  108. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/factory.py +0 -0
  109. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/layout.py +0 -0
  110. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/masking.py +0 -0
  111. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/onnx_backend.py +0 -0
  112. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/ops.py +0 -0
  113. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/packed_cross_attn.py +0 -0
  114. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/packed_self_attn.py +0 -0
  115. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/protocols.py +0 -0
  116. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/self_attn.py +0 -0
  117. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/attention/varlen_backend.py +0 -0
  118. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/config.py +0 -0
  119. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/cross_attender.py +0 -0
  120. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/decoder.py +0 -0
  121. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/decoder_cache.py +0 -0
  122. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/encoder.py +0 -0
  123. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/DEVLOG.md +0 -0
  124. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/README.md +0 -0
  125. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/__init__.py +0 -0
  126. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/config.py +0 -0
  127. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/factory.py +0 -0
  128. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/geglu.py +0 -0
  129. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/gelu.py +0 -0
  130. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/hardswish_glu.py +0 -0
  131. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/packed_geglu.py +0 -0
  132. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/packed_hardswish_glu.py +0 -0
  133. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/packed_swiglu.py +0 -0
  134. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/protocols.py +0 -0
  135. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/relu_squared.py +0 -0
  136. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/feedforward/swiglu.py +0 -0
  137. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/layers.py +0 -0
  138. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/README.md +0 -0
  139. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/config.py +0 -0
  140. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/head.py +0 -0
  141. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/head_cosine.py +0 -0
  142. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/masking.py +0 -0
  143. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/protocols.py +0 -0
  144. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/mlm/wrapper.py +0 -0
  145. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/norm/README.md +0 -0
  146. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/norm/__init__.py +0 -0
  147. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/norm/config.py +0 -0
  148. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/norm/factory.py +0 -0
  149. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/norm/protocols.py +0 -0
  150. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/packing.py +0 -0
  151. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/__init__.py +0 -0
  152. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/factory.py +0 -0
  153. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/learned.py +0 -0
  154. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/none.py +0 -0
  155. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/protocols.py +0 -0
  156. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/rope1d.py +0 -0
  157. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/positional/validation.py +0 -0
  158. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/preallocated_decoder.py +0 -0
  159. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/presets/README.md +0 -0
  160. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/presets/__init__.py +0 -0
  161. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/presets/cross_attender.py +0 -0
  162. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/presets/decoder.py +0 -0
  163. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/presets/encoder.py +0 -0
  164. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/presets/variable_width_encoder.py +0 -0
  165. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/py.typed +0 -0
  166. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/result/README.md +0 -0
  167. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/result/__init__.py +0 -0
  168. {stackformers-5.1.1 → stackformers-6.0.0rc2}/stackformers/sequence.py +0 -0
  169. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/__init__.py +0 -0
  170. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/__init__.py +0 -0
  171. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/legacy_api_rc1.json +0 -0
  172. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_all_valid.py +0 -0
  173. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_cached.py +0 -0
  174. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_config.py +0 -0
  175. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_contracts.py +0 -0
  176. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_cross_attn.py +0 -0
  177. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_cross_attn_cache.py +0 -0
  178. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_empty_rows.py +0 -0
  179. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_factory.py +0 -0
  180. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_geometry.py +0 -0
  181. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_kernels.py +0 -0
  182. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_legacy_api.py +0 -0
  183. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_masking.py +0 -0
  184. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_onnx_backend.py +0 -0
  185. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_ops.py +0 -0
  186. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_packed_cross_attn.py +0 -0
  187. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_packed_self_attn.py +0 -0
  188. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_sdpa_export.py +0 -0
  189. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_self_attn.py +0 -0
  190. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/attention/test_varlen_backend.py +0 -0
  191. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/conftest.py +0 -0
  192. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/export_utils.py +0 -0
  193. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/__init__.py +0 -0
  194. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/legacy_swiglu_4_6.json +0 -0
  195. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_config.py +0 -0
  196. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_factory.py +0 -0
  197. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_geglu.py +0 -0
  198. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_gelu.py +0 -0
  199. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_hardswish_glu.py +0 -0
  200. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_packed_geglu.py +0 -0
  201. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_packed_hardswish_glu.py +0 -0
  202. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_packed_swiglu.py +0 -0
  203. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_relu_squared.py +0 -0
  204. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/feedforward/test_swiglu.py +0 -0
  205. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/mlm/__init__.py +0 -0
  206. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/mlm/test_empty_selection.py +0 -0
  207. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/mlm/test_head.py +0 -0
  208. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/mlm/test_head_cosine.py +0 -0
  209. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/mlm/test_masking.py +0 -0
  210. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/mlm/test_wrapper.py +0 -0
  211. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/norm_topology_helpers.py +0 -0
  212. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/positional/__init__.py +0 -0
  213. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/positional/test_learned_pos.py +0 -0
  214. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/presets/__init__.py +0 -0
  215. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/presets/test_cross_attender.py +0 -0
  216. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/presets/test_decoder.py +0 -0
  217. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/presets/test_projection_packing.py +0 -0
  218. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_alignment.py +0 -0
  219. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_all_valid_decoder.py +0 -0
  220. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_cross_attender.py +0 -0
  221. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_decoder.py +0 -0
  222. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_decoder_cache.py +0 -0
  223. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_decoder_equations.py +0 -0
  224. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_encoder.py +0 -0
  225. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_encoder_decoder_example.py +0 -0
  226. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_examples.py +0 -0
  227. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_export_utils.py +0 -0
  228. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_layers.py +0 -0
  229. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_norm.py +0 -0
  230. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_packing.py +0 -0
  231. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_preallocated_decoder.py +0 -0
  232. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_projection_packing.py +0 -0
  233. {stackformers-5.1.1 → stackformers-6.0.0rc2}/tests/test_result.py +0 -0
  234. {stackformers-5.1.1 → stackformers-6.0.0rc2}/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,60 @@ 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.0rc2]
10
+
11
+ ### Bug Fixes
12
+
13
+ - Resolve `Encoder2d` stages through their registered module slots so replacement
14
+ changes forward execution and checkpoint state together, preserving parameter names.
15
+ - Accumulate pooling centroids in at least float32 while retaining float64 geometry,
16
+ avoiding float16 overflow for finite physical coordinate means.
17
+ - Remove a local coordinate origin before reducing normalization precision so small
18
+ float64 separations survive around large physical offsets.
19
+
20
+ ## [6.0.0rc1]
21
+
22
+ ### Backwards Incompatible Changes
23
+
24
+ - Replace base-based `RoPE2DConfig` with calibrated physical `r_min`/`r_max`
25
+ bounds. Supply positive finite bounds explicitly; obsolete `base` arguments
26
+ are rejected. RoPE2D and RoPEND now share one continuous-coordinate implementation.
27
+ - Store rotary frequencies as `[coords, bands]`, including when scalar bounds
28
+ broadcast across axes. The frequency buffer remains nonpersistent.
29
+
30
+ ### New Features
31
+
32
+ - Add `WindowEncoderStage2d` to share one partition and coordinate preparation
33
+ across injected 1D encoder blocks, and `Encoder2dLike` for spatial encoder consumers.
34
+ The composition example preserves sandwich normalization, explicit Q/K
35
+ normalization, and HardSwishGLU.
36
+
37
+ - Add `TransformerLayer2d` pre-norm residual blocks and `Encoder2d` for composable
38
+ spatial stages. Reuse injected feed-forward and normalization modules, preserve
39
+ padded/packed spatial records, and place pooling between residual blocks.
40
+
41
+ - Support independent `r_min` and `r_max` tuples per coordinate axis in RoPEND
42
+ and RoPE2D. Scalar bounds explicitly share a scale across axes. Supplied
43
+ physical coordinates may be nonuniform and are never reconstructed from indices.
44
+ - Add `WindowSelfAttention2d` and `CrossAttnPooling2d` for channels-last spatial
45
+ windows, with automatic boundary padding, boolean validity masks, and learned
46
+ rectangular output tiles that preserve channel width.
47
+ - Add `PackedTensor2d` and `PaddedTensor2d` for variable-sized spatial feature grids. Both window layers
48
+ preserve packed layouts without allocating a shared padded spatial canvas.
49
+ Padded records carry validity; packed records store only valid tokens with
50
+ integer grid indices distinct from nonuniform absolute coordinates. Cross-pooling
51
+ preserves its query anchors as output coordinates.
52
+ - Adapt 2D windows to the existing fused 1D self-/cross-attention modules,
53
+ preserving padded/packed backend dispatch and unsupported-GPU fallbacks.
54
+ Cross-pooling uses learned query features with geometry-derived RoPEND anchors.
55
+ - Accept injected positional-encoding modules in 2D layers. Omitted encodings use
56
+ window-calibrated RoPEND with per-window coordinate normalization, preserving
57
+ physical output coordinates across composed stages.
58
+ - Make 2D attention, coordinate preparation, and pooling query placement independently
59
+ injectable through protocols. Bind source/query coordinate frames with closures
60
+ and preserve versioned built-in geometry signatures in checkpoints.
61
+
62
+
9
63
  ## [5.1.1]
10
64
 
11
65
  ### Improvements
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stackformers
3
- Version: 5.1.1
3
+ Version: 6.0.0rc2
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.1"
7
+ version = "6.0.0rc2"
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)
@@ -40,6 +40,18 @@ from stackformers.attention import (
40
40
  build_self_attn,
41
41
  )
42
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
+ )
43
55
  from stackformers.config import DecoderConfig, EncoderConfig, LayerConfig
44
56
  from stackformers.cross_attender import (
45
57
  CrossAttenderLayer,
@@ -67,6 +79,13 @@ from stackformers.decoder_cache import (
67
79
  DecoderCrossAttentionCacheBuilder,
68
80
  )
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,6 +195,21 @@ from stackformers.sequence import (
176
195
  )
177
196
 
178
197
  __all__ = [
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",
179
213
  "AlignmentConfig",
180
214
  "AllValid",
181
215
  "materialize_padding_mask",
@@ -0,0 +1,243 @@
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
+ Coordinate arithmetic promotes float16 and bfloat16 to float32 and retains supplied
94
+ float64 precision. Normalization subtracts a valid local source origin before
95
+ computing its centered offsets; only the final normalized attention coordinates
96
+ are converted to float32. Query transforms reuse that same source origin and frame.
97
+ This preserves small representable separations around a large float64 origin.
98
+
99
+ Spacing estimates depend on valid adjacent pairs. Removing tokens can change the
100
+ estimated scale or select the unit fallback, even for the remaining physical
101
+ positions. Use an explicit physical-coordinate policy and calibrated RoPEND when
102
+ remaining source positions must retain the same coordinate scale after masking.
103
+ This data-dependent normalization policy remains a research choice, not a claim
104
+ of invariance to token removal.
105
+
106
+ This removes overall per-window translation and axis scale from default attention.
107
+ For example, source coordinates `[0, 1, 2, 3]` and pooled coordinates
108
+ `[0.5, 2.5, 4.5, 6.5]` have the same normalized offsets. Successive pooling stages
109
+ therefore do not need explicit accumulated-spacing metadata. All returned physical
110
+ coordinates stay in their original units, including the pooling query anchors.
111
+
112
+ For physical-scale-sensitive attention, inject a calibrated module explicitly:
113
+
114
+ ```python
115
+ from stackformers import RoPENDConfig, RotaryEmbeddingND
116
+
117
+ attention = WindowSelfAttention2d(
118
+ 96,
119
+ window_size=(4, 4),
120
+ num_heads=4,
121
+ rope=RotaryEmbeddingND(
122
+ RoPENDConfig(dim_head=24, coords=2, r_min=(0.5, 2.0), r_max=(32.0, 2048.0))
123
+ ),
124
+ )
125
+ ```
126
+
127
+ The minimum bounds describe the finest meaningful physical separation on each
128
+ axis; maximum bounds cover expected within-window offsets across the stages
129
+ using that calibration. Cross-pooling is single-head and needs `dim_head=dim`.
130
+ An injected encoding defaults to physical coordinates; an explicit `coordinates`
131
+ policy can independently select normalization. The encoding is registered inside
132
+ the existing attention module so device moves include its buffers.
133
+
134
+ ## Pooling query anchors
135
+
136
+ The default `CentroidQueryPositions` policy places learned query features shared
137
+ across windows. Each output query
138
+ is anchored at the mean of valid physical source coordinates in its corresponding
139
+ integer output region. For a `4x4 -> 2x2` window, the four anchors come from the
140
+ four `2x2` source regions. Irregular sizes assign source row `r` to output row
141
+ `floor(r*oh/wh)`, and likewise for columns. Each query still attends to every valid
142
+ source token in the whole window: region membership determines only its anchor.
143
+
144
+ An empty region uses the window's valid-coordinate centroid. A fully empty window
145
+ has invalid queries, yielding zero padded output tiles or no packed output tokens.
146
+ Anchors are computed before attention from geometry alone and remain the output
147
+ `abs_positions`. They are not recomputed using feature-dependent attention weights.
148
+ Coordinates retain their floating point dtype under AMP. The integer output tile
149
+ is row-major, with extents `ceil(H/wh)*oh` by `ceil(W/ww)*ow` and unchanged channels.
150
+
151
+ Centroid sums and counts use at least float32 accumulation, preserving float64 when
152
+ supplied. Physical anchors are cast back to the input coordinate dtype only after
153
+ the mean is computed, avoiding float16 overflow from otherwise finite centroids.
154
+
155
+ Default RoPEND computes rotary phases without coordinate autograd. A trainable
156
+ coordinate or query-position strategy requires an injected positional encoding
157
+ that differentiates through its coordinates to learn from the feature loss.
158
+ Returning differentiable physical output positions alone does not establish that
159
+ attention propagates gradients to geometry.
160
+
161
+ ## Independent extension points
162
+
163
+ Both layers accept `attention` and `coordinates`; pooling additionally accepts
164
+ `query_positions`. Constructor collaborators are typed against protocols:
165
+
166
+ | Dependency | Contract | Default implementation |
167
+ | --- | --- | --- |
168
+ | Self-attention | Existing `SelfAttn` | Existing fused-QKV 1D attention |
169
+ | Cross-attention | Existing `CrossAttn` | Existing fused-KV single-head 1D attention |
170
+ | Coordinate preparation | `WindowCoordinates` | `NormalizedWindowCoordinates` |
171
+ | Pooling query placement | `QueryPositions` | `CentroidQueryPositions` |
172
+
173
+ Default construction belongs to `factory.py`. The adapters do not import concrete
174
+ attention implementations, RoPEND configs, or centroid computation functions.
175
+ No optional dependency checks occur in `forward()`.
176
+
177
+ Each coordinate policy returns prepared sources and a closure bound to the same
178
+ coordinate transformation for queries. Pooling constructs physical output queries
179
+ once, transforms them for attention, then merges the attended features with the
180
+ original physical query positions. Custom nonlinear anchor rules therefore run
181
+ once in their intended physical frame, independently of normalization.
182
+
183
+ ```python
184
+ from stackformers import NormalizedWindowCoordinates
185
+
186
+ pooling = CrossAttnPooling2d(
187
+ 96,
188
+ window_size=(4, 4),
189
+ output_window_size=(2, 2),
190
+ attention=custom_cross_attention,
191
+ coordinates=NormalizedWindowCoordinates((4, 4)),
192
+ query_positions=custom_query_positions,
193
+ )
194
+ ```
195
+
196
+ An injected attention module owns its positional encoding; passing both
197
+ `attention` and `rope` is rejected rather than silently ignoring either one.
198
+ Custom attention defaults to `PhysicalCoordinates` unless `coordinates` is explicit.
199
+ An injected module can use another head count while retaining the same model width.
200
+ For reproducibility, explicitly supply all collaborators when experimenting with
201
+ alternative geometry or attention.
202
+
203
+ Implementations must honor the protocol contracts: preserve window ordering and
204
+ source validity, support padded and packed layouts, emit row-major full output
205
+ tiles for nonempty windows, and keep fully empty windows finite. Coordinate
206
+ policies preserve features and boundaries. Packed source slots are sorted within
207
+ each window. Attention returns feature tensors in query order with model width
208
+ unchanged. Use `nn.Module` for collaborators with parameters or buffers so PyTorch
209
+ registers them for optimization, device moves, and checkpoints. Custom strategies
210
+ remain responsible for compile/export compatibility of their operators.
211
+
212
+ To add a variant, implement the owning protocol in a separate file and inject it;
213
+ no edits to the adapters or their dispatch are needed. The default normalizer's
214
+ axis-aligned spacing assumption is a replaceable policy, not a tensor invariant.
215
+ Shifted or overlapping window topology would require a separate partition/merge
216
+ implementation; arbitrary window topology is not a supported injection point here.
217
+
218
+ ## Checkpoint compatibility
219
+
220
+ Built-in geometry modules store a persistent integer signature containing policy
221
+ identity, behavior revision, and relevant window/tile topology. Loading a different
222
+ policy or topology rejects the checkpoint rather than silently changing geometry.
223
+ Future behavior changes must retain the previous implementation as an injectable
224
+ variant or provide an explicit checkpoint migration and increment its revision.
225
+ Signature checks execute only during checkpoint loading.
226
+
227
+ A `state_dict` does not reconstruct an architecture. Save the construction recipe
228
+ alongside weights, including layer dimensions, explicit RoPEND calibration, and
229
+ custom collaborator configurations. RoPEND frequency buffers are nonpersistent;
230
+ geometry signatures do not encode an injected encoding's calibration or backend.
231
+ Custom modules own their state and compatibility checks. This guard protects the
232
+ built-in geometry policies, not arbitrary injected implementations.
233
+
234
+ ## Export and readiness
235
+
236
+ Padded records are the intended dynamic-width ONNX path. Values, validity,
237
+ coordinates, and extents are graph inputs and outputs. Packed token counts depend
238
+ on validity and metadata; packed export is not currently supported.
239
+
240
+ The API and rotary integration are being revised. Previous export results do not
241
+ validate this revision. Tests will be run only after the user declares the
242
+ implementation ready. Test sources and vector figures describe the projected cross-attention and
243
+ 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
+ ]
@@ -0,0 +1,52 @@
1
+ """Guard checkpoint loading against incompatible built-in geometry construction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ if TYPE_CHECKING:
11
+ from collections.abc import Mapping
12
+
13
+ from jaxtyping import Int
14
+ from torch import Tensor
15
+
16
+
17
+ class GeometryModule(nn.Module):
18
+ """Persist policy identity as a tensor without adding operations to forward graphs."""
19
+
20
+ _geometry_signature: Int[Tensor, "fields"]
21
+
22
+ def __init__(self, kind: int, revision: int, topology: tuple[int, ...]) -> None:
23
+ """Bind a permanent policy identifier, behavior revision, and construction topology."""
24
+ super().__init__()
25
+ self._geometry_identity = (kind, revision, *topology)
26
+ signature = torch.tensor(self._geometry_identity, dtype=torch.int64)
27
+ self.register_buffer("_geometry_signature", signature)
28
+ self.register_load_state_dict_pre_hook(self._validate_policy)
29
+
30
+ def _validate_policy(
31
+ self,
32
+ module: nn.Module,
33
+ state_dict: Mapping[str, Tensor],
34
+ prefix: str,
35
+ local_metadata: object,
36
+ strict: bool,
37
+ missing_keys: list[str],
38
+ unexpected_keys: list[str],
39
+ error_msgs: list[str],
40
+ ) -> None:
41
+ """Reject geometry mismatches at checkpoint loading, outside traced computation."""
42
+ key = prefix + "_geometry_signature"
43
+ if key not in state_dict:
44
+ return
45
+ saved = state_dict[key]
46
+ expected = saved.new_tensor(self._geometry_identity, dtype=torch.int64)
47
+ matches = saved.dtype == expected.dtype and torch.equal(saved, expected)
48
+ if not matches:
49
+ error_msgs.append(
50
+ f"{prefix}geometry differs from the checkpoint; reconstruct the original "
51
+ "policy or migrate its state explicitly"
52
+ )
@@ -0,0 +1,41 @@
1
+ """Place pooling queries at region centroids with an empty-region window fallback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from stackformers.attention2d._geometry_module import GeometryModule
8
+ from stackformers.attention2d.query_anchors import packed_queries, padded_queries, query_regions
9
+ from stackformers.attention2d.windows import validate_window
10
+
11
+ if TYPE_CHECKING:
12
+ from jaxtyping import Bool, Float, Int
13
+ from torch import Tensor
14
+
15
+ from stackformers.sequence import PackedTensor, PaddedTensor
16
+
17
+
18
+ class CentroidQueryPositions(GeometryModule):
19
+ """Use integer regions to anchor queries while retaining whole-window attention."""
20
+
21
+ regions: Bool[Tensor, "n s"]
22
+
23
+ def __init__(self, window: tuple[int, int], output: tuple[int, int]) -> None:
24
+ """Bind row-major source-to-query membership as a registered module buffer."""
25
+ validate_window(window)
26
+ validate_window(output)
27
+ super().__init__(3, 1, window + output)
28
+ self.register_buffer("regions", query_regions(window, output), persistent=False)
29
+
30
+ def padded(self, context: PaddedTensor, features: Float[Tensor, "n d"]) -> PaddedTensor:
31
+ """Repeat learned features with valid-region physical centroids."""
32
+ return padded_queries(context, features, self.regions)
33
+
34
+ def packed(
35
+ self,
36
+ context: PackedTensor,
37
+ slots: Int[Tensor, "nt"],
38
+ features: Float[Tensor, "n d"],
39
+ ) -> PackedTensor:
40
+ """Emit full packed tiles for nonempty windows and no tokens for empty ones."""
41
+ return packed_queries(context, slots, features, self.regions)