flashrt-structures 0.2.0__py3-none-any.whl

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 (122) hide show
  1. flashrt_structures/__init__.py +174 -0
  2. flashrt_structures/adapters/__init__.py +55 -0
  3. flashrt_structures/adapters/diffusers_attention.py +237 -0
  4. flashrt_structures/adapters/diffusers_rotary_attention.py +239 -0
  5. flashrt_structures/adapters/factored_qk_norm_rope.py +252 -0
  6. flashrt_structures/adapters/factored_two_way_attention.py +99 -0
  7. flashrt_structures/adapters/gemma_attention.py +226 -0
  8. flashrt_structures/adapters/packed_qkv_rope.py +342 -0
  9. flashrt_structures/adapters/packed_stream_qk_norm_rope.py +376 -0
  10. flashrt_structures/adapters/qwen_per_head_qk_norm_rope.py +231 -0
  11. flashrt_structures/adapters/sglang_engine.py +207 -0
  12. flashrt_structures/adapters/transformers_attention_interface.py +73 -0
  13. flashrt_structures/adapters/transformers_gated_delta.py +152 -0
  14. flashrt_structures/adapters/transformers_gated_delta_fused.py +96 -0
  15. flashrt_structures/adapters/vllm_engine.py +424 -0
  16. flashrt_structures/adjudicate.py +85 -0
  17. flashrt_structures/aot.py +191 -0
  18. flashrt_structures/autobuild.py +2052 -0
  19. flashrt_structures/beta/__init__.py +43 -0
  20. flashrt_structures/beta/conform.py +94 -0
  21. flashrt_structures/beta/joins.py +113 -0
  22. flashrt_structures/beta/negotiate.py +84 -0
  23. flashrt_structures/beta/ports.py +140 -0
  24. flashrt_structures/decisions.py +80 -0
  25. flashrt_structures/discover.py +623 -0
  26. flashrt_structures/explain.py +70 -0
  27. flashrt_structures/frontdoor.py +572 -0
  28. flashrt_structures/gates.py +465 -0
  29. flashrt_structures/guard.py +421 -0
  30. flashrt_structures/handle.py +189 -0
  31. flashrt_structures/impls/__init__.py +219 -0
  32. flashrt_structures/impls/adaln_producer/__init__.py +8 -0
  33. flashrt_structures/impls/adaln_producer/broker.py +116 -0
  34. flashrt_structures/impls/adaln_producer/fused.py +388 -0
  35. flashrt_structures/impls/adarms_stack/__init__.py +8 -0
  36. flashrt_structures/impls/adarms_stack/fp8_chain.py +832 -0
  37. flashrt_structures/impls/adarms_stack/region.py +102 -0
  38. flashrt_structures/impls/attention_core/__init__.py +132 -0
  39. flashrt_structures/impls/attention_core/fa2_seqused.py +458 -0
  40. flashrt_structures/impls/attention_core/fa4_cute.py +154 -0
  41. flashrt_structures/impls/attention_core/fa4_fp8.py +178 -0
  42. flashrt_structures/impls/attention_core/masked_mha.py +158 -0
  43. flashrt_structures/impls/attention_core/two_way_fa2.py +220 -0
  44. flashrt_structures/impls/cadence_static/__init__.py +18 -0
  45. flashrt_structures/impls/cadence_static/buffers.py +122 -0
  46. flashrt_structures/impls/cadence_static/cross_attention.py +187 -0
  47. flashrt_structures/impls/chain_elements.py +89 -0
  48. flashrt_structures/impls/decode_loop/__init__.py +0 -0
  49. flashrt_structures/impls/decode_loop/fp8_kv.py +206 -0
  50. flashrt_structures/impls/decode_loop/mtp_speculative.py +245 -0
  51. flashrt_structures/impls/decode_loop/whole_step.py +852 -0
  52. flashrt_structures/impls/decoder_block/__init__.py +6 -0
  53. flashrt_structures/impls/decoder_block/attn_sublayer.py +110 -0
  54. flashrt_structures/impls/decoder_block/fused.py +167 -0
  55. flashrt_structures/impls/decoder_ffn/__init__.py +0 -0
  56. flashrt_structures/impls/decoder_ffn/fp8_static.py +310 -0
  57. flashrt_structures/impls/decoder_ffn/fp8_static.yaml +22 -0
  58. flashrt_structures/impls/decoder_ffn/w4a16_static.py +221 -0
  59. flashrt_structures/impls/decoder_ffn/w8a16_static.py +183 -0
  60. flashrt_structures/impls/dit_stack/__init__.py +11 -0
  61. flashrt_structures/impls/dit_stack/fp4_chain.py +417 -0
  62. flashrt_structures/impls/dit_stack/region.py +86 -0
  63. flashrt_structures/impls/fixed_iter/__init__.py +29 -0
  64. flashrt_structures/impls/fixed_iter/openpi.py +264 -0
  65. flashrt_structures/impls/fixed_iter/protocol.py +94 -0
  66. flashrt_structures/impls/gated_delta_core/__init__.py +3 -0
  67. flashrt_structures/impls/gated_delta_core/fused_layer.py +545 -0
  68. flashrt_structures/impls/gated_delta_core/hub_v3.py +152 -0
  69. flashrt_structures/impls/graph_lowering/__init__.py +27 -0
  70. flashrt_structures/impls/graph_lowering/pi052_denoise.py +179 -0
  71. flashrt_structures/impls/graph_lowering/protocol.py +76 -0
  72. flashrt_structures/impls/graph_lowering/qwen3_vl.py +364 -0
  73. flashrt_structures/impls/linear_proj/__init__.py +0 -0
  74. flashrt_structures/impls/linear_proj/fp8_static.py +270 -0
  75. flashrt_structures/impls/linear_proj/nvfp4_balance.py +131 -0
  76. flashrt_structures/impls/linear_proj/nvfp4_dynamic.py +182 -0
  77. flashrt_structures/impls/linear_proj/w8a16_static.py +230 -0
  78. flashrt_structures/impls/modnorm_qkv_chain/__init__.py +0 -0
  79. flashrt_structures/impls/modnorm_qkv_chain/fp8_ptok_table.py +291 -0
  80. flashrt_structures/impls/moe_experts/__init__.py +9 -0
  81. flashrt_structures/impls/moe_experts/nvfp4_dynamic.py +208 -0
  82. flashrt_structures/impls/moe_experts/nvfp4_w4a16.py +129 -0
  83. flashrt_structures/impls/norm_fused/__init__.py +3 -0
  84. flashrt_structures/impls/norm_fused/bf16.py +94 -0
  85. flashrt_structures/impls/norm_fused/fp8_producer.py +84 -0
  86. flashrt_structures/impls/patch_projection/__init__.py +3 -0
  87. flashrt_structures/impls/patch_projection/bf16_flat.py +139 -0
  88. flashrt_structures/impls/prefill_tower/__init__.py +10 -0
  89. flashrt_structures/impls/prefill_tower/fp8_chain.py +955 -0
  90. flashrt_structures/impls/prefill_tower/region.py +99 -0
  91. flashrt_structures/impls/qk_norm_rope/__init__.py +12 -0
  92. flashrt_structures/impls/qk_norm_rope/per_head_gqa.py +199 -0
  93. flashrt_structures/impls/qk_norm_rope/projection_bf16.py +165 -0
  94. flashrt_structures/impls/qkv_pack/__init__.py +5 -0
  95. flashrt_structures/impls/qkv_pack/bf16.py +110 -0
  96. flashrt_structures/impls/qkv_pack/fp8_static.py +435 -0
  97. flashrt_structures/impls/qkv_pack/nvfp4_balance.py +218 -0
  98. flashrt_structures/impls/qkv_rope/__init__.py +3 -0
  99. flashrt_structures/impls/qkv_rope/packed_bias_bf16.py +143 -0
  100. flashrt_structures/impls/step_table.py +113 -0
  101. flashrt_structures/impls/vision_ffn/__init__.py +0 -0
  102. flashrt_structures/impls/vision_ffn/fp8_static.py +261 -0
  103. flashrt_structures/impls/vision_ffn/nvfp4_balance.py +211 -0
  104. flashrt_structures/impls/vision_tower/__init__.py +7 -0
  105. flashrt_structures/impls/vision_tower/fp8_chain.py +533 -0
  106. flashrt_structures/impls/vision_tower/region.py +91 -0
  107. flashrt_structures/matrix.py +126 -0
  108. flashrt_structures/points.py +368 -0
  109. flashrt_structures/prequantized.py +131 -0
  110. flashrt_structures/quantize_on_adopt.py +94 -0
  111. flashrt_structures/recipe.py +438 -0
  112. flashrt_structures/regions.py +208 -0
  113. flashrt_structures/schemes.py +490 -0
  114. flashrt_structures/stages.py +298 -0
  115. flashrt_structures/storage.py +255 -0
  116. flashrt_structures/swap.py +398 -0
  117. flashrt_structures/workspace.py +110 -0
  118. flashrt_structures-0.2.0.dist-info/METADATA +140 -0
  119. flashrt_structures-0.2.0.dist-info/RECORD +122 -0
  120. flashrt_structures-0.2.0.dist-info/WHEEL +5 -0
  121. flashrt_structures-0.2.0.dist-info/licenses/LICENSE +202 -0
  122. flashrt_structures-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,191 @@
