Buckets:
| """Shape-only width ablation: all variants use synthetic weights and common Triton. | |
| Not a perplexity evaluation. No checkpoint is sliced or modified. | |
| """ | |
| import argparse | |
| import gc | |
| import hashlib | |
| import json | |
| import random | |
| import numpy as np | |
| import torch | |
| from four_way import Model, ROOT, parity, run_case | |
| from inference.compact_triton import attention | |
| VARIANTS = { | |
| 'gqa': ('gqa', False), | |
| 'cla': ('cla', False), | |
| 'concat_128_32': ('concat', False), | |
| 'concat_64_16': ('concat', True), | |
| 'concat_48_12': ('concat', True), | |
| 'residual_160_32': ('residual', False), | |
| 'residual_80_16': ('residual', True), | |
| } | |
| class SyntheticModel(Model): | |
| def __init__(self, variant): | |
| self.name, small = VARIANTS[variant] | |
| self.backend = 'triton' | |
| self.alpha_dim = 64 if small else 128 | |
| self.delta_dim = 16 if small else 32 | |
| if variant == 'concat_48_12': | |
| self.alpha_dim, self.delta_dim = 48, 12 | |
| self.dim = dict(gqa=64, cla=256, concat=self.alpha_dim+self.delta_dim, | |
| residual=self.alpha_dim+self.delta_dim)[self.name] | |
| self.ffn_dim = dict(gqa=2048, cla=1024, concat=1536, residual=1516)[self.name] | |
| self.w = {} | |
| torch.manual_seed(5000) | |
| def add(key, shape, norm=False): | |
| value = torch.empty(shape, device='cuda', dtype=torch.bfloat16) | |
| self.w[key] = value.fill_(1) if norm else value.normal_(std=.02) | |
| add('embedding.word_embeddings.weight', (50304, 512)) | |
| add('output_layer.weight', (50304, 512)) | |
| add('decoder.final_layernorm.weight', (512,), True) | |
| for i in range(12): | |
| def layer(suffix, shape, norm=False): | |
| add(f'decoder.layers.{i}.{suffix}', shape, norm) | |
| anchor = i % 4 == 0 | |
| layer('self_attention.linear_qkv.layer_norm_weight' if self.name == 'gqa' | |
| else 'input_layernorm.weight', (512,), True) | |
| if self.name == 'gqa': | |
| layer('self_attention.linear_qkv.weight', (16*self.dim, 512)) | |
| elif self.name == 'cla': | |
| layer('self_attention.linear_q.weight', (8*self.dim, 512)) | |
| if anchor: | |
| layer('self_attention.linear_kv.weight', (8*self.dim, 512)) | |
| elif self.name == 'concat': | |
| suffix = 'linear_q_delta_base' if anchor else 'linear_q_delta' | |
| size = 8*self.dim + 8*self.delta_dim + (8*self.alpha_dim if anchor else 0) | |
| layer(f'self_attention.{suffix}.weight', (size, 512)) | |
| else: | |
| suffix = 'linear_q_kv' if anchor else 'linear_q_delta' | |
| size = 8*self.dim + 8*(self.dim if anchor else self.delta_dim) | |
| layer(f'self_attention.{suffix}.weight', (size, 512)) | |
| if not anchor: | |
| layer('self_attention.delta_up_weight', (4, 2, self.dim, self.delta_dim)) | |
| layer('self_attention.linear_proj.weight', (512, 8*self.dim)) | |
| layer('pre_mlp_layernorm.weight' if self.name == 'cla' | |
| else 'mlp.linear_fc1.layer_norm_weight', (512,), True) | |
| layer('mlp.linear_fc1.weight', (2*self.ffn_dim, 512)) | |
| layer('mlp.linear_fc2.weight', (512, self.ffn_dim)) | |
| self.params = sum(v.numel() for v in self.w.values()) | |
| if not small: | |
| assert self.params == 98710016, (variant, self.params) | |
| assert self.cache_elements_per_token == (2304 if variant=='concat_48_12' else 3072 if small else 6144) | |
| self.init_rope() | |
| def config(self): | |
| return dict(model=self.name, layers=12, hidden_size=512, query_heads=8, | |
| kv_heads=4, head_dim=self.dim, ffn_dim=self.ffn_dim, | |
| alpha_dim=self.alpha_dim if self.name=='concat' else None, | |
| delta_dim=self.delta_dim if self.name in ('concat','residual') else None, | |
| group_size=1 if self.name=='gqa' else 4, params=self.params, | |
| cache_elements_per_token=self.cache_elements_per_token) | |
| def validate(model): | |
| torch.manual_seed(5000) | |
| checks = [] | |
| # The eager oracle independently prepares q/k/v and runs FP32 QK/softmax/PV. | |
| ids = torch.randint(0, 50257, (2, 65), device='cuda') | |
| fast_cache, ref_cache = model.cache(2, 65), model.cache(2, 65) | |
| fast = model.forward(ids[:, :61], fast_cache, all_logits=True).float() | |
| model.backend = 'eager' | |
| ref = model.forward(ids[:, :61], ref_cache, all_logits=True).float() | |
| error = float((fast-ref).norm()/ref.norm()) | |
| assert error < .025, ('full', model.name, error) | |
| checks.append(dict(kind='full_logits', relative_l2=error)) | |
| for pos in range(61,65): | |
| model.backend = 'triton' | |
| fast = model.forward(ids[:,pos:pos+1],fast_cache,pos).float() | |
| model.backend = 'eager' | |
| ref = model.forward(ids[:,pos:pos+1],ref_cache,pos).float() | |
| error = float((fast-ref).norm()/ref.norm()) | |
| assert error < .025, ('decode', model.name, pos, error) | |
| checks.append(dict(kind='incremental_logits',position=pos,relative_l2=error)) | |
| model.backend = 'triton' | |
| # Independent attention checks exercise all residual depths and split boundaries. | |
| for start,s in [(0,33),(511,1),(512,1),(32768,1)]: | |
| b=2 if start<1000 else 1 | |
| end=start+s | |
| cache=model.cache(b,end+7) | |
| for tensor in cache.values(): | |
| tensor.normal_(std=.2) | |
| q=torch.randn(b,s,8,model.dim,device='cuda',dtype=torch.bfloat16)*.2 | |
| for layer in (range(4) if model.name=='residual' else [0,3]): | |
| anchor=layer if model.name=='gqa' else layer//4*4 | |
| base=cache['base',anchor][:,:end] | |
| if model.name=='concat': | |
| delta=cache['delta',layer][:,:end] | |
| k=torch.cat((base[...,0,:],delta[...,0,:]),-1) | |
| v=torch.cat((base[...,1,:],delta[...,1,:]),-1) | |
| elif model.name=='residual': | |
| state=base | |
| for j in range(anchor+1,layer+1): | |
| state=state+torch.einsum('bshvr,hvdr->bshvd',cache['delta',j][:,:end], | |
| model.weight(j,'self_attention.delta_up_weight')) | |
| k,v=model.rope(state[...,0,:]),state[...,1,:] | |
| else: | |
| k,v=base[...,0,:],base[...,1,:] | |
| scores=torch.einsum('bshd,bthd->bhst',q.float(),k.repeat_interleave(2,2).float())*model.dim**-.5 | |
| mask=torch.arange(end,device='cuda')[None,:]>(start+torch.arange(s,device='cuda'))[:,None] | |
| scores.masked_fill_(mask,-float('inf')) | |
| ref=torch.einsum('bhst,bthd->bshd',scores.softmax(-1),v.repeat_interleave(2,2).float()) | |
| fast=attention(q,cache,model.name,layer,start,model.cos,model.sin,model.weight).float() | |
| error=float((fast-ref).norm()/ref.norm()) | |
| absolute=float((fast-ref).abs().max()) | |
| assert error<.015 and absolute<.01,(model.name,start,layer,error,absolute) | |
| checks.append(dict(kind='attention',position=start,length=s,layer=layer, | |
| relative_l2=error,max_abs=absolute)) | |
| return dict(checks=checks, incremental=parity(model)) | |
| def main(): | |
| parser=argparse.ArgumentParser() | |
| parser.add_argument('--checks-only',action='store_true') | |
| parser.add_argument('--output',default='inference/results/width_ablation_triton.json') | |
| parser.add_argument('--variants',nargs='+',default=[v for v in VARIANTS if v!='concat_48_12'],choices=list(VARIANTS)) | |
| args=parser.parse_args() | |
| torch.set_num_threads(4) | |
| torch.backends.cuda.matmul.allow_tf32=False | |
| import triton | |
| report=dict(backend='triton',weights='synthetic, seed 5000, ALL variants; no PPL claims', | |
| gpu=torch.cuda.get_device_name(),torch=torch.__version__,triton=triton.__version__, | |
| steps=32,repeats=5,warmup_replays=10,configs={},correctness={},results=[], | |
| source_sha256={f:hashlib.sha256((ROOT/f).read_bytes()).hexdigest() for f in | |
| ['inference/benchmark_widths.py','inference/four_way.py','inference/compact_triton.py','inference/kernels.py']}) | |
| output=ROOT/args.output | |
| output.parent.mkdir(parents=True,exist_ok=True) | |
| def save(): | |
| output.write_text(json.dumps(report,indent=2)+'\n') | |
| # Finish checks for ALL models before timing any of them. | |
| for variant in args.variants: | |
| model=SyntheticModel(variant) | |
| report['configs'][variant]=model.config() | |
| report['correctness'][variant]=validate(model) | |
| print('PASS',variant,report['configs'][variant],flush=True) | |
| save() | |
| del model | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| if args.checks_only: | |
| return | |
| raw=np.fromfile(ROOT/'ppl-evals/datasets/c4_10m.bin',dtype=np.uint16,count=8*(32768+32)) | |
| ids=torch.tensor(raw.astype(np.int64),device='cuda').reshape(8,-1) | |
| order=args.variants.copy() | |
| random.Random(5000).shuffle(order) | |
| report['model_order']=order | |
| for variant in order: | |
| model=SyntheticModel(variant) | |
| for context in [2048,8192,32768]: | |
| for batch in [1,8]: | |
| row=run_case(model,ids,context,batch,32,5,True,warmup_replays=10) | |
| row['variant']=variant | |
| report['results'].append(row) | |
| save() | |
| print(json.dumps(row),flush=True) | |
| del model | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| save() | |
| if __name__=='__main__': | |
| main() | |
Xet Storage Details
- Size:
- 9.53 kB
- Xet hash:
- 57d18d795e76409478188151425dd3fdceb6d1abecd119a9bc9fdf59b015510a
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.