"""Step 6: fp32 export (litert-torch) + fp16-weight storage (ai-edge-quantizer FLOAT_CASTING) at one window. Usage: export.py --seq 128 [--matmul plain|rank4] [--suffix name] [--ln-shift none|audit] (round 2: --ln-shift audit = SafeLayerNorm at the audit's k map, graph.ln_shift_audit(); use a distinct --suffix) 1. Guard: results/rewrite_check_s{N}.json must say PASS for the same --matmul; the graph object being exported is re-checked on 3 probes against the oracle (argmax, multi_set, max |dlogit| <= 1e-3). 2. litert_torch.convert(graph, sample_kwargs={3 inputs}).export -> exports/_s{N}[_suffix]_fp32.tflite; flatbuffer scan (vendored from the Open Decision run's export.py; reads the schema only, never runs the model) -> results/opscan_*_fp32.json: op histogram, operator count, tensor rank / dtype histograms, the ML Drift rejection list (GATHER GATHER_ND CAST SELECT_V2 BROADCAST_TO MAXIMUM, int64 tensors, rank > 4, constant-LEFT BATCH_MATMUL), SPLIT / TILE / PACK / ONE_HOT counts, every BATCH_MATMUL's input shapes (rank-4 check), constant-input dtypes per op type, signatures. 3. ai-edge-quantizer 0.8.0 weight-only fp16 (ALL_SUPPORTED, 16-bit, TENSORWISE, FLOAT_CASTING; the Open Decision recipe) -> exports/_s{N}[_suffix]_wfp16.tflite + scan (FULLY_CONNECTED with fp16 weights, DEQUANTIZE count, BATCH_MATMUL constants must stay FLOAT32). Existing artifacts are never overwritten. Writes results/export_s{N}[_suffix].json (status, sha256, bytes, seconds). """ import argparse import collections import importlib.metadata import json import time import traceback import numpy as np import torch from common import PREFIX, ROOT, THRESHOLD, dump_json, load_official, sha256 from graph import GliclassGraph, as_kwargs, contract, fixed_inputs, ln_shift_audit FORBIDDEN_OPS = {"GATHER", "GATHER_ND", "CAST", "SELECT_V2", "BROADCAST_TO", "MAXIMUM"} REPORT_OPS = ("SPLIT", "SPLIT_V", "TILE", "PACK", "ONE_HOT", "STRIDED_SLICE", "SLICE", "CONCATENATION", "TRANSPOSE", "RESHAPE", "BATCH_MATMUL", "FULLY_CONNECTED", "DEQUANTIZE", "GELU", "SOFTMAX") def scan(path): from ai_edge_litert import schema_py_generated as schema model = schema.ModelT.InitFromPackedBuf(path.read_bytes(), 0) op_names = {v: k for k, v in vars(schema.BuiltinOperator).items() if isinstance(v, int)} type_names = {v: k for k, v in vars(schema.TensorType).items() if isinstance(v, int)} codes = [] for code in model.operatorCodes: name = op_names.get(max(code.builtinCode, code.deprecatedBuiltinCode), "UNKNOWN") if name == "CUSTOM": name = "CUSTOM:" + (code.customCode.decode() if code.customCode else "") codes.append(name) histogram, ranks, dtypes = collections.Counter(), collections.Counter(), collections.Counter() found = collections.defaultdict(int) bmm_const = collections.Counter() const_dtypes_by_op = collections.defaultdict(collections.Counter) bmms, fc_weight_dtypes = [], collections.Counter() signatures = [] for gi, graph in enumerate(model.subgraphs): produced = {int(o) for op in graph.operators for o in op.outputs} graph_inputs = {int(i) for i in graph.inputs} is_const = lambda t: t >= 0 and t not in produced and t not in graph_inputs producer = {int(o): codes[op.opcodeIndex] for op in graph.operators for o in op.outputs} for ti, tensor in enumerate(graph.tensors): shape = tensor.shape.tolist() if tensor.shape is not None else [] ranks[len(shape)] += 1 dtypes[type_names.get(tensor.type, str(tensor.type))] += 1 if tensor.type == schema.TensorType.INT64: found["int64_tensor"] += 1 if len(shape) > 4: found["rank_gt4_tensor"] += 1 for oi, op in enumerate(graph.operators): name = codes[op.opcodeIndex] histogram[name] += 1 if name in FORBIDDEN_OPS: found[f"op_{name}"] += 1 ins = [int(i) for i in op.inputs] for ti in ins: if is_const(ti): const_dtypes_by_op[name][type_names.get(graph.tensors[ti].type, "?")] += 1 if name == "BATCH_MATMUL": if is_const(ins[0]): found["batch_matmul_constant_left"] += 1 for ti in ins: if is_const(ti): bmm_const[type_names.get(graph.tensors[ti].type, "?")] += 1 bmms.append(dict(op_index=oi, input_shapes=[graph.tensors[t].shape.tolist() for t in ins], constant_inputs=[is_const(t) for t in ins])) if name == "FULLY_CONNECTED" and len(ins) > 1 and ins[1] >= 0: w = ins[1] fc_weight_dtypes["via DEQUANTIZE (fp16 constant -> " + type_names.get(graph.tensors[w].type, "?") + ")" if producer.get(w) == "DEQUANTIZE" else type_names.get(graph.tensors[w].type, "?")] += 1 for sig in model.signatureDefs: graph = model.subgraphs[sig.subgraphIndex] entry = {"key": sig.signatureKey.decode()} for side in ("inputs", "outputs"): entry[side] = [{"name": tm.name.decode(), "shape": graph.tensors[tm.tensorIndex].shape.tolist(), "type": type_names.get(graph.tensors[tm.tensorIndex].type, "?")} for tm in getattr(sig, side)] signatures.append(entry) return dict(file=str(path.relative_to(ROOT)), bytes=path.stat().st_size, sha256=sha256(path), subgraphs=len(model.subgraphs), operator_count=sum(histogram.values()), op_histogram=dict(sorted(histogram.items())), reported_op_counts={k: histogram.get(k, 0) for k in REPORT_OPS}, tensor_rank_histogram=dict(sorted(ranks.items())), max_tensor_rank=max(ranks), tensor_dtype_histogram=dict(sorted(dtypes.items())), batch_matmul_constant_dtypes=dict(bmm_const), batch_matmuls=bmms, all_batch_matmul_inputs_rank4=all(all(len(s) == 4 for s in b["input_shapes"]) for b in bmms), fully_connected_weight_dtypes=dict(fc_weight_dtypes), constant_input_dtypes_by_op={k: dict(v) for k, v in sorted(const_dtypes_by_op.items())}, forbidden_found=dict(found), forbidden_count=sum(found.values()), forbidden_checked=sorted(FORBIDDEN_OPS) + ["int64 tensors", "tensor rank > 4", "BATCH_MATMUL constant LEFT operand"], signatures=signatures) def main(): ap = argparse.ArgumentParser() ap.add_argument("--seq", type=int, required=True) ap.add_argument("--matmul", default="plain", choices=["plain", "rank4"]) ap.add_argument("--suffix", default="", help="artifact name suffix, e.g. r4mm") ap.add_argument("--ln-shift", default="none", choices=["none", "audit"], help="SafeLayerNorm k map (round 2)") args = ap.parse_args() seq = args.seq tag = f"s{seq}" + (f"_{args.suffix}" if args.suffix else "") fp32 = ROOT / "exports" / f"{PREFIX}_{tag}_fp32.tflite" wfp16 = ROOT / "exports" / f"{PREFIX}_{tag}_wfp16.tflite" assert not fp32.exists() and not wfp16.exists(), "Never overwrite an exported artifact" rc = json.loads((ROOT / f"results/rewrite_check_{tag}.json").read_text()) assert rc["status"] == "PASS" and rc["matmul"] == args.matmul, "run rewrite_check.py for this graph first" model, _, _, _ = load_official() table = model.model.encoder_model.embeddings.tok_embeddings.weight.detach().numpy() oracle = json.loads((ROOT / "fixtures/oracle.json").read_text())["records"] rows = [r for r in oracle if r["fits"][f"s{seq}"]] probes = [max(rows, key=lambda r: r["n_tokens"]), max(rows, key=lambda r: (r["n_labels"], r["n_tokens"])), next(r for r in rows if r["id"] == "card_01")] ln_shift = ln_shift_audit() if args.ln_shift == "audit" else None if ln_shift: assert "sln" in args.suffix, "SafeLayerNorm artifacts need their own name" graph = GliclassGraph(model, seq, matmul=args.matmul, ln_shift=ln_shift).eval().requires_grad_(False) checks = [] with torch.no_grad(): for r in probes: arrays, n = fixed_inputs(r, seq, table) z = graph(**as_kwargs(arrays))["logits"].reshape(-1)[:n] ref = np.asarray(r["logits"]) p = torch.sigmoid(z) checks.append(dict(id=r["id"], max_abs_vs_oracle=float(np.abs(z.double().numpy() - ref).max()), argmax_equal=int(torch.softmax(z, -1).argmax()) == r["argmax"], multi_set_equal=[j for j in range(n) if float(p[j]) >= THRESHOLD] == r["multi_set"])) assert all(c["argmax_equal"] and c["multi_set_equal"] and c["max_abs_vs_oracle"] <= 1e-3 for c in checks), checks record = dict(seq=seq, matmul=args.matmul, suffix=args.suffix, ln_shift=ln_shift or "none", contract=contract(seq), status="RUNNING", probe_checks=checks, rewrite_check=f"results/rewrite_check_{tag}.json", versions=dict(torch=torch.__version__, transformers=importlib.metadata.version("transformers"), litert_torch=importlib.metadata.version("litert-torch"), ai_edge_litert=importlib.metadata.version("ai-edge-litert"), ai_edge_quantizer=importlib.metadata.version("ai-edge-quantizer"))) started = time.perf_counter() try: import litert_torch if args.matmul == "rank4": from rank4 import register_rank4_matmul register_rank4_matmul() sample, _ = fixed_inputs(probes[0], seq, table) litert_torch.convert(graph, sample_kwargs=as_kwargs(sample)).export(str(fp32)) record["convert_seconds"] = round(time.perf_counter() - started, 1) fp32_scan = scan(fp32) dump_json(f"results/opscan_{tag}_fp32.json", fp32_scan) t1 = time.perf_counter() from ai_edge_quantizer import algorithm_manager, qtyping, quantizer, recipe_manager manager = recipe_manager.RecipeManager() manager.add_weight_only_config(regex=".*", operation_name=qtyping.TFLOperationName.ALL_SUPPORTED, num_bits=16, granularity=qtyping.QuantGranularity.TENSORWISE, algorithm_key=algorithm_manager.AlgorithmName.FLOAT_CASTING) qt = quantizer.Quantizer(str(fp32)) qt.load_quantization_recipe(manager.get_quantization_recipe()) qt.quantize().export_model(str(wfp16)) record["quantize_seconds"] = round(time.perf_counter() - t1, 1) wfp16_scan = scan(wfp16) dump_json(f"results/opscan_{tag}_wfp16.json", wfp16_scan) brief = lambda s: {k: s[k] for k in ("file", "bytes", "sha256", "subgraphs", "operator_count", "op_histogram", "reported_op_counts", "max_tensor_rank", "tensor_dtype_histogram", "all_batch_matmul_inputs_rank4", "batch_matmul_constant_dtypes", "fully_connected_weight_dtypes", "forbidden_found", "forbidden_count", "signatures")} sig_ok = lambda s: (len(s["signatures"]) == 1 and sorted(i["name"] for i in s["signatures"][0]["inputs"]) == sorted(x["name"] for x in contract(seq)["inputs"]) and [(o["name"], o["shape"]) for o in s["signatures"][0]["outputs"]] == [("logits", [1, 1, 1, 25])]) ok = (fp32_scan["forbidden_count"] == 0 and wfp16_scan["forbidden_count"] == 0 and set(wfp16_scan["batch_matmul_constant_dtypes"]) <= {"FLOAT32"} and sig_ok(fp32_scan) and sig_ok(wfp16_scan)) record.update(status="PASS" if ok else "CHECK", signature_ok=[sig_ok(fp32_scan), sig_ok(wfp16_scan)], batch_matmul_rank4=[fp32_scan["all_batch_matmul_inputs_rank4"], wfp16_scan["all_batch_matmul_inputs_rank4"]], fp32=brief(fp32_scan), wfp16=brief(wfp16_scan)) dump_json(f"results/export_{tag}.json", record) print(json.dumps({k: v for k, v in record.items() if k not in ("contract",)}, indent=1), flush=True) except BaseException: (ROOT / f"logs/export_{tag}.traceback.txt").write_text(traceback.format_exc()) record.update(status="FAIL", seconds=time.perf_counter() - started) dump_json(f"results/export_attempt_{tag}.json", record) raise if __name__ == "__main__": main()