"""Lossless separate-expert layout adapter for pinned official Qwen3.5 MoE. Usage: with native_layout_adapter() as audit: mlx_lm.convert.convert(...) The context changes only source layout handling and restores the original method. All quantization, model math, serialization and reload remain official MLX code. """ import contextlib,importlib.metadata,json,pathlib,re,struct,threading _PATTERN=re.compile(r'^(model\.language_model|language_model\.model)\.layers\.(\d+)\.mlp\.experts\.(\d+)\.(gate_proj|up_proj|down_proj)\.weight$') _LOCK=threading.Lock() def _plan(weights,layers,experts,hidden,intermediate): found={};recognized=set() for key,value in weights.items(): match=_PATTERN.fullmatch(key) if match: base,layer,expert,proj=match.groups();layer=int(layer);expert=int(expert) assert key==f'{base}.layers.{layer}.mlp.experts.{expert}.{proj}.weight','Noncanonical expert index' assert 0<=layer