Download projects/sparse-world-dynamics/native_visual_pilot.py from KineJIng/kinejing-open-source: direct link, hf CLI and curl.
- Browser
- Download file 8.57 kB
-
https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/sparse-world-dynamics/native_visual_pilot.py
- Command line
-
hf download hf://datasets/KineJIng/kinejing-open-source/projects/sparse-world-dynamics/native_visual_pilot.py
-
curl -L -o native_visual_pilot.py https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/sparse-world-dynamics/native_visual_pilot.py
8.57 kB
| """Train native RGB/action latent dynamics. No LLM, text tokens or base weights. | |
| Small controlled experiment only: all dynamics parameters learn observation / | |
| action -> future-latent prediction, and all experts are actual dense FFNs. | |
| """ | |
| import argparse | |
| from dataclasses import asdict | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| import torch | |
| from torch.nn import functional as F | |
| from model import Config, WorldModel, parameter_audit | |
| from visual_data import generate, data_hash, VisualCodec, image_scores, DOMAINS | |
| from stream_train import atomic_torch_save | |
| def encode(codec, data, device): | |
| frames = data['images'].reshape(-1, 3, 32, 32) | |
| results = [] | |
| with torch.no_grad(): | |
| for index in range(0, len(frames), 256): | |
| results.append(codec.encode(torch.from_numpy(frames[index:index+256]).to(device).float()/255).cpu()) | |
| return torch.cat(results).reshape(*data['images'].shape[:2], -1) | |
| def evaluate(model, z, data, codec, mean, std, device, history=4): | |
| # Every development episode and every eligible start; aggregate per episode. | |
| records = [] | |
| for episode in range(len(z)): | |
| ids = np.arange(history-1, data['actions'].shape[1]) | |
| latent = torch.stack([z[episode,t-history+1:t+1] for t in ids]).to(device) | |
| action = torch.from_numpy(np.stack([data['actions'][episode,t-history+1:t+1] for t in ids])).to(device) | |
| target = z[episode,ids+1].to(device) | |
| previous = latent[:,-1] | |
| if isinstance(model,str): | |
| prediction = previous if model=='persistence' else previous+(previous-latent[:,-2]) | |
| shuffled = prediction | |
| else: | |
| delta,_,_,_ = model(torch.cat((latent,action),-1)) | |
| prediction = previous+delta[:,-1] | |
| delta,_,_,_ = model(torch.cat((latent,action.flip(0)),-1)) | |
| shuffled = previous+delta[:,-1] | |
| raw = prediction*std.to(device).reshape(1,-1)+mean.to(device).reshape(1,-1) | |
| pixel_prediction = codec.decode(raw) | |
| pixels = torch.from_numpy(data['images'][episode,ids+1]).to(device).float()/255 | |
| full, foreground = image_scores(pixel_prediction,pixels) | |
| # Native pixel persistence also avoids codec reconstruction error. | |
| pixel_previous = torch.from_numpy(data['images'][episode,ids]).to(device).float()/255 | |
| pfull,pfg = image_scores(pixel_previous,pixels) | |
| records.append(dict(episode=episode, domain=DOMAINS[int(data['domains'][episode])], | |
| latent_mse=float(F.mse_loss(prediction,target)), | |
| shuffled_action_latent_mse=float(F.mse_loss(shuffled,target)), | |
| pixel_mse=float(full.mean()),foreground_mse=float(foreground.mean()), | |
| raw_pixel_persistence_mse=float(pfull.mean()), | |
| raw_pixel_persistence_foreground_mse=float(pfg.mean()))) | |
| keys=['latent_mse','shuffled_action_latent_mse','pixel_mse','foreground_mse', | |
| 'raw_pixel_persistence_mse','raw_pixel_persistence_foreground_mse'] | |
| return dict(means={key:float(np.mean([row[key] for row in records])) for key in keys},episodes=records) | |
| def main(): | |
| p=argparse.ArgumentParser() | |
| p.add_argument('--codec',type=Path,required=True) | |
| p.add_argument('--out',type=Path,required=True) | |
| p.add_argument('--steps',type=int,default=1200) | |
| p.add_argument('--seeds',type=int,nargs='+',default=[11,22,33]) | |
| a=p.parse_args() | |
| a.out.mkdir(parents=True,exist_ok=False) | |
| torch.set_num_threads(4) | |
| device='cuda' if torch.cuda.is_available() else 'cpu' | |
| saved=torch.load(a.codec,map_location='cpu',weights_only=False) | |
| if not saved.get('usable'): | |
| raise ValueError('Codec reconstruction gate failed') | |
| codec=VisualCodec().to(device).eval() | |
| codec.load_state_dict(saved['model']);codec.requires_grad_(False) | |
| train,valid=generate(1401,256,20),generate(2401,64,20) | |
| if data_hash(train)!=saved['train_hash'] or data_hash(valid)!=saved['val_hash']: | |
| raise ValueError('Data provenance mismatch') | |
| z=encode(codec,train,device);vz=encode(codec,valid,device) | |
| mean,std=z.mean((0,1),keepdim=True),z.std((0,1),keepdim=True).clamp_min(.01) | |
| z,vz=(z-mean)/std,(vz-mean)/std | |
| # Windows remain entirely within an episode. No simulator states enter inputs. | |
| history=4 | |
| train_x=[];train_y=[] | |
| for t in range(history-1,20): | |
| actions=torch.from_numpy(train['actions'][:,t-history+1:t+1]) | |
| train_x.append(torch.cat((z[:,t-history+1:t+1],actions),-1)) | |
| train_y.append(z[:,t-history+2:t+2]-z[:,t-history+1:t+1]) | |
| x,y=torch.cat(train_x).to(device),torch.cat(train_y).to(device) | |
| source=Path(__file__).parent | |
| manifest=dict(status='NATIVE_VISUAL_DYNAMICS_TOY_PROTOCOL',domains=DOMAINS, | |
| training_hash=data_hash(train),validation_hash=data_hash(valid), | |
| training_episodes=256,validation_episodes=64,history=history, | |
| steps=a.steps,seeds=a.seeds,uses_llm=False, | |
| selection_note='Development split, not an untouched final benchmark.', | |
| codec_sha256=hashlib.sha256(a.codec.read_bytes()).hexdigest(), | |
| sources={n:hashlib.sha256((source/n).read_bytes()).hexdigest() for n in | |
| ['model.py','visual_data.py','native_visual_pilot.py']}) | |
| (a.out/'protocol.json').write_text(json.dumps(manifest,indent=2),encoding='utf-8') | |
| records=[] | |
| for kind in ['persistence','constant_velocity']: | |
| record=dict(kind=kind,seed=None,evaluation=evaluate(kind,vz,valid,codec,mean,std,device)) | |
| records.append(record) | |
| for seed in a.seeds: | |
| for dense in (False,True): | |
| torch.manual_seed(seed) | |
| # Dense FFN has the same active FFN width as two selected experts. | |
| config=Config(width=128,layers=3,intermediate=512 if dense else 256, | |
| experts=4,top_k=2,dense=dense,input_dim=130,output_dim=128,heads=4) | |
| model=WorldModel(config).to(device) | |
| optimizer=torch.optim.AdamW(model.parameters(),lr=.0005,weight_decay=.001) | |
| started=time.perf_counter();losses=[] | |
| for index in range(a.steps): | |
| positions=torch.randint(len(x),(128,),device=device) | |
| prediction,balance,z_loss,loads=model(x[positions]) | |
| loss=F.mse_loss(prediction,y[positions]) | |
| objective=loss+.005*balance+.0001*z_loss | |
| optimizer.zero_grad(set_to_none=True);objective.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(),1.);optimizer.step() | |
| if index%200==0 or index+1==a.steps: | |
| row=dict(kind='dense' if dense else 'moe',seed=seed,step=index+1, | |
| training_latent_delta_mse=float(loss.detach()),balance=float(balance.detach())) | |
| losses.append(row);print(json.dumps(row),flush=True) | |
| model.eval() | |
| evaluation=evaluate(model,vz,valid,codec,mean,std,device) | |
| record=dict(kind='dense' if dense else 'moe',seed=seed,accounting=parameter_audit(config), | |
| train_seconds=time.perf_counter()-started,training_log=losses,evaluation=evaluation) | |
| records.append(record) | |
| atomic_torch_save(dict(status='NATIVE_VISUAL_DYNAMICS_TOY_ONLY',model=model.state_dict(), | |
| config=asdict(config),mean=mean,std=std, | |
| codec_sha256=manifest['codec_sha256'],seed=seed,steps=a.steps), | |
| a.out/f'{record["kind"]}-seed-{seed}.pt') | |
| (a.out/'partial-results.json').write_text(json.dumps(records,indent=2),encoding='utf-8') | |
| print(json.dumps(dict(kind=record['kind'],seed=seed,means=evaluation['means'])),flush=True) | |
| report=dict(status='NATIVE_VISUAL_DYNAMICS_TOY_PILOT_COMPLETED',uses_llm=False,records=records, | |
| trained_100B_model=False,general_world_model=False, | |
| limitations=['Small two-object synthetic suite, not a general visual world model.', | |
| 'No native >100B checkpoint has been allocated or trained.', | |
| 'One-step development evaluation; long rollouts and real-world transfer remain.', | |
| 'No large-model superiority, significance, or publishable novelty claim.']) | |
| (a.out/'result.json').write_text(json.dumps(report,indent=2),encoding='utf-8') | |
| if __name__=='__main__': | |
| main() | |