Files
Athena-Deck/docs/experiments/audio8-cpu-2026-10-27/avx2_compat.py
T

88 lines
5.2 KiB
Python

"""Verify the local U8S8 kernel and create separate equivalent U8U8 graphs."""
from pathlib import Path
import hashlib
import importlib.util
import json
import numpy as np
import onnx
from onnx import helper, numpy_helper, TensorProto
import onnxruntime as ort
ROOT = Path('/data/athena-audio8-cpu-20261027')
SRC = ROOT/'model'
DST = ROOT/'model-u8u8'
DST.mkdir(mode=0o700,exist_ok=True)
original = onnx.load(str(SRC/'slow_ar_int8.onnx'),load_external_data=True)
initializers = {v.name:v for v in original.graph.initializer}
node = next(n for n in original.graph.node if n.op_type=='MatMulInteger')
weight = numpy_helper.to_array(initializers[node.input[1]])
zero = numpy_helper.to_array(initializers[node.input[3]])
rng = np.random.default_rng(42)
activation = rng.integers(0,256,(3,weight.shape[0]),dtype=np.uint8)
activation[0,:] = 255
activation_zero = np.array(128,dtype=np.uint8)
expected = (activation.astype(np.int32)-activation_zero.astype(np.int32)) @ (weight.astype(np.int32)-zero.astype(np.int32))
def run_matrix(w,z):
graph = helper.make_graph([helper.make_node('MatMulInteger',['a','w','az','wz'],['y'])],
'matrix-validation',[helper.make_tensor_value_info('a',TensorProto.UINT8,list(activation.shape))],
[helper.make_tensor_value_info('y',TensorProto.INT32,list(expected.shape))],
[numpy_helper.from_array(w,'w'),numpy_helper.from_array(activation_zero,'az'),numpy_helper.from_array(z,'wz')])
model = helper.make_model(graph,opset_imports=[helper.make_opsetid('',14)],ir_version=9)
options=ort.SessionOptions();options.intra_op_num_threads=4;options.inter_op_num_threads=1
session=ort.InferenceSession(model.SerializeToString(),sess_options=options,providers=['CPUExecutionProvider'])
return session.run(None,{'a':activation})[0]
signed_result = run_matrix(weight,zero)
unsigned_weight=(weight.astype(np.int16)+128).astype(np.uint8)
unsigned_zero=(zero.astype(np.int16)+128).astype(np.uint8)
unsigned_result=run_matrix(unsigned_weight,unsigned_zero)
validation=dict(node=node.name,weight_shape=list(weight.shape),
u8s8_mismatches=int(np.count_nonzero(signed_result!=expected)),
u8s8_max_absolute_error=int(np.max(np.abs(signed_result.astype(np.int64)-expected))),
u8u8_mismatches=int(np.count_nonzero(unsigned_result!=expected)),
u8u8_max_absolute_error=int(np.max(np.abs(unsigned_result.astype(np.int64)-expected))))
assert validation['u8u8_mismatches']==0
(ROOT/'avx2-matrix-validation.json').write_text(json.dumps(validation,indent=2))
print(json.dumps(validation),flush=True)
del original,initializers,weight
converter=ROOT/'workaround-source/onnx_runtime_0_1b_int8/scripts/convert_u8s8_to_u8u8.py'
spec=importlib.util.spec_from_file_location('audited_audio8_converter',converter)
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
converted=[]
for old,new in [('slow_ar_int8.onnx','slow_ar_u8u8.onnx'),('fast_ar_int8.onnx','fast_ar_u8u8.onnx')]:
count=module.convert_graph(SRC/old,DST/new,False)
before=onnx.load(str(SRC/old),load_external_data=True)
after=onnx.load(str(DST/new),load_external_data=True)
a={v.name:v for v in before.graph.initializer};b={v.name:v for v in after.graph.initializer}
checked=0
for n in before.graph.node:
if n.op_type!='MatMulInteger':continue
wn,zn=n.input[1],n.input[3]
ow=numpy_helper.to_array(a[wn]).astype(np.int16);oz=numpy_helper.to_array(a[zn]).astype(np.int16)
nw=numpy_helper.to_array(b[wn]).astype(np.int16);nz=numpy_helper.to_array(b[zn]).astype(np.int16)
assert np.array_equal(ow-oz,nw-nz)
checked+=1
# Nonconverted initializers, including every scale, must remain byte-equivalent.
changed={n.input[i] for n in before.graph.node if n.op_type=='MatMulInteger' for i in [1,3]}
for name,tensor in a.items():
if name not in changed:
assert np.array_equal(numpy_helper.to_array(tensor),numpy_helper.to_array(b[name]))
converted.append(dict(source=old,derived=new,converted_weights=count,verified_matrix_nodes=checked,
all_other_initializers_unchanged=True))
del before,after,a,b
for name in ['codec_decoder_fp16.onnx','codec_decoder_fp16.onnx.data','tokenizer','registration','config.json','reference_codes.npy']:
target=DST/name
if not target.exists():target.symlink_to(SRC/name)
manifest=json.loads((SRC/'runtime_manifest.json').read_text())
manifest['available_precisions']=['u8u8'];manifest['default_precision']='u8u8'
manifest['slow_decode_models']={'u8u8':'slow_ar_u8u8.onnx'}
manifest['fast_models']={'u8u8':'fast_ar_u8u8.onnx'}
(DST/'runtime_manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2))
report=dict(community_commit='3628c9756936e8d33bf2a662300f1f4131c0bc6e',
converter_sha256=hashlib.sha256(converter.read_bytes()).hexdigest(),
transformation='Add 128 to existing signed weights and zero points; scales unchanged; no recalibration.',
original_models_unchanged=True,graphs=converted,
derived_files={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in DST.iterdir() if p.is_file() and not p.is_symlink()})
(ROOT/'compatibility-manifest.json').write_text(json.dumps(report,indent=2))
print(json.dumps(converted),flush=True)