1
+ """Whole-graph ahead-of-time packaging for swapped modules.
2
+
3
+ Graph integrity is a first-class property of the structures runtime:
4
+ a swapped module's hot path carries no Python bookkeeping (guards
5
+ qualify at bind time and step aside under compilation), so the whole
6
+ forward exports as one graph with the Hub kernels riding along as
7
+ ``torch.library`` ops. This module turns that property into an
8
+ artifact: ``aot_package`` exports the module and compiles it with
9
+ AOTInductor into a self-contained package on disk; ``aot_load`` brings
10
+ it back as a callable that replays the compiled graph with no dynamo
11
+ in the loop and no JIT cost at first call.
12
+
13
+ The scoring suite treats an AoT arm like any other treated form:
14
+ stepwise parity, repeat chains, detach, and dual-baseline timing —
15
+ the package is a faster body for the same declared plan, never a
16
+ change of plan.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import pathlib
22
+
23
+ import torch
24
+
25
+ #: True while ``torch.export`` traces a module through this door.
26
+ #: Export functionalization supports in-place writes only into
27
+ #: *registered* buffers (it lifts them as graph outputs); structure
28
+ #: code holding pool-leased plain-attribute tensors checks this flag
29
+ #: and re-homes them as owned registered buffers before writing.
30
+ _EXPORTING = False
31
+
32
+
33
+ def is_exporting() -> bool:
34
+ return _EXPORTING
35
+
36
+
37
+ def _own_leased_stashes(module: torch.nn.Module) -> int:
38
+ """Re-home pool-leased stash tensors as registered buffers.
39
+
40
+ The pack heads write later siblings into stash tensors with a
41
+ plain ``copy_``. Export functionalization lifts an in-place write
42
+ only when its target is a *registered buffer* (the mutation
43
+ becomes a graph output); a pool-leased plain-attribute tensor is
44
+ inexpressible and kills the export. Re-homing has to happen here,
45
+ before tracing — inside a traced forward the module would be
46
+ mutated with fake tensors. The owned copy detaches the tensor
47
+ from the workspace pool for this module only; readers resolve the
48
+ same attribute name and see the registered buffer.
49
+ """
50
+ owned = 0
51
+ for m in module.modules():
52
+ splits = getattr(m, "splits", None)
53
+ if not isinstance(splits, (list, tuple)) or len(splits) < 2:
54
+ continue
55
+ for i in range(1, len(splits)):
56
+ name = f"stash{i}"
57
+ t = m.__dict__.get(name)
58
+ if t is not None and torch.is_tensor(t):
59
+ del m.__dict__[name]
60
+ m.register_buffer(name, t.detach().clone(),
61
+ persistent=False)
62
+ owned += 1
63
+ return owned
64
+
65
+ __all__ = ["aot_package", "aot_package_external", "aot_load", "AotModule"]
66
+
67
+
68
+ def aot_package(module: torch.nn.Module, args=(), kwargs=None,
69
+ package_path="module_aot.pt2",
70
+ external_weights: bool = False,
71
+ inductor_configs=None) -> str:
72
+ """Export ``module`` on example inputs and AOT-compile the graph.
73
+
74
+ Returns the package path. Raises on graph breaks or export
75
+ failure — a partial graph is a defect to fix at the seam, not a
76
+ fallback to hide.
77
+
78
+ ``external_weights=True`` keeps the constants out of the compiled
79
+ binary: the package carries the graph alone and the caller supplies
80
+ the weights at load time (:func:`aot_load` with ``weights=``). This
81
+ is the form for a module that must keep serving from its live
82
+ parameters — baking would put a second copy of every weight on the
83
+ card — and doubles as the deployment shape where one graph binary
84
+ serves many checkpoints.
85
+ """
86
+ if not torch.cuda.is_available():
87
+ raise RuntimeError(
88
+ "refused: AOT packaging compiles for the present GPU; "
89
+ "no CUDA device is visible")
90
+ kwargs = dict(kwargs or {})
91
+ _own_leased_stashes(module)
92
+ global _EXPORTING
93
+ _EXPORTING = True
94
+ try:
95
+ with torch.no_grad():
96
+ exported = torch.export.export(module, args=tuple(args),
97
+ kwargs=kwargs)
98
+ finally:
99
+ _EXPORTING = False
100
+ configs = dict(inductor_configs or {})
101
+ if external_weights:
102
+ configs["aot_inductor.package_constants_in_so"] = False
103
+ out = torch._inductor.aoti_compile_and_package(
104
+ exported, package_path=str(pathlib.Path(package_path)),
105
+ inductor_configs=configs or None)
106
+ return str(out)
107
+
108
+
109
+ def aot_package_external(module: torch.nn.Module, args=(), kwargs=None,
110
+ package_path="module_aot.pt2",
111
+ inductor_configs=None):
112
+ """External-weights packaging: returns ``(path, weights)``.
113
+
114
+ ``weights`` is the complete name→tensor map the package will ask
115
+ for at load — parameters, buffers persistent or not, and the
116
+ tensor constants export lifted (plain-attribute tensors an impl
117
+ holds). Handing exactly this map to :func:`aot_load` makes the
118
+ runtime borrow every one of them in place: no second copy of any
119
+ weight, and buffer mutations land in the caller's tensors.
120
+ """
121
+ if not torch.cuda.is_available():
122
+ raise RuntimeError(
123
+ "refused: AOT packaging compiles for the present GPU; "
124
+ "no CUDA device is visible")
125
+ kwargs = dict(kwargs or {})
126
+ _own_leased_stashes(module)
127
+ global _EXPORTING
128
+ _EXPORTING = True
129
+ try:
130
+ with torch.no_grad():
131
+ exported = torch.export.export(module, args=tuple(args),
132
+ kwargs=kwargs)
133
+ finally:
134
+ _EXPORTING = False
135
+ weights = dict(module.named_parameters())
136
+ weights.update(dict(module.named_buffers()))
137
+ weights.update({k: v for k, v in (exported.constants or {}).items()
138
+ if torch.is_tensor(v)})
139
+ configs = dict(inductor_configs or {})
140
+ configs["aot_inductor.package_constants_in_so"] = False
141
+ out = torch._inductor.aoti_compile_and_package(
142
+ exported, package_path=str(pathlib.Path(package_path)),
143
+ inductor_configs=configs)
144
+ return str(out), weights
145
+
146
+
147
+ def aot_load(package_path: str, weights=None):
148
+ """Load an AOT package back as a callable graph.
149
+
150
+ ``weights`` is a name→tensor mapping (a module ``state_dict``) for
151
+ packages built with ``external_weights=True``. The runtime borrows
152
+ the tensors in place (``user_managed``): no copy is made, and a
153
+ graph that mutates a buffer mutates the caller's tensor — which is
154
+ the point, for state the rest of the pipeline keeps reading.
155
+ Missing names fail loudly with the exact FQNs.
156
+ """
157
+ compiled = torch._inductor.aoti_load_package(str(package_path))
158
+ if weights is not None:
159
+ fqns = compiled.get_constant_fqns()
160
+ missing = [f for f in fqns if f not in weights]
161
+ if missing:
162
+ raise ValueError(
163
+ f"aot_load: {len(missing)} constant(s) absent from the "
164
+ f"supplied weights, first: {missing[:5]}")
165
+ compiled.load_constants(
166
+ {f: weights[f] for f in fqns},
167
+ check_full_update=True, user_managed=True)
168
+ return compiled
169
+
170
+
171
+ class AotModule(torch.nn.Module):
172
+ """Drop-in stand-in that replays the packaged graph.
173
+
174
+ Attribute lookups fall through to the host module, so pipeline
175
+ glue that introspects config/dtype keeps working; ``host`` gives
176
+ the original back for detach.
177
+ """
178
+
179
+ def __init__(self, compiled, host: torch.nn.Module):
180
+ super().__init__()
181
+ object.__setattr__(self, "_compiled", compiled)
182
+ object.__setattr__(self, "host", host)
183
+
184
+ def forward(self, *args, **kwargs):
185
+ return self._compiled(*args, **kwargs)
186
+
187
+ def __getattr__(self, name):
188
+ try:
189
+ return super().__getattr__(name)
190
+ except AttributeError:
191
+ return getattr(object.__getattribute__(self, "host"), name)