mlx-agent-tools / mlx_agent_tools /separate_mtp.py
ChengyiX's picture
Initial release of mlx-agent-tools (v1.0.0)
4606829 verified
Raw History Blame Contribute Delete
4.76 kB
"""Separate normalized embedded MTP by byte-preserving safetensors repack.
Avoids mlx-lm's presence-keyed RMSNorm shift on a converted trunk. No inference,
quantization, normalization, provider selection or source mutation is performed.
"""
from pathlib import Path
import argparse,hashlib,json,os,shutil,struct
def header(path):
with path.open('rb') as f:
length=struct.unpack('<Q',f.read(8))[0]
if length>16*1024**2:raise ValueError('Header size limit')
data=json.loads(f.read(length))
return data,8+length
def repack(output,entries,heads):
metadata={'__metadata__':{'format':'mlx'}};cursor=0
for newname,src,old,base,key in entries:
start,end=old['data_offsets'];metadata[newname]={**old,'data_offsets':[cursor,cursor+end-start]};cursor+=end-start
raw=json.dumps(metadata,separators=(',',':')).encode();raw+=b' '*(-len(raw)%8);digests={}
with output.open('xb') as out:
out.write(struct.pack('<Q',len(raw)));out.write(raw)
for newname,src,old,base,key in entries:
start,end=old['data_offsets'];count=end-start;digest=hashlib.sha256()
with src.open('rb') as source:
source.seek(base+start)
while count:
chunk=source.read(min(count,8*1024**2))
if not chunk:raise ValueError('Truncated tensor')
out.write(chunk);digest.update(chunk);count-=len(chunk)
digests[newname]={'source_tensor':key,'payload_sha256':digest.hexdigest(),'payload_bytes':end-start}
return digests,cursor
def prepare(source,output):
source,output=Path(source).resolve(),Path(output).resolve()
if output.exists() or source==output or source in output.parents:raise ValueError('Output exists or inside source')
index=json.loads((source/'model.safetensors.index.json').read_text())['weight_map'];heads=[k for k in index if k.startswith('language_model.mtp.') or k.startswith('mtp.')]
if not heads:raise ValueError('No embedded MTP tensors')
schemas={}
for filename in sorted(set(index.values())):
if Path(filename).name!=filename:raise ValueError('Unsafe source shard')
h,base=header(source/filename);keys={k for k in h if k!='__metadata__'}
if keys!={k for k,v in index.items() if v==filename}:raise ValueError('Index/header mismatch')
if h.get('__metadata__',{}).get('format')!='mlx':raise ValueError('Source not marked normalized MLX format')
schemas[filename]=(h,base)
output.mkdir();mapping={};allhead=[];payloads={};total=0
for filename,(h,base) in schemas.items():
selected=[k for k,v in index.items() if v==filename];trunk=[k for k in selected if k not in heads]
for key in selected:
if key in heads:
newname=key.removeprefix('language_model.')
allhead.append((newname,source/filename,h[key],base,key))
if not trunk:continue
if len(trunk)==len(selected):
os.link(source/filename,output/filename)
total+=sum(h[k]['data_offsets'][1]-h[k]['data_offsets'][0] for k in trunk)
else:
entries=[(k,source/filename,h[k],base,k) for k in trunk]
d,size=repack(output/filename,entries,heads);payloads.update(d);total+=size
mapping.update({k:filename for k in trunk})
d,size=repack(output/'mtp.safetensors',allhead,heads);payloads.update(d)
for p in source.iterdir():
if p.is_file() and p.suffix in ['.json','.jinja','.txt','.md'] and p.name not in ['model.safetensors.index.json']:
shutil.copy2(p,output/p.name)
(output/'model.safetensors.index.json').write_text(json.dumps({'metadata':{'total_size':total},'weight_map':mapping},indent=2)+'\n')
# Verify every rewritten payload independently against the copied digest.
for filename in [*{index[k] for k in heads if index[k] in mapping.values()},'mtp.safetensors']:
p=output/filename
if not p.exists():continue
h,base=header(p)
with p.open('rb') as f:
for name,record in h.items():
if name=='__metadata__':continue
start,end=record['data_offsets'];f.seek(base+start);remaining=end-start;digest=hashlib.sha256()
while remaining:
block=f.read(min(remaining,8*1024**2));digest.update(block);remaining-=len(block)
if digest.hexdigest()!=payloads[name]['payload_sha256']:raise ValueError('Repacked tensor hash mismatch')
receipt={'method':'exact tensor-payload repack only; no numerical change',
'source':str(source),'base_tensors':len(mapping),'mtp_tensors':len(heads),'payload_hashes':payloads,
'norm_shift_applied':False,'quantization_changed':False,'source_unchanged':True}
(output/'mtp-separation-manifest.json').write_text(json.dumps(receipt,indent=2)+'\n');return receipt
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();r=prepare(a.source,a.output);print({k:r[k] for k in ['base_tensors','mtp_tensors','norm_shift_applied','quantization_changed']})