Add Kernel Hub build/torch-universal + torch-cpu for get_kernel (szl-maskmod, version 1)
Browse files- build/torch-cpu/metadata.json +13 -0
- build/torch-cpu/szl_maskmod/__init__.py +7 -0
- build/torch-cpu/szl_maskmod/_chain.py +35 -0
- build/torch-cpu/szl_maskmod/_ops.py +54 -0
- build/torch-universal/metadata.json +13 -0
- build/torch-universal/szl_maskmod/__init__.py +7 -0
- build/torch-universal/szl_maskmod/_chain.py +35 -0
- build/torch-universal/szl_maskmod/_ops.py +54 -0
build/torch-cpu/metadata.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "szl-maskmod",
|
| 3 |
+
"version": 1,
|
| 4 |
+
"summary": "SZL original Flex-silhouette score_mod + block-mask attention with SHA3 receipts (CPU torch)",
|
| 5 |
+
"license": "Apache-2.0",
|
| 6 |
+
"universal": true,
|
| 7 |
+
"python-depends": [],
|
| 8 |
+
"id": "_szl_maskmod_cpu_010",
|
| 9 |
+
"backend": {
|
| 10 |
+
"type": "cpu"
|
| 11 |
+
},
|
| 12 |
+
"doctrine": "Lambda=Conjecture 1 (advisory)"
|
| 13 |
+
}
|
build/torch-cpu/szl_maskmod/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 SZL Holdings
|
| 3 |
+
from ._chain import ReceiptChain
|
| 4 |
+
from ._ops import maskmod_attn, selfcheck
|
| 5 |
+
|
| 6 |
+
__all__ = ["ReceiptChain", "maskmod_attn", "selfcheck"]
|
| 7 |
+
__version__ = "0.1.0"
|
build/torch-cpu/szl_maskmod/_chain.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 SZL Holdings
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import hashlib, json
|
| 5 |
+
from typing import Any, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
GENESIS = "0" * 64
|
| 8 |
+
|
| 9 |
+
def _canon(obj: Any) -> bytes:
|
| 10 |
+
return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
| 11 |
+
|
| 12 |
+
def _sha3(body: bytes) -> str:
|
| 13 |
+
return hashlib.sha3_256(body).hexdigest()
|
| 14 |
+
|
| 15 |
+
class ReceiptChain:
|
| 16 |
+
def __init__(self) -> None:
|
| 17 |
+
self._rows: List[dict] = []
|
| 18 |
+
def emit(self, payload: dict) -> str:
|
| 19 |
+
prev = self._rows[-1]["digest"] if self._rows else GENESIS
|
| 20 |
+
body = dict(payload); body["seq"] = len(self._rows); body["prev"] = prev
|
| 21 |
+
digest = _sha3(_canon(body))
|
| 22 |
+
self._rows.append({**body, "digest": digest})
|
| 23 |
+
return digest
|
| 24 |
+
def verify(self) -> Tuple[bool, int, int]:
|
| 25 |
+
prev = GENESIS
|
| 26 |
+
for i, row in enumerate(self._rows):
|
| 27 |
+
body = {k: v for k, v in row.items() if k != "digest"}
|
| 28 |
+
if row.get("prev") != prev or _sha3(_canon(body)) != row.get("digest"):
|
| 29 |
+
return False, i, i
|
| 30 |
+
prev = row["digest"]
|
| 31 |
+
return True, len(self._rows), -1
|
| 32 |
+
def head(self) -> Optional[str]:
|
| 33 |
+
return self._rows[-1]["digest"] if self._rows else None
|
| 34 |
+
def __len__(self) -> int:
|
| 35 |
+
return len(self._rows)
|
build/torch-cpu/szl_maskmod/_ops.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 SZL Holdings
|
| 3 |
+
"""Original score_mod + block-mask attention. Not copied from flex_attention.py."""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
from typing import Callable, Optional
|
| 6 |
+
import torch
|
| 7 |
+
from ._chain import ReceiptChain
|
| 8 |
+
|
| 9 |
+
ScoreMod = Callable[[torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor]
|
| 10 |
+
|
| 11 |
+
def _dense_attn(q, k, v, *, causal, score_mod, block_mask, scale):
|
| 12 |
+
b, h, tq, d = q.shape
|
| 13 |
+
tkv = k.shape[2]
|
| 14 |
+
sm = (d ** -0.5) if scale is None else scale
|
| 15 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) * sm
|
| 16 |
+
q_idx = torch.arange(tq, device=q.device)[:, None]
|
| 17 |
+
k_idx = torch.arange(tkv, device=q.device)[None, :]
|
| 18 |
+
if causal:
|
| 19 |
+
scores = scores.masked_fill(q_idx < k_idx, float("-inf"))
|
| 20 |
+
if block_mask is not None:
|
| 21 |
+
scores = scores.masked_fill(~block_mask, float("-inf"))
|
| 22 |
+
if score_mod is not None:
|
| 23 |
+
scores = score_mod(scores, q_idx, k_idx)
|
| 24 |
+
p = torch.softmax(scores, dim=-1)
|
| 25 |
+
p = torch.nan_to_num(p, nan=0.0)
|
| 26 |
+
return torch.matmul(p, v)
|
| 27 |
+
|
| 28 |
+
def maskmod_attn(
|
| 29 |
+
q, k, v, *,
|
| 30 |
+
score_mod: Optional[ScoreMod] = None,
|
| 31 |
+
block_mask: Optional[torch.Tensor] = None,
|
| 32 |
+
causal: bool = False,
|
| 33 |
+
chain: Optional[ReceiptChain] = None,
|
| 34 |
+
scale: Optional[float] = None,
|
| 35 |
+
):
|
| 36 |
+
y = _dense_attn(q, k, v, causal=causal, score_mod=score_mod, block_mask=block_mask, scale=scale)
|
| 37 |
+
if chain is not None:
|
| 38 |
+
mid = "none" if score_mod is None else getattr(score_mod, "__name__", type(score_mod).__name__)
|
| 39 |
+
bdigest = "none" if block_mask is None else f"sum={float(block_mask.to(torch.float32).sum().item()):.6g}"
|
| 40 |
+
chain.emit({"op": "maskmod_attn", "score_mod": mid, "block_mask": bdigest,
|
| 41 |
+
"causal": causal, "q_shape": list(q.shape), "lambda": "Conjecture 1"})
|
| 42 |
+
return y
|
| 43 |
+
|
| 44 |
+
def selfcheck() -> dict:
|
| 45 |
+
torch.manual_seed(20260828)
|
| 46 |
+
q = k = v = torch.randn(1, 2, 8, 16)
|
| 47 |
+
chain = ReceiptChain()
|
| 48 |
+
y = maskmod_attn(q, k, v, causal=True, chain=chain)
|
| 49 |
+
ref = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0)
|
| 50 |
+
err = float((y - ref).abs().max().item())
|
| 51 |
+
ok_c, depth, brk = chain.verify()
|
| 52 |
+
ok = bool(err < 1e-5 and ok_c)
|
| 53 |
+
return {"ok": ok, "max_abs_vs_sdpa_causal": err, "chain_ok": ok_c, "chain_depth": depth,
|
| 54 |
+
"lambda": "Conjecture 1", "note": "correctness vs SDPA causal; no speedup claimed"}
|
build/torch-universal/metadata.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "szl-maskmod",
|
| 3 |
+
"version": 1,
|
| 4 |
+
"summary": "SZL original Flex-silhouette score_mod + block-mask attention with SHA3 receipts (CPU torch)",
|
| 5 |
+
"license": "Apache-2.0",
|
| 6 |
+
"universal": true,
|
| 7 |
+
"python-depends": [],
|
| 8 |
+
"id": "_szl_maskmod_universal_010",
|
| 9 |
+
"backend": {
|
| 10 |
+
"type": "cpu"
|
| 11 |
+
},
|
| 12 |
+
"doctrine": "Lambda=Conjecture 1 (advisory)"
|
| 13 |
+
}
|
build/torch-universal/szl_maskmod/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 SZL Holdings
|
| 3 |
+
from ._chain import ReceiptChain
|
| 4 |
+
from ._ops import maskmod_attn, selfcheck
|
| 5 |
+
|
| 6 |
+
__all__ = ["ReceiptChain", "maskmod_attn", "selfcheck"]
|
| 7 |
+
__version__ = "0.1.0"
|
build/torch-universal/szl_maskmod/_chain.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 SZL Holdings
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import hashlib, json
|
| 5 |
+
from typing import Any, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
GENESIS = "0" * 64
|
| 8 |
+
|
| 9 |
+
def _canon(obj: Any) -> bytes:
|
| 10 |
+
return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
| 11 |
+
|
| 12 |
+
def _sha3(body: bytes) -> str:
|
| 13 |
+
return hashlib.sha3_256(body).hexdigest()
|
| 14 |
+
|
| 15 |
+
class ReceiptChain:
|
| 16 |
+
def __init__(self) -> None:
|
| 17 |
+
self._rows: List[dict] = []
|
| 18 |
+
def emit(self, payload: dict) -> str:
|
| 19 |
+
prev = self._rows[-1]["digest"] if self._rows else GENESIS
|
| 20 |
+
body = dict(payload); body["seq"] = len(self._rows); body["prev"] = prev
|
| 21 |
+
digest = _sha3(_canon(body))
|
| 22 |
+
self._rows.append({**body, "digest": digest})
|
| 23 |
+
return digest
|
| 24 |
+
def verify(self) -> Tuple[bool, int, int]:
|
| 25 |
+
prev = GENESIS
|
| 26 |
+
for i, row in enumerate(self._rows):
|
| 27 |
+
body = {k: v for k, v in row.items() if k != "digest"}
|
| 28 |
+
if row.get("prev") != prev or _sha3(_canon(body)) != row.get("digest"):
|
| 29 |
+
return False, i, i
|
| 30 |
+
prev = row["digest"]
|
| 31 |
+
return True, len(self._rows), -1
|
| 32 |
+
def head(self) -> Optional[str]:
|
| 33 |
+
return self._rows[-1]["digest"] if self._rows else None
|
| 34 |
+
def __len__(self) -> int:
|
| 35 |
+
return len(self._rows)
|
build/torch-universal/szl_maskmod/_ops.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 SZL Holdings
|
| 3 |
+
"""Original score_mod + block-mask attention. Not copied from flex_attention.py."""
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
from typing import Callable, Optional
|
| 6 |
+
import torch
|
| 7 |
+
from ._chain import ReceiptChain
|
| 8 |
+
|
| 9 |
+
ScoreMod = Callable[[torch.Tensor, torch.Tensor, torch.Tensor], torch.Tensor]
|
| 10 |
+
|
| 11 |
+
def _dense_attn(q, k, v, *, causal, score_mod, block_mask, scale):
|
| 12 |
+
b, h, tq, d = q.shape
|
| 13 |
+
tkv = k.shape[2]
|
| 14 |
+
sm = (d ** -0.5) if scale is None else scale
|
| 15 |
+
scores = torch.matmul(q, k.transpose(-2, -1)) * sm
|
| 16 |
+
q_idx = torch.arange(tq, device=q.device)[:, None]
|
| 17 |
+
k_idx = torch.arange(tkv, device=q.device)[None, :]
|
| 18 |
+
if causal:
|
| 19 |
+
scores = scores.masked_fill(q_idx < k_idx, float("-inf"))
|
| 20 |
+
if block_mask is not None:
|
| 21 |
+
scores = scores.masked_fill(~block_mask, float("-inf"))
|
| 22 |
+
if score_mod is not None:
|
| 23 |
+
scores = score_mod(scores, q_idx, k_idx)
|
| 24 |
+
p = torch.softmax(scores, dim=-1)
|
| 25 |
+
p = torch.nan_to_num(p, nan=0.0)
|
| 26 |
+
return torch.matmul(p, v)
|
| 27 |
+
|
| 28 |
+
def maskmod_attn(
|
| 29 |
+
q, k, v, *,
|
| 30 |
+
score_mod: Optional[ScoreMod] = None,
|
| 31 |
+
block_mask: Optional[torch.Tensor] = None,
|
| 32 |
+
causal: bool = False,
|
| 33 |
+
chain: Optional[ReceiptChain] = None,
|
| 34 |
+
scale: Optional[float] = None,
|
| 35 |
+
):
|
| 36 |
+
y = _dense_attn(q, k, v, causal=causal, score_mod=score_mod, block_mask=block_mask, scale=scale)
|
| 37 |
+
if chain is not None:
|
| 38 |
+
mid = "none" if score_mod is None else getattr(score_mod, "__name__", type(score_mod).__name__)
|
| 39 |
+
bdigest = "none" if block_mask is None else f"sum={float(block_mask.to(torch.float32).sum().item()):.6g}"
|
| 40 |
+
chain.emit({"op": "maskmod_attn", "score_mod": mid, "block_mask": bdigest,
|
| 41 |
+
"causal": causal, "q_shape": list(q.shape), "lambda": "Conjecture 1"})
|
| 42 |
+
return y
|
| 43 |
+
|
| 44 |
+
def selfcheck() -> dict:
|
| 45 |
+
torch.manual_seed(20260828)
|
| 46 |
+
q = k = v = torch.randn(1, 2, 8, 16)
|
| 47 |
+
chain = ReceiptChain()
|
| 48 |
+
y = maskmod_attn(q, k, v, causal=True, chain=chain)
|
| 49 |
+
ref = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=0.0)
|
| 50 |
+
err = float((y - ref).abs().max().item())
|
| 51 |
+
ok_c, depth, brk = chain.verify()
|
| 52 |
+
ok = bool(err < 1e-5 and ok_c)
|
| 53 |
+
return {"ok": ok, "max_abs_vs_sdpa_causal": err, "chain_ok": ok_c, "chain_depth": depth,
|
| 54 |
+
"lambda": "Conjecture 1", "note": "correctness vs SDPA causal; no speedup claimed"}
|