You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
defmoduleMOE.Treedo@moduledoc""" Recursively maps a function over nested tuples of tensors. """defmap(tuple,func)whenis_tuple(tuple)dotuple|>Tuple.to_list()|>Enum.map(&map(&1,func))|>List.to_tuple()end# The base case: When it hits a tensor (or a compile-time Expr), apply the functiondefmap(tensor,func)dofunc.(tensor)endend
defmoduleMOE.CurriculumStreamerdodefbuild_infinite_stream(directory_path,batch_size)dotarget_shards=Path.wildcard(Path.join(directory_path,"*.bin"))iflength(target_shards)==0doraise"CRITICAL: No .bin shards found in directory: #{directory_path}"endStream.iterate(1,&(&1+1))|>Stream.flat_map(fnepoch->:rand.seed(:exsss,{epoch,epoch,epoch})shuffled_shards=Enum.shuffle(target_shards)IO.puts("\n🔄 Epoch #{epoch} Started | Shuffling #{length(target_shards)} shards...")Stream.flat_map(shuffled_shards,fnpath->tensor=File.read!(path)|>:erlang.binary_to_term()total_seqs=Nx.axis_size(tensor,0)num_batches=div(total_seqs,batch_size)# 1. Generate all the slice indices0..(num_batches-1)# 2. Slice the tensor into actual batch tensors|>Enum.map(fni->Nx.slice_along_axis(tensor,i*batch_size,batch_size,axis: 0)end)# 3. Shuffle the list of batches|>Enum.shuffle()end)#|> Enum.shuffle() # shuffle it all together nowend)endend
defmoduleMOE.Phase2_EvaldoimportNx.Defndefnstep_cross_entropy(logits,targets)dovocab_size=Nx.axis_size(logits,-1)one_hot=Nx.equal(Nx.iota({vocab_size}),Nx.new_axis(targets,-1))max_logits=Nx.reduce_max(logits,axes: [-1],keep_axes: true)safe_logits=Nx.subtract(logits,max_logits)log_probs=Nx.subtract(safe_logits,Nx.log(Nx.sum(Nx.exp(safe_logits),axes: [-1],keep_axes: true)))Nx.negate(Nx.sum(Nx.multiply(one_hot,log_probs),axes: [-1]))enddefncompute_sentence_loss(input_tokens,target_tokens,h_init,trainable)doseq_len=Nx.axis_size(input_tokens,1)-1batch_size=Nx.axis_size(input_tokens,0)# Explicitly initialize the batch-sized accumulatorszero_batch=Nx.broadcast(0.0,{batch_size})result=while{i=0,total_loss=zero_batch,valid_tokens=zero_batch,h=h_init,inf=input_tokens,tgf=target_tokens,tr=trainable},Nx.less(i,seq_len)do# 1. Grab the single character context and targetx_t=inf[[..,i]]t_t=tgf[[..,i]]# 2. Forward pass through the reservoir{logits,h_new}=MOE.SSM.forward_step(x_t,h,tr)# 3. Calculate 1-step prediction lossstep_loss=step_cross_entropy(logits,t_t)# 4. MASK: 1.0 if valid text, 0.0 if ASCII 1 (SOH / Padding)mask=Nx.not_equal(t_t,1)|>Nx.as_type(:f32)masked_loss=Nx.multiply(step_loss,mask){i+1,Nx.add(total_loss,masked_loss),Nx.add(valid_tokens,mask),h_new,inf,tgf,tr}end{_,acc_loss,val_tokens,_,_,_,_}=resulttotal_loss=Nx.divide(acc_loss,Nx.add(val_tokens,1.0e-8))total_lossendend
defmoduleMOE.Probedodefrun(params)dogpu=Nx.default_backend()muzzle=MOE.Inference.build_muzzle()|>Nx.backend_copy(gpu)IO.puts("\n"<>String.duplicate("=",60))IO.puts("MOE UNIVERSAL SSM INFERENCE PROBE")IO.puts(String.duplicate("=",60))IO.puts("\n📚 IN-DISTRIBUTION")IO.puts(String.duplicate("-",40))probe(params,"[W]happy [T]adj [D]","Definition of 'happy'",muzzle)probe(params,"[W]water [T]noun [D]","Definition of 'water'",muzzle)probe(params,"[W]run [T]verb [D]","Definition of 'run'",muzzle)IO.puts("\n🔄 REVERSE FORMAT")IO.puts(String.duplicate("-",40))probe(params,"[D]A feeling of great pleasure [W]","Word for pleasure",muzzle)probe(params,"[D]To move swiftly on foot [W]","Word for swift",muzzle)IO.puts("\n🔀 NEAR-DISTRIBUTION")IO.puts(String.duplicate("-",40))probe(params,"The word 'happy' means","Prose definition",muzzle)probe(params,"[W]love [R]Related:","Relational format",muzzle)probe(params,"[W]cold [T]adj [D]The opposite","Partial def",muzzle)IO.puts("\n💬 OUT-OF-DISTRIBUTION")IO.puts(String.duplicate("-",40))probe(params,"What is the meaning of life?","Philosophical",muzzle)probe(params,"Hello, how are you?","Greeting",muzzle)probe(params,"Can you define the word","Conversational",muzzle)probe(params,"Do state space models dream of recursive sheep?","Special",muzzle)IO.puts("\n🔤 MORPHOLOGY")IO.puts(String.duplicate("-",40))probe(params,"[W]Electr","Electr-",muzzle)probe(params,"[W]Mecha","Mecha-",muzzle)probe(params,"[W]Inter","Inter-",muzzle)probe(params,"[W]Ortho","Ortho-",muzzle)probe(params,"[W]Trans","Trans-",muzzle)IO.puts("\n"<>String.duplicate("=",60))enddefpprobe(params,prompt,label,muzzle)doIO.puts("\n▶ #{label}")IO.puts(" Prompt: #{inspect(prompt)}")# Call the V17 Inferencesampled=MOE.Inference.top_k(params,prompt,muzzle)IO.puts(" Top-k: #{inspect(String.slice(sampled,String.length(prompt)..-1//1))}"):erlang.garbage_collect(self())endendIO.puts("✅ MOE.Probe loaded")
✅ DLM.Probe loaded
:ok
# --- Inference Probe ---full_state_path="v7667_DLM_512sq_yolo_em2b4u_p3d6expa2fx_checkpoint_step_4600.bin"ifFile.exists?(full_state_path)doIO.puts("💾 Loading latest V18 Checkpoint...")%{trainable: t_p}=File.read!(full_state_path)|>:erlang.binary_to_term()params_gpu=MOE.Tree.map(t_p,&Nx.backend_copy(&1,gpu))IO.puts("✅ Model Loaded")# Fire the battery!MOE.Probe.run(params_gpu)elseIO.puts("❌ No checkpoint found at #{full_state_path}")end
💾 Loading latest V18 Checkpoint...
✅ Model Loaded
============================================================
DLM UNIVERSAL SSM INFERENCE PROBE
============================================================
📚 IN-DISTRIBUTION
----------------------------------------
▶ Definition of 'happy'
Prompt: "[W]happy [T]adj [D]"
Top-k: "No s wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Definition of 'water'
Prompt: "[W]water [T]noun [D]"
Top-k: "Dend thilind we a th th thanof thend s t he s t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Definition of 'run'
Prompt: "[W]run [T]verb [D]"
Top-k: "Nou s wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
🔄 REVERSE FORMAT
----------------------------------------
▶ Word for pleasure
Prompt: "[D]A feeling of great pleasure [W]"
Top-k: "No he he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Word for swift
Prompt: "[D]To move swiftly on foot [W]"
Top-k: "Nor we he he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
🔀 NEAR-DISTRIBUTION
----------------------------------------
▶ Prose definition
Prompt: "The word 'happy' means"
Top-k: "pere h we st atin he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Relational format
Prompt: "[W]love [R]Related:"
Top-k: "No s wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Partial def
Prompt: "[W]cold [T]adj [D]The opposite"
Top-k: "Nor we he he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
💬 OUT-OF-DISTRIBUTION
----------------------------------------
▶ Philosophical
Prompt: "What is the meaning of life?"
Top-k: "pathas atin he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Greeting
Prompt: "Hello, how are you?"
Top-k: "No s wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Conversational
Prompt: "Can you define the word"
Top-k: "Sthed. aner atin he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Special
Prompt: "Do state space models dream of recursive sheep?"
Top-k: "Dof thend s t he s t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
🔤 MORPHOLOGY
----------------------------------------
▶ Electr-
Prompt: "[W]Electr"
Top-k: "Dind the as tous tear tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Mecha-
Prompt: "[W]Mecha"
Top-k: "Sore whe t wane wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Inter-
Prompt: "[W]Inter"
Top-k: "Sore whe t wane wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Ortho-
Prompt: "[W]Ortho"
Top-k: "Sore whe t wane wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
▶ Trans-
Prompt: "[W]Trans"
Top-k: "Sore whe t wane wanofo tonghean he he wa he t s win a ato t the th are te tine athe an tounge whato the asereand there the a t t angofis the that s ange s t ang an sthathe t areng t thand and whaner athe and he woure s torer the s ang hend t asthe "
============================================================
:ok
Train
defmoduleMOE.Phase2TrainerdoimportNx.Defndefnstep_cross_entropy(logits,targets)dovocab_size=Nx.axis_size(logits,-1)one_hot=Nx.equal(Nx.iota({vocab_size}),Nx.new_axis(targets,-1))max_logits=Nx.reduce_max(logits,axes: [-1],keep_axes: true)safe_logits=Nx.subtract(logits,max_logits)log_probs=Nx.subtract(safe_logits,Nx.log(Nx.sum(Nx.exp(safe_logits),axes: [-1],keep_axes: true)))# Returns a {batch_size} 1D tensor of individual sequence lossesNx.negate(Nx.sum(Nx.multiply(one_hot,log_probs),axes: [-1]))enddefncompute_sequence_loss(input_tokens,params)dobatch_size=Nx.axis_size(input_tokens,0)h_start=Nx.broadcast(0.0,{batch_size,128,128})|>Nx.as_type(:f32)zero_scalar=Nx.tensor(0.0,type: :f32)result=while{i=0,total_loss=zero_scalar,valid_tokens=zero_scalar,inf=input_tokens,h=h_start,tp=params},Nx.less(i,Nx.axis_size(inf,1)-1)dox_t=inf[[..,i]]t_t=inf[[..,i+1]]{logits,h_new}=MOE.SSM.forward_step(x_t,h,tp)step_loss=step_cross_entropy(logits,t_t)mask=Nx.not_equal(t_t,1)|>Nx.as_type(:f32)masked_loss_scalar=Nx.sum(Nx.multiply(step_loss,mask))valid_tokens_scalar=Nx.sum(mask){i+1,Nx.add(total_loss,masked_loss_scalar),Nx.add(valid_tokens,valid_tokens_scalar),inf,h_new,tp}end{_,acc_loss,val_tokens,_,_,_}=result# compress and save final hlong for a long term memory context?total_loss=Nx.divide(acc_loss,Nx.add(val_tokens,1.0e-8))total_lossenddefncompute_grad(params,batch_tokens)doseq_len=Nx.axis_size(batch_tokens,1)-1input_tokens=Nx.slice_along_axis(batch_tokens,0,seq_len,axis: 1){loss,raw_grads}=value_and_grad(params,fnp->compute_sequence_loss(input_tokens,p)end){loss,raw_grads}endend
defmoduleMOE.CheckpointManagerdo@moduledoc""" Scans the directory for the latest checkpoint of a specific run prefix. If no checkpoints exist, it triggers a completely fresh initialization. """defget_resume_state(run_prefix)docheckpoints=Path.wildcard("#{run_prefix}_checkpoint_step_*.bin")ifEnum.empty?(checkpoints)doifFile.exists?("#{run_prefix}_final.bin")doIO.puts("Found completed run: #{run_prefix}_final.bin"){"#{run_prefix}_final.bin",:completed}elseIO.puts("No checkpoints found for '#{run_prefix}'. Starting FRESH from Genesis."){:fresh,0}endelse# Extract step numbers using regex and find the maximumlatest_file=Enum.max_by(checkpoints,fnfile->caseRegex.run(~r/_step_(\d+)\.bin$/,file)do[_,step_str]->String.to_integer(step_str)_->-1endend)[_,step_str]=Regex.run(~r/_step_(\d+)\.bin$/,latest_file)step=String.to_integer(step_str)IO.puts("Auto-Resuming '#{run_prefix}' from Step #{step}..."){latest_file,step}endendend
run_prefix="v67_MOE_512sq_yolo_em2b4u_finmb"# frozen_path = "./data/f_semantic_reservoir_512D.bin"total_steps=7301{load_path,start_step}=MOE.CheckpointManager.get_resume_state(run_prefix)ifstart_step==:completeddoIO.puts("This run has already reached #{total_steps} steps. Exiting.")elsebatch_size=128# ./data/bbylm_512_fullmix (256 too) bbylm_lg_wiki_512 # try data with sq len of just one worddata_dir="./data/bbylm_512_strict"#/babylm_high_sanitize(sq 256), /bbylm_512_strict(sq 512)IO.puts("Initializing Lazy Curriculum Data Stream from [#{data_dir}]...")data_stream=MOE.CurriculumStreamer.build_infinite_stream(data_dir,batch_size)|>Stream.drop(start_step){starting_trainable,initial_key}=ifload_path==:freshdoIO.puts("Igniting brand new Trainable weights for #{run_prefix}..."){ip,ik}=MOE.Parameter.init(Nx.Random.key(System.system_time()))# %{frozen: {r, _m}} = File.read!(frozen_path) |> :erlang.binary_to_term(){ip,ik}elseIO.puts("Loading Trainable Weights from #{load_path}...")# Checkpoints now only contain %{trainable: ...}%{trainable: t_p}=File.read!(load_path)|>:erlang.binary_to_term(){t_p,Nx.Random.key(System.system_time())}endtrainable_gpu=MOE.Tree.map(starting_trainable,&Nx.backend_copy(&1,gpu))step_count=Nx.tensor(start_step)|>Nx.backend_copy(gpu)# ZIP FROM THE START_STEP{final_p,_key,_step}=Enum.reduce(Stream.zip(start_step..(total_steps-1),data_stream),{trainable_gpu,initial_key,step_count},fn{step,cpu_batch},{cur_tr,cur_key,c_step}->gpu_batch=Nx.backend_copy(cpu_batch,gpu)base_lr=7.0e-4min_lr=7.0e-5warmup_steps=800cooldown_start=6600current_lr=ifstep<warmup_stepsdobase_lr*(step/warmup_steps)elseifstep<cooldown_startdobase_lrelseprogress=min(max((step-cooldown_start)/(total_steps-cooldown_start),0.0),1.0)min_lr+0.5*(base_lr-min_lr)*(1.0+:math.cos(:math.pi()*progress))endendlr_tensor=Nx.tensor(current_lr,type: :f32)|>Nx.backend_copy(gpu)split_keys=Nx.Random.split(cur_key)next_key=split_keys[1]{loss_tensor,grads}=MOE.Phase2Trainer.compute_grad(cur_tr,gpu_batch)loss_val=Nx.to_number(loss_tensor){up_tr,up_step}=MOE.Optimizer.update(cur_tr,grads,c_step,lr_tensor)# Telemetryifrem(step,100)==0do{emb,dec,key}=up_tremb_norm=emb|>Nx.pow(2)|>Nx.sum()|>Nx.sqrt()|>Nx.to_number()|>Float.round(4)dec_norm=dec|>Nx.pow(2)|>Nx.sum()|>Nx.sqrt()|>Nx.to_number()|>Float.round(4)key_norm=key|>Nx.pow(2)|>Nx.sum()|>Nx.sqrt()|>Nx.to_number()|>Float.round(4)IO.puts("➡️ Step #{step} | LR: #{Float.round(current_lr,6)} | Loss: #{Float.round(loss_val,4)} | emb #{emb_norm} | dec #{dec_norm} | key #{key_norm}"):erlang.garbage_collect()end# Checkpoint Saving (Save both structures!) try every 500 for 64bx512sqlnifrem(step,200)==0andstep>0doIO.puts("Checkpoint reached! Saving Step #{step}...")cpu_tr=MOE.Tree.map(up_tr,&Nx.backend_copy(&1,Nx.BinaryBackend))filename="#{run_prefix}_checkpoint_step_#{step}.bin"File.write!(filename,:erlang.term_to_binary(%{trainable: cpu_tr})):erlang.garbage_collect()end{up_tr,next_key,up_step}end)IO.puts("Saving Final Fourier Reservoir Weights...")fin_t=MOE.Tree.map(final_p,&Nx.backend_copy(&1,Nx.BinaryBackend))# You could save frozen here too if desired, but since they are deterministic it's optional.File.write!("#{run_prefix}_final.bin",:erlang.term_to_binary(%{trainable: fin_t}))IO.puts("Training Complete!")end