tcfm-prereg / k2_pack /k2 /parameter_flops.py
BraylonDash's picture
freeze A6 K2 implementation pack
27b13d2
Raw
History Blame Contribute Delete
6.01 kB
"""Emit the frozen CPU parameter/symbolic/profiler FLOP receipt."""
from __future__ import annotations
import argparse
import os
import platform
from dataclasses import asdict
import numpy as np
import torch
from .config import load_full_config
from .constants import A6_PROTOCOL_SHA256, ATTENTION_MODES
from .io import file_record, write_json_exclusive
from .model import K2Student, StudentSpec, allocated_parameter_count, state_dict_tensor_bytes
def symbolic_forward_flops(spec: StudentSpec, batch: int, length: int) -> dict[str, int]:
b, l, d, z = batch, length, spec.d_model, spec.latent_dim
per_block = {
"qkv_and_output_projections": 8 * b * l * d * d,
"attention_qk_and_av_matmuls": 4 * b * l * l * d,
"mlp_linears": 4 * b * l * d * spec.mlp_hidden,
}
components = {
"input_projection": 2 * b * l * z * d,
"time_mlp": 2 * b * (128 * d + d * d),
"transformer_blocks": spec.blocks * sum(per_block.values()),
"head_a_h": 2 * b * l * d * spec.within_token_hidden,
"head_a_z": 2 * b * l * z * spec.within_token_hidden,
"head_a_t_once_per_sequence": 2 * b * d * spec.within_token_hidden,
"head_b": 2 * b * l * spec.within_token_hidden * z,
"head_c_h": 2 * b * l * d * z,
"head_c_z": 2 * b * l * z * z,
}
return {
"total": int(sum(components.values())),
"components": {key: int(value) for key, value in components.items()},
"per_transformer_block_components": {
key: int(value) for key, value in per_block.items()
},
}
def profiler_forward_flops(model: K2Student, mode: str) -> int:
z = torch.zeros((1, 64, 16), dtype=torch.float32)
t = torch.full((1, 1, 1), 0.5, dtype=torch.float32)
with torch.no_grad(), torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU], with_flops=True,
record_shapes=True,
) as profile:
model(z, t, mode)
return int(sum(int(event.flops or 0) for event in profile.key_averages()))
def graph_active_parameter_count(model: K2Student, mode: str) -> int:
model.zero_grad(set_to_none=True)
z = torch.zeros((1, 64, 16), dtype=torch.float32)
t = torch.full((1, 1, 1), 0.5, dtype=torch.float32)
model(z, t, mode).sum().backward()
active = sum(
parameter.numel() for parameter in model.parameters()
if parameter.grad is not None
)
model.zero_grad(set_to_none=True)
return int(active)
def generate_receipt(config_path: str, output: str) -> dict:
config = load_full_config(config_path)
if str(torch.__version__) != "2.7.0+cu126" or np.__version__ != "1.26.4":
raise RuntimeError(
f"receipt requires torch 2.7.0+cu126/numpy 1.26.4; "
f"got {torch.__version__}/{np.__version__}"
)
if torch.cuda.is_available():
raise RuntimeError("public CPU receipt requires CUDA to be unavailable")
torch.manual_seed(0)
torch.use_deterministic_algorithms(True)
model = K2Student(StudentSpec.from_protocol(config.protocol)).cpu().eval()
parameter_count = allocated_parameter_count(model)
profiler = {mode: profiler_forward_flops(model, mode) for mode in ATTENTION_MODES}
active = {mode: graph_active_parameter_count(model, mode) for mode in ATTENTION_MODES}
symbolic_b1 = symbolic_forward_flops(model.spec, 1, 64)
symbolic_b256 = symbolic_forward_flops(model.spec, 256, 64)
config_record = file_record(config.path)
config_record.pop("path")
config_record["relative_path"] = "config/k2_full_config.json"
receipt = {
"schema_version": 1,
"receipt": "TCFM-A6-K2-parameter-and-flop-v1",
"status": "PASS" if (
profiler["full"] == profiler["prefix"]
and active == {"full": parameter_count, "prefix": parameter_count}
) else "FAIL",
"scope": "CPU architecture receipt; no training/evaluation metric",
"hardware": "CPU",
"h200_claim": False,
"environment": {
"python": platform.python_version(),
"torch": str(torch.__version__),
"numpy": np.__version__,
"cuda_used": False,
"cuda_available": torch.cuda.is_available(),
"cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"),
"deterministic_algorithms": torch.are_deterministic_algorithms_enabled(),
},
"a6_protocol_sha256": A6_PROTOCOL_SHA256,
"full_config": config_record,
"architecture_closure": config.raw["architecture_closure"],
"student_spec": asdict(model.spec),
"allocated_parameter_count": parameter_count,
"active_parameter_count_by_mode": active,
"active_parameter_method": "parameter has non-None gradient after a complete B=1,L=64 forward/backward",
"state_dict_tensor_bytes": state_dict_tensor_bytes(model),
"only_mode_difference": "equal-shaped boolean attention mask entries",
"symbolic_flop_convention": (
"one multiply plus one add equals two FLOPs; counts dense Linear and "
"attention matmuls only; bias, normalization, elementwise, softmax, "
"trigonometric and loss operations excluded"
),
"symbolic_forward_flops_batch1_length64": symbolic_b1,
"symbolic_forward_flops_batch256_length64": symbolic_b256,
"cpu_torch_profiler_forward_flops_batch1_length64": profiler,
"profiler_parity_required": True,
}
if receipt["status"] != "PASS":
raise AssertionError(f"full/prefix CPU profiler FLOPs differ: {profiler}")
write_json_exclusive(output, receipt)
return receipt
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
receipt = generate_receipt(args.config, args.output)
print(receipt["status"])
if __name__ == "__main__":
main()