Download runtime/training/streaming/sparse.py from hscr/luxfer: direct link, hf CLI and curl.
- Browser
- Download file 4.33 kB
-
https://huggingface.co/hscr/luxfer/resolve/main/runtime/training/streaming/sparse.py
- Command line
-
hf download hf://hscr/luxfer/runtime/training/streaming/sparse.py
-
curl -L -o sparse.py https://huggingface.co/hscr/luxfer/resolve/main/runtime/training/streaming/sparse.py
4.33 kB
| """Small FP32 optimization tiles over an immutable zero-output expansion checkpoint.""" | |
| from collections import OrderedDict | |
| from pathlib import Path | |
| import torch | |
| from torch import nn | |
| from torch.nn import functional as F | |
| from safetensors.torch import load_file | |
| class Tile(nn.Module): | |
| def __init__(self,up,down): | |
| super().__init__();self.up=nn.Parameter(up.detach().float().clone());self.down=nn.Parameter(down.detach().float().clone()) | |
| def forward(self,x): | |
| a,b=F.linear(x.float(),self.up).chunk(2,-1);return F.linear(F.silu(a)*b,self.down) | |
| class SparseExpansion(nn.Module): | |
| force_evaluate=True | |
| def __init__(self,base,layer,store,max_cached=4): | |
| super().__init__();self.gate_up_proj=base.gate_up_proj;self.down_proj=base.down_proj;self.layer=layer;self.store=store;self.active=None;self.active_key=None;self.enabled=True;self.cache=OrderedDict();self.max_cached=max_cached | |
| if torch.count_nonzero(self.down_proj.weight).item():raise ValueError('Sparse trainer requires a zero-output expansion base; previous learning belongs in overlays') | |
| def forward(self,x): | |
| output=torch.zeros_like(x,dtype=torch.float32) | |
| if not self.enabled:return output.to(x.dtype) | |
| for key,record in sorted(self.store.catalog.items()): | |
| if record['layer']!=self.layer or key==self.active_key:continue | |
| revision=record['weights_sha256'] | |
| if revision not in self.cache: | |
| values=self.store.weights(record);self.cache[revision]=values | |
| while len(self.cache)>self.max_cached:self.cache.popitem(last=False) | |
| values=self.cache[revision];self.cache.move_to_end(revision) | |
| a,b=F.linear(x.float(),values['up']).chunk(2,-1);output=output+F.linear(F.silu(a)*b,values['down']) | |
| if self.active is not None:output=output+self.active(x) | |
| return output.to(x.dtype) | |
| def activate(self,key,start,width): | |
| if self.active is not None:raise ValueError('Deactivate previous coordinate first') | |
| if key in self.store.catalog: | |
| values=self.store.weights(self.store.catalog[key]);self.active=Tile(values['up'],values['down']) | |
| else: | |
| full=self.gate_up_proj.weight.shape[0]//2 | |
| self.active=Tile(torch.cat([self.gate_up_proj.weight[start:start+width],self.gate_up_proj.weight[full+start:full+start+width]],0),self.down_proj.weight[:,start:start+width]) | |
| self.active_key=key;return self.active | |
| def deactivate(self):self.active=None;self.active_key=None | |
| class OverlayRouting: | |
| def __init__(self,bank,expansions,allowed_routes=None):self.bank=bank;self.expansions=expansions;self.layers=bank.layers;self.allowed_routes=set(allowed_routes) if allowed_routes is not None else None | |
| def select(self,source,target): | |
| admitted=self.allowed_routes is None or source+'->'+target in self.allowed_routes | |
| route=self.bank.select(source,target) if admitted else self.bank.select('','') | |
| for expansion in self.expansions.values():expansion.enabled=route is not None | |
| return route | |
| def set_source_length(self,length):self.bank.set_source_length(length) | |
| def attach_sparse(model,bank,store): | |
| expansions={} | |
| for i in bank.layers: | |
| layer=model.model.layers.layers[i];base=getattr(layer,'base',layer) | |
| if base.mlp.expansion is None:raise ValueError('Checkpoint has no added feed-forward capacity') | |
| sparse=SparseExpansion(base.mlp.expansion,i,store);base.mlp.expansion=sparse;expansions[i]=sparse | |
| return expansions,OverlayRouting(bank,expansions) | |
| def coordinates(layers,width,tile_width,max_tiles): | |
| if tile_width<1 or tile_width>width or width%tile_width:raise ValueError('Tile width must divide the expansion width') | |
| per_layer=width//tile_width;available=per_layer*len(layers);count=min(available,max_tiles) | |
| if count<len(layers):raise ValueError('Tile budget must cover each selected layer') | |
| result=[] | |
| for n in range(count): | |
| layer=layers[n%len(layers)];slot=(n//len(layers))*per_layer//((count+len(layers)-1)//len(layers));start=slot*tile_width | |
| result.append(dict(key=f'layer-{layer:03d}-start-{start:05d}',layer=layer,start=start,width=tile_width)) | |
| if len({r['key'] for r in result})!=len(result):raise ValueError('Duplicate coordinates') | |
| return result | |