"""Source-only FFN weight frames with independently verified reconstruction. The frozen physical prior is shared. Each observed frame owns a small residual adapter; only positions, lengths and digests accompany those weights. Readers never supply observed tokens, VAE codes or saved KV states to reconstruction. """ from dataclasses import dataclass,replace import hashlib,json,math import torch from torch.nn.utils.rnn import pad_sequence @dataclass(frozen=True) class PhysicalSource: count: int checksum: str def __post_init__(self): if type(self.count) is not int or self.count<1:raise ValueError('positive physical source length required') if not isinstance(self.checksum,str) or len(self.checksum)!=64:raise ValueError('physical source requires a SHA256') try:raw=bytes.fromhex(self.checksum) except ValueError:raise ValueError('physical source requires a SHA256') from None if len(raw)!=32:raise ValueError('physical source requires a SHA256') object.__setattr__(self,'checksum',raw.hex()) @dataclass(frozen=True) class PhysicalFrame: offset: int count: int checksum: str record: int state: object def detach(self,device=None): from .episodic_adapters import AdapterMemory groups=[{k:v.detach().to(device) if device is not None else v.detach() for k,v in g.items()} for g in (self.state.factors,self.state.first_moment,self.state.second_moment)] return replace(self,state=AdapterMemory(*groups,self.state.commits).detach()) @dataclass(frozen=True) class FrameSpan: record: int offset: int count: int @dataclass(frozen=True) class PhysicalRecall: pieces: tuple # (record, offset, verified token tensor) frames: tuple # all frame descriptors, including failed reads @property def verified_positions(self):return sum(len(ids) for _,_,ids in self.pieces) @property def positions(self):return sum(f.count for f in self.frames) def describe_source(ids): if ids.ndim!=1 or not len(ids):raise ValueError('one complete observed source required') raw=ids.detach().cpu().to(torch.int64).contiguous().numpy().tobytes() return PhysicalSource(len(ids),hashlib.sha256(raw).hexdigest()) def frame_metadata(frames): return [dict(offset=f.offset,count=f.count,checksum=f.checksum,record=f.record,commits=f.state.commits, rank=next(v.shape[0] for k,v in f.state.factors.items() if k.endswith('.A'))) for f in frames] def describe_frames(frames): if not frames:return None return PhysicalSource(sum(f.count for f in frames),hashlib.sha256( json.dumps(frame_metadata(frames),sort_keys=True,separators=(',',':')).encode()).hexdigest()) def source_tensors(source): if source is None:return {} return {'physical_source.count':torch.tensor([source.count],dtype=torch.int64), 'physical_source.checksum':torch.tensor(list(bytes.fromhex(source.checksum)),dtype=torch.uint8)} def load_source(tensors): if 'physical_source.count' not in tensors:return None count=tensors['physical_source.count'];checksum=tensors['physical_source.checksum'] if count.dtype!=torch.int64 or count.shape!=(1,) or checksum.dtype!=torch.uint8 or checksum.shape!=(32,): raise ValueError('invalid physical source descriptor tensors') return PhysicalSource(int(count[0]),bytes(checksum.tolist()).hex()) def frame_tensors(frames): return {f'frame.{i}.{kind}.{name}':value.detach().cpu().contiguous() for i,f in enumerate(frames) for kind,group in [('factor',f.state.factors),('first',f.state.first_moment),('second',f.state.second_moment)] for name,value in group.items()} def frame_shapes(model,metadata): if not isinstance(metadata,list):raise ValueError('physical frame metadata must be a list') shapes={};offset=0;last_record=-1 rank=model.config.physical_frame_rank;limit=model.config.physical_frame_tokens for i,f in enumerate(metadata): if (type(f.get('offset')) is not int or f['offset']!=offset or type(f.get('count')) is not int or not 0model.config.text_config.max_position_embeddings: raise MemoryContextLimitError('verified physical fragments plus query/output exceed native context') result=dict(inputs,inputs_embeds=value[None],attention_mask=torch.ones((1,len(value)),device=value.device,dtype=torch.long)) for key in ('pixel_values','spatial_shapes','pixel_attention_mask'):result.pop(key,None) return result