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,94 @@
1
+ """norm_fused — a plain norm run by a fused kernel at compute dtype.
2
+
3
+ Vision towers commonly keep their LayerNorms in FP32 while the rest of
4
+ the block runs in BF16, so every norm pays a dtype round trip plus an
5
+ unfused mean/variance pass. This replacement runs the norm in one fused
6
+ BF16 kernel and hands the result back in the host's dtype.
7
+
8
+ Qualification is the host's own dtype: the win comes from collapsing an
9
+ FP32 norm into a fused BF16 one, so a norm the host already runs in
10
+ BF16 is left alone (there is nothing to collapse), and the parity gate
11
+ adjudicates the numerical difference the dtype change introduces.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import torch
17
+
18
+ from .. import hub_kernel
19
+ from ...guard import CAST_OK, PROCEED, GuardedSeam
20
+
21
+ KERNEL_DEP = {
22
+ "provider": "hf",
23
+ "repo": "flashrt/flashrt-residual-norm-quant",
24
+ "version": ">=1",
25
+ }
26
+
27
+
28
+ class FusedNorm(GuardedSeam, torch.nn.Module):
29
+ """Drop-in for an affine LayerNorm, computed by a fused kernel."""
30
+
31
+ _frt_host_attr = "host_norm"
32
+ _frt_can_fallback = True
33
+
34
+ def __init__(self, original: torch.nn.Module):
35
+ super().__init__()
36
+ self.host_norm = original
37
+ ks = hub_kernel(KERNEL_DEP["repo"], KERNEL_DEP["version"])
38
+ self._fn = ks.layer_norm_bf16
39
+ self.register_buffer("w", original.weight.detach().to(
40
+ torch.bfloat16))
41
+ self.register_buffer("b", original.bias.detach().to(
42
+ torch.bfloat16))
43
+ self.eps = float(getattr(original, "eps", 1e-6))
44
+ self._frt_arm(dtypes=CAST_OK, device=self.w.device,
45
+ k=int(self.w.shape[0]))
46
+
47
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
48
+ admitted = self._frt_admit(x)
49
+ if admitted is not PROCEED:
50
+ return admitted
51
+ # the kernel's contract is 2D [rows, width]; hosts hand the norm
52
+ # whatever leading shape their block carries
53
+ shape = x.shape
54
+ flat = x.reshape(-1, shape[-1]).to(torch.bfloat16).contiguous()
55
+ y = self._fn(flat, self.w, self.b, self.eps)
56
+ return y.reshape(shape).to(x.dtype)
57
+
58
+ def __getattr__(self, name):
59
+ try:
60
+ return super().__getattr__(name)
61
+ except AttributeError:
62
+ return getattr(super().__getattr__("host_norm"), name)
63
+
64
+
65
+ def bind_norm_fused(original: torch.nn.Module,
66
+ host_dtypes=None) -> FusedNorm:
67
+ """Bind a fused norm, refusing where there is nothing to collapse.
68
+
69
+ ``host_dtypes`` is the set of input dtypes this norm was observed with
70
+ during calibration — one observation, not a statistic. A host already
71
+ running the norm at a compute dtype has nothing for this structure to
72
+ collapse, and the refusal names the dtype so it reads as "not in this
73
+ form" rather than "not supported".
74
+ """
75
+ if getattr(original, "weight", None) is None or \
76
+ getattr(original, "bias", None) is None:
77
+ raise ValueError("norm_fused: needs an affine norm (weight+bias)")
78
+ if host_dtypes and torch.float32 not in set(host_dtypes):
79
+ raise ValueError(
80
+ "norm_fused: host already runs this norm at compute "
81
+ f"dtype ({sorted(str(d) for d in host_dtypes)}) — nothing "
82
+ "to collapse")
83
+ bound = FusedNorm(original)
84
+ # bind-time smoke through the real entry point, at a 3D host shape:
85
+ # a stale build, a missing symbol, or a kernel whose rank contract
86
+ # moved must surface here as a clean bind refusal, not mid-forward
87
+ probe_in = torch.zeros(1, 2, bound.w.shape[0], device=bound.w.device)
88
+ probe = bound(probe_in)
89
+ if probe.shape != probe_in.shape or not torch.isfinite(probe).all():
90
+ raise ValueError(
91
+ f"refused: norm_fused bind smoke produced shape "
92
+ f"{tuple(probe.shape)}, "
93
+ f"finite={bool(torch.isfinite(probe).all())}")
94
+ return bound
@@ -0,0 +1,84 @@
1
+ """An affine LayerNorm that emits FP8 directly, at a consumer's scale.
2
+
3
+ The pipeline fact this serves: a vision block's pre-FFN norm output has
4
+ exactly one consumer, the FFN — and when that FFN is seated in FP8 form
5
+ its first act is to quantize its input. Emitting FP8 from the norm
6
+ itself (one fused kernel: no-affine LN + scale/shift + static quantize,
7
+ with scale=(gamma-1), shift=beta reproducing the affine norm exactly)
8
+ deletes the FFN's own input quantize and the norm's dtype round trip.
9
+
10
+ The hard precedent this respects: handing FP8 to a *host* consumer is
11
+ garbage-in-silence (measured 0.24 output match at the decoder norm
12
+ boundary). This producer is therefore only ever seated by the
13
+ negotiation pass that pairs it with an FP8-input seat as the direct
14
+ consumer — seat produces, seat consumes, and the consumer's FP8_ONLY
15
+ guard refuses loudly if anything else arrives between them. Whether
16
+ the pair actually pays is measured at bind, never assumed.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import torch
22
+
23
+ from .. import hub_kernel
24
+ from ...guard import CAST_OK, PROCEED, GuardedSeam
25
+
26
+ KERNEL_DEP = {
27
+ "provider": "hf",
28
+ "repo": "flashrt/adaptive-layernorm-producers",
29
+ "version": ">=1",
30
+ }
31
+
32
+
33
+ class FusedNormFp8Producer(GuardedSeam, torch.nn.Module):
34
+ """Drop-in for an affine LayerNorm whose sole consumer eats FP8."""
35
+
36
+ _frt_host_attr = "host_norm"
37
+ _frt_can_fallback = False # the consumer expects FP8; a BF16
38
+ # fallback here would feed the paired seat out of contract, so an
39
+ # out-of-form input must refuse loudly instead of degrading quietly
40
+
41
+ def __init__(self, original: torch.nn.Module,
42
+ act_scale: torch.Tensor):
43
+ super().__init__()
44
+ self.host_norm = original
45
+ ks = hub_kernel(KERNEL_DEP["repo"], KERNEL_DEP["version"])
46
+ self._fn = ks.ada_layer_norm_quant_fp8_bf16
47
+ # scale=(gamma-1), shift=beta: norm(x)*(1+scale)+shift is then
48
+ # exactly the host's affine LayerNorm, quantized
49
+ self.register_buffer("w", (original.weight.detach().float() - 1.0)
50
+ .to(torch.bfloat16).contiguous())
51
+ self.register_buffer("b", original.bias.detach()
52
+ .to(torch.bfloat16).contiguous())
53
+ self.register_buffer("act_scale",
54
+ act_scale.detach().reshape(1).float())
55
+ self.eps = float(getattr(original, "eps", 1e-6))
56
+ self._frt_arm(dtypes=CAST_OK, device=self.w.device,
57
+ k=int(self.w.shape[0]))
58
+
59
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
60
+ admitted = self._frt_admit(x)
61
+ if admitted is not PROCEED:
62
+ return admitted
63
+ shape = x.shape
64
+ flat = x.reshape(-1, shape[-1]).to(torch.bfloat16).contiguous()
65
+ y = self._fn(flat, self.w, self.b, self.act_scale, self.eps)
66
+ return y.reshape(shape)
67
+
68
+ def __getattr__(self, name):
69
+ try:
70
+ return super().__getattr__(name)
71
+ except AttributeError:
72
+ if name == "host_norm":
73
+ raise
74
+ return getattr(super().__getattr__("host_norm"), name)
75
+
76
+
77
+ def bind_norm_fp8_producer(original: torch.nn.Module,
78
+ act_scale: torch.Tensor
79
+ ) -> FusedNormFp8Producer:
80
+ if getattr(original, "weight", None) is None \
81
+ or getattr(original, "bias", None) is None:
82
+ raise ValueError("fp8 norm producer needs a two-sided affine "
83
+ "LayerNorm")
84
+ return FusedNormFp8Producer(original, act_scale)
@@ -0,0 +1,3 @@
1
+ from .bf16_flat import FlatPatchProjection, bind_flat_patch_projection
2
+
3
+ __all__ = ["FlatPatchProjection", "bind_flat_patch_projection"]
@@ -0,0 +1,139 @@
1
+ """BF16 lowering for processor-preflattened full-patch Conv3D modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Mapping, Sequence
6
+
7
+ import torch
8
+
9
+ from ...guard import CAST_OK, PROCEED, GuardedSeam
10
+
11
+ KERNEL_DEP = {
12
+ "provider": "hf",
13
+ "repo": "flashrt/flashrt-gemm-epilogues",
14
+ "version": ">=1",
15
+ }
16
+
17
+
18
+ def _kernel():
19
+ from flashrt_structures.impls import hub_kernel
20
+
21
+ return hub_kernel(KERNEL_DEP["repo"], KERNEL_DEP["version"])
22
+
23
+
24
+ class FlatPatchProjection(GuardedSeam, torch.nn.Module):
25
+ """Drop-in replacement for an exact full-patch Conv3D wrapper.
26
+
27
+ The host owns checkpoint-layout Conv3D weights ``[N,C,T,P,P]``. Binding
28
+ flattens them to the Hub API's ``[K,N]`` GEMM layout exactly once. The
29
+ retained host module remains the fallback and state-dict owner.
30
+ """
31
+
32
+ _frt_host_attr = "host_patch"
33
+ _frt_can_fallback = True
34
+
35
+ def __init__(
36
+ self,
37
+ weight_kn: torch.Tensor,
38
+ bias: torch.Tensor | None,
39
+ *,
40
+ row_capacity: int,
41
+ host_dtypes: Sequence[torch.dtype],
42
+ original: torch.nn.Module,
43
+ kernel=None,
44
+ ) -> None:
45
+ super().__init__()
46
+ self._weight_kn = weight_kn
47
+ self._bias = bias
48
+ self._row_capacity = int(row_capacity)
49
+ self.host_patch = original
50
+ self._ops = _kernel() if kernel is None else kernel
51
+ entry = (
52
+ "bf16_linear_bias_bf16"
53
+ if bias is not None
54
+ else "bf16_linear_bf16"
55
+ )
56
+ try:
57
+ self._fn = getattr(self._ops, entry)
58
+ except AttributeError as exc:
59
+ raise ValueError(
60
+ f"patch_projection Hub artifact lacks {entry}"
61
+ ) from exc
62
+ self._out = torch.empty(
63
+ self._row_capacity,
64
+ weight_kn.shape[1],
65
+ device=weight_kn.device,
66
+ dtype=torch.bfloat16,
67
+ )
68
+ self._frt_arm(
69
+ dtypes=tuple(host_dtypes) or CAST_OK,
70
+ device=weight_kn.device,
71
+ k=int(weight_kn.shape[0]),
72
+ row_capacity=self._row_capacity,
73
+ )
74
+
75
+ def __getattr__(self, name):
76
+ try:
77
+ return super().__getattr__(name)
78
+ except AttributeError:
79
+ if name == "host_patch":
80
+ raise
81
+ return getattr(super().__getattr__("host_patch"), name)
82
+
83
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
84
+ admitted = self._frt_admit(x)
85
+ if admitted is not PROCEED:
86
+ return admitted
87
+ flat = x.reshape(-1, self._weight_kn.shape[0])
88
+ rows = flat.shape[0]
89
+ out = self._out[:rows]
90
+ flat = flat.to(torch.bfloat16).contiguous()
91
+ if self._bias is None:
92
+ return self._fn(flat, self._weight_kn, out=out)
93
+ return self._fn(flat, self._weight_kn, self._bias, out=out)
94
+
95
+
96
+ @torch.no_grad()
97
+ def bind_flat_patch_projection(
98
+ weights: Mapping[str, torch.Tensor],
99
+ *,
100
+ row_profile: Sequence[int],
101
+ host_dtypes: Sequence[torch.dtype],
102
+ original: torch.nn.Module,
103
+ ) -> FlatPatchProjection:
104
+ """Bind a full-patch projection from checkpoint weights ``w[N,K]``."""
105
+ if not row_profile:
106
+ raise ValueError("patch_projection: no real patch rows were observed")
107
+ w = weights["w"]
108
+ if w.dim() != 2 or w.dtype is not torch.bfloat16 or not w.is_cuda:
109
+ raise ValueError(
110
+ "patch_projection requires CUDA BF16 checkpoint weights [N,K]"
111
+ )
112
+ b = weights.get("b")
113
+ if b is not None:
114
+ if b.shape != (w.shape[0],):
115
+ raise ValueError("patch_projection bias width does not match N")
116
+ b = b.detach().to(torch.bfloat16).contiguous()
117
+ weight_kn = w.detach().t().contiguous()
118
+ capacity = max(int(row) for row in row_profile)
119
+ bound = FlatPatchProjection(
120
+ weight_kn,
121
+ b,
122
+ row_capacity=capacity,
123
+ host_dtypes=host_dtypes,
124
+ original=original,
125
+ )
126
+ # A fallback-capable seam must prove the formal artifact launches at bind
127
+ # time; otherwise a stale package would look numerically perfect by
128
+ # silently running the retained host.
129
+ sample_dtype = next(iter(host_dtypes), torch.bfloat16)
130
+ sample = torch.zeros(
131
+ capacity,
132
+ w.shape[1],
133
+ device=w.device,
134
+ dtype=sample_dtype,
135
+ )
136
+ bound(sample)
137
+ if bound._frt_guard is not None:
138
+ bound._frt_guard.calls = 0
139
+ return bound
@@ -0,0 +1,10 @@
1
+ """The plain-norm decoder tower region: the prefix-building pass.
2
+
3
+ The tower that fills the cache another stack later attends over: plain
4
+ RMS norms (no conditioning), bias-free attention and gated FFN, one
5
+ forward per observation with ``use_cache``. Its chain candidate
6
+ re-expresses the per-layer loop in static-FP8 hub primitives while
7
+ writing host-layout keys back into the host's own cache, so every
8
+ downstream consumer — the sibling chain or the host fallback — reads
9
+ what it always read.
10
+ """