Continual learning, catastrophic forgetting and model merging
Measure forgetting and study continual pretraining, replay, EWC, alignment tax and model merging.
After this lesson you can
- Measure forgetting with a task-by-stage performance matrix and backward and forward transfer metrics.
- Design continual pretraining with learning-rate rewarming and a justified replay fraction.
- Derive EWC as a Laplace posterior approximation and apply diagonal Fisher information.
- Merge fine-tuned models with interpolation, task arithmetic, TIES and DARE, and explain when it works.
- Quantify and mitigate the alignment tax of SFT or DPO on base-model capabilities.
Before you start
- 20Mid-training and annealing on high-quality dataPretraining token budgetLoRA learning-forgetting trade-offInstruction tuningVocabulary extensionLog-likelihood multiple-choice evaluationKL-regularized RLHF objective
- 05Fisher informationFisher information matrix
- 14Laplace approximation
- 06Mode connectivity
- 13Dataset shift taxonomyDomain adaptation bound
Learn something new without erasing the old
A model trained on general text later receives recent technical documents. Its new-domain loss falls, but does it still answer as well in the old domain? Catastrophic forgetting describes a pronounced loss of previous performance during subsequent learning. Not every metric change is catastrophic: an initial baseline, uncertainty and a task-appropriate magnitude criterion are needed.
Shared parameters explain a possibility of interference: an update improving one dataset changes representations used by another. This does not determine how much forgetting will occur in a particular case. The previous distribution may also be unknown; an accessible general collection is a useful indicator, but not proof it samples the original pretraining distribution.
McCloskey and Cohen studied interference in connectionist networks learning associations sequentially. An LLM is a different system, but shares the difficulty of modifying parameters used by previous data. A domain or language change is a form of distribution shift: measure important capabilities and data groups separately.
A task-by-stage matrix
To measure forgetting metrics, define as accuracy on task after training through stage . Assuming tasks learned in order, mean backward transfer is
A negative value indicates mean decline compared with performance immediately after learning each task. It is not necessarily the worst drop experienced across the entire trajectory. If measurements exist before learning each task and an initial baseline is available, one forward-transfer definition is . A different baseline or index changes the question; publish it with the matrix.
Preparing the task matrix.
A loss matrix, such as bits per byte, has the opposite direction from an accuracy matrix: lower is better. Do not apply an accuracy BWT formula to loss and interpret the sign in the same way. Retain per-task, per-stage performance, held-out set and uncertainty: a mean can hide a large regression in a small domain.
This matrix shows a short test of the second lab, with four updates per stage and four test documents per domain. It checks the procedure, not which method best retains capabilities.
Rewarm and replay data
Continual pretraining continues optimizing a checkpoint on a new distribution. A learning rate already decayed almost to zero may be too small for adaptation; rewarming it and decaying again lets you explore the adaptation-stability tradeoff. A higher peak can also move parameters further, but its effect depends on data, optimizer, duration and scale; there is no universally safe value.
Data replay mixes old examples with new ones. Under a fixed budget, increasing replay reduces new tokens seen; if both budgets remain intact, more compute is spent. Split evaluation data before building the mixture and check duplicates and licenses. Choose the proportion against an adaptation-retention curve, not new loss alone.
Preparing continual-training measurements.
The figure includes a short lab run with one seed and four updates per condition. Under conditions with 25% replay probability, three old documents and one new one were selected: such a small sample need not reproduce the expected proportion and cannot establish forgetting or superiority of a configuration.
In table 2 of Ibrahim and colleagues, a 405 million parameter model moved from Pile to SlimPajama with a 300 billion token second-phase budget. Without replay, validation loss was 2.44 on Pile and 2.50 on SlimPajama; with 5% replay and equivalent compute it was 2.23 and 2.51. This illustrates a tradeoff in that configuration, not a universal 5% recipe. For a stronger shift to German the authors explored other proportions.
Domain adaptation, or DAPT, continues training on text from a specific field; Gururangan and colleagues study this approach. If extending vocabulary or changing tokenization, preserve ID correspondence and also evaluate representation of the old domain. A new token does not itself add knowledge, and poorly chosen replay may fail to cover relevant capabilities.
When adding a language, hold out text and tasks from it and earlier languages, with their respective licenses. Vocabulary extension also changes text segmentation; evaluate the same original content and declare the protocol before comparing losses.
To compare models with different tokenizations, bits per byte can help: sum negative log-likelihood in nats for a text and divide by and the number of UTF-8 bytes in the same text. Declare which special tokens and context boundaries are included; do not count padding or compare different texts as though the denominator fixed every protocol difference.
The lab continues SmolLM2-135M with float32 weights and bfloat16 autocast. It needs CUDA, torch, transformers, datasets, huggingface_hub and numpy. The general domain uses WikiText-2 raw; the new domain uses the science and technology class of AG News. Its card states an unknown license; WikiText lists CC BY-SA 3.0 and GFDL. These are domain samples, not a reconstruction of the pretraining corpus or all technical text.
The WikiText card is inconsistent: its tags state CC BY-SA 3.0 and GFDL, while its license section mentions CC BY-SA 4.0. Check source terms before reusing the corpus; we do not treat that discrepancy as resolved.
The split holds out test and validation before selecting training and removes exact duplicates across domains and splits. Only documents that fit entirely and whose tokenizer reconstructs the original UTF-8 are evaluated. Loss sums surprise of all their tokens, with BOS as context, and divides by original bytes and log 2: it excludes padding and does not use truncated bytes as denominator.
Each condition starts from the same base and combines a rewarming peak with per-document replay probability. The log also gives documents, tokens and bytes actually processed: matching steps does not match bytes. Both tasks are evaluated on validation during training and initial and final test are reported, without using test to select the condition. Curves are based exclusively on real outputs; a short test does not demonstrate forgetting.
By default the reader’s full sweep runs; ORYON_QUICK=1 reduces samples and steps, ORYON_OFFLINE=1 requires cached data and model, and ORYON_CONTINUAL_DIR sets the output folder. Optionally ORYON_SAVE_RUN saves one checkpoint identified by field id from a previous run; the others are discarded to avoid filling disk. The saved checkpoint does not contain optimizer state. This exercise relates to continual pretraining and rewarming, without reproducing their scales.
"""Preentrenamiento continuo con recalentamiento y replay de texto real."""
import gc
import hashlib
import json
import math
import os
import random
from pathlib import Path
import numpy as np
import torch
import datasets
import transformers
from datasets import DownloadConfig, load_dataset
from huggingface_hub import snapshot_download
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
QUICK=os.getenv('ORYON_QUICK')=='1'; OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
OUT=Path(os.getenv('ORYON_CONTINUAL_DIR','./oryon-continual'))
MODEL='HuggingFaceTB/SmolLM2-135M'; REV='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
OLD='Salesforce/wikitext'; OLD_REV='b08601e04326c79dfdd32d625aee71d232d685c3'
NEW='fancyzhx/ag_news'; NEW_REV='eb185aade064a813bc0b7f42de02595523103ca4'
LIMITS={'train':16 if QUICK else 4096,'validation':4 if QUICK else 64,'test':4 if QUICK else 64}
MAX_TOKENS=512; STEPS=4 if QUICK else 384; DATA_SEED=25250
SEEDS=[2501] if QUICK else [2501,2502,2503]
PEAKS=[1e-5,5e-5] if QUICK else [1e-5,3e-5,5e-5]
REPLAYS=[0.,.25] if QUICK else [0.,.1,.25]
torch.set_num_threads(1)
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for chunk in iter(lambda:f.read(1048576),b''): h.update(chunk)
return h.hexdigest()
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def prepare_data(tok):
if tok.bos_token_id is None: raise ValueError('El tokenizador debe tener BOS')
config=DownloadConfig(local_files_only=OFFLINE)
wiki=load_dataset(OLD,'wikitext-2-raw-v1',revision=OLD_REV,download_config=config)
news=load_dataset(NEW,revision=NEW_REV,download_config=config)
pools={'old':{'train':[],'validation':[],'test':[]},'new':{'train':[],'validation':[],'test':[]}}
for split in ('train','validation','test'):
for row in wiki[split]:
text=row.get('text')
if isinstance(text,str) and text.strip(): pools['old'][split].append(text)
for raw_split in ('train','test'):
for row in news[raw_split]:
if row.get('label')!=3: continue
text=row.get('text')
if not isinstance(text,str) or not text.strip(): continue
split='test' if raw_split=='test' else ('validation' if int(sha(text)[:8],16)%10==0 else 'train')
pools['new'][split].append(text)
data={domain:{split:[] for split in LIMITS} for domain in ('old','new')}; seen=set()
# Prioridad a test, luego validación. Un hash idéntico no cruza dominios o splits.
for split in ('test','validation','train'):
for domain in ('old','new'):
candidates=[]
for text in pools[domain][split]:
ident=sha(text)
if ident in seen: continue
seen.add(ident); candidates.append(text)
random.Random(DATA_SEED).shuffle(candidates)
for text in candidates:
ident=sha(text)
ids=tok.encode(text,add_special_tokens=False)
if not ids or len(ids)>MAX_TOKENS: continue
if tok.decode(ids,skip_special_tokens=False,clean_up_tokenization_spaces=False)!=text: continue
data[domain][split].append({'id':ident,'text':text,'ids':ids,'bytes':len(text.encode('utf-8'))})
if len(data[domain][split])==LIMITS[split]: break
if len(data[domain][split])!=LIMITS[split]: raise ValueError('No hay suficientes documentos válidos en '+domain+' '+split)
all_ids=[r['id'] for domain in data.values() for rows in domain.values() for r in rows]
if len(all_ids)!=len(set(all_ids)): raise ValueError('Particiones con duplicados exactos')
return data
def evaluate_bpb(model,rows,bos):
total_nll=0.; total_bytes=total_tokens=0
with torch.inference_mode():
for row in rows:
ids=row['ids']; x=torch.tensor([[bos]+ids],dtype=torch.long,device='cuda')
with torch.autocast(device_type='cuda',dtype=torch.bfloat16):
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,:-1].float()
target=x[0,1:]; total_nll+=float(F.cross_entropy(logits,target,reduction='sum'))
total_tokens+=len(ids); total_bytes+=row['bytes']
if not total_bytes or not total_tokens: raise ValueError('Evaluación vacía')
return {'documents':len(rows),'bytes':total_bytes,'tokens':total_tokens,'nll_nats':total_nll,
'bits_per_byte':total_nll/(math.log(2)*total_bytes),
'protocol':'BOS; todos los tokens originales; sin padding ni truncamiento'}
def learning_rate(step,total,peak):
if total<2 or not 0<=step<total or not math.isfinite(peak) or peak<=0: raise ValueError('Calendario inválido')
warm=max(1,total//10)
if step<warm: return peak*(.05+.95*step/warm)
progress=(step-warm)/max(1,total-1-warm)
return peak*(.1+.9*.5*(1+math.cos(math.pi*progress)))
def fingerprint():
folder=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,
allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
weights={p.name:file_hash(p) for p in sorted(folder.glob('*.safetensors'))}
if not weights: raise ValueError('Pesos base ausentes')
return {'model':MODEL,'revision':REV,'weights_sha256':weights,
'tokenizer_sha256':{p.name:file_hash(p) for p in (folder/'tokenizer.json',folder/'tokenizer_config.json') if p.exists()}}
def load_base():
model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE,dtype=torch.float32).to('cuda')
model.config.use_cache=False
return model
def run_condition(tok,data,seed,peak,replay):
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);torch.cuda.manual_seed_all(seed)
chooser=random.Random(seed);model=load_base();optimizer=torch.optim.AdamW(model.parameters(),lr=peak)
seen={'old':0,'new':0}; training_tokens=training_bytes=0; loss_history=[]
history=[]
def checkpoint_metrics(step):
model.eval()
return {'step':step,'old':evaluate_bpb(model,data['old']['validation'],tok.bos_token_id),
'new':evaluate_bpb(model,data['new']['validation'],tok.bos_token_id),
'training_tokens':training_tokens,'training_bytes':training_bytes,'seen_documents':dict(seen)}
history.append(checkpoint_metrics(0))
model.eval(); test_initial={'old':evaluate_bpb(model,data['old']['test'],tok.bos_token_id),
'new':evaluate_bpb(model,data['new']['test'],tok.bos_token_id)}
for step in range(STEPS):
model.train(); domain='old' if chooser.random()<replay else 'new'
pool=data[domain]['train']; row=pool[chooser.randrange(len(pool))]; ids=row['ids']
x=torch.tensor([[tok.bos_token_id]+ids],dtype=torch.long,device='cuda')
lr=learning_rate(step,STEPS,peak)
for group in optimizer.param_groups: group['lr']=lr
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda',dtype=torch.bfloat16):
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,:-1].float()
loss=F.cross_entropy(logits,x[0,1:],reduction='mean')
if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),1.);optimizer.step()
seen[domain]+=1;training_tokens+=len(ids);training_bytes+=row['bytes']
loss_history.append({'step':step+1,'domain':domain,'lr':lr,'nll_per_token':float(loss.detach()),'id':row['id']})
if step+1==STEPS or (step+1)%(2 if QUICK else 64)==0: history.append(checkpoint_metrics(step+1))
model.eval(); test={'old':evaluate_bpb(model,data['old']['test'],tok.bos_token_id),
'new':evaluate_bpb(model,data['new']['test'],tok.bos_token_id)}
run_id=f'seed-{seed}-lr-{peak:.0e}-replay-{round(replay*100)}'; saved=None
if os.getenv('ORYON_SAVE_RUN','')==run_id:
path=OUT/'checkpoints'/run_id; model.save_pretrained(path,safe_serialization=True);tok.save_pretrained(path)
weights={p.name:file_hash(p) for p in sorted(path.glob('*.safetensors'))}
if not weights: raise ValueError('No se guardaron pesos')
saved={'path':str(path),'weights_sha256':weights,'note':'Solo inferencia; no incluye estado del optimizador.'}
result={'id':run_id,'seed':seed,'peak_lr':peak,'replay_fraction':replay,'steps':STEPS,'history':history,
'test_initial':test_initial,'test_final':test,'saved_checkpoint':saved,
'training':{'tokens':training_tokens,'bytes':training_bytes,
'documents_drawn':dict(seen),'losses':loss_history}}
del optimizer,model,loss,logits,x;gc.collect();torch.cuda.empty_cache()
return result
def main():
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): raise RuntimeError('Se necesita CUDA con bfloat16')
OUT.mkdir(parents=True,exist_ok=True)
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
data=prepare_data(tok); provenance=fingerprint();runs=[]
for seed in SEEDS:
for peak in PEAKS:
for replay in REPLAYS: runs.append(run_condition(tok,data,seed,peak,replay))
report={'quick':QUICK,'source':{'old':{'id':OLD,'revision':OLD_REV,'config':'wikitext-2-raw-v1',
'licence':'CC BY-SA 3.0 y GFDL, según ficha'},
'new':{'id':NEW,'revision':NEW_REV,'label':3,'topic':'Science/Technology',
'licence':'desconocida según ficha'}},
'model':provenance,'data_seed':DATA_SEED,'bos_id':tok.bos_token_id,
'versions':{'torch':str(torch.__version__),'transformers':str(transformers.__version__),
'datasets':str(datasets.__version__),'numpy':str(np.__version__),
'device':torch.cuda.get_device_name()},
'splits':{d:{s:[r['id'] for r in rows] for s,rows in parts.items()} for d,parts in data.items()},
'config':{'max_tokens_per_document':MAX_TOKENS,'steps':STEPS,'peaks':PEAKS,'replays':REPLAYS,
'seeds':SEEDS,'schedule':'lineal 5 % a pico durante primera décima, coseno hasta 10 % del pico',
'trainable':'todos los pesos','precision':'pesos float32, autocast bfloat16','optimizer':'AdamW con valores por defecto'},
'runs':runs,
'limits':'WikiText es un proxy general, no prueba de pertenencia al preentrenamiento de SmolLM2. AG News de ciencia y tecnología es un dominio distinto, no una muestra representativa de todo el texto técnico. Las proporciones de replay se fijan en probabilidad por documento y se informan las frecuencias realizadas. Sin padding ni truncar; los bytes son los del texto UTF-8 original. Una prueba corta no demuestra olvido ni mejora.'}
write_json(OUT/'continual-report.json',report)
print('Informe:',OUT/'continual-report.json',flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.EWC as a local approximation
Elastic weight consolidation, EWC, starts from a sequential Bayesian update. If A and B data are conditionally independent given parameters,
Suppose A’s log posterior has an interior maximum and admits a quadratic approximation with positive precision near that point. Minimizing the negative log posterior for B yields
up to constants. EWC replaces that precision with a diagonal approximation related to Fisher and a scale :
This replacement is not a general identity between observed Hessian and Fisher, and the diagonal does not preserve parameter correlations. Prior, example count and whether losses are summed or averaged affect scale; must be interpreted with those conventions. Kirkpatrick and colleagues present the approximation and also show limits of diagonal estimation in their experiments.
The Laplace approximation provides the local form and the Fisher matrix the notion of probabilistic sensitivity. Replacing all diagonal entries with the same value gives an L2 penalty toward : it protects every coordinate equally without distinguishing estimated importance. It is not an L2 penalty toward zero.
With parameters, storing a full matrix requires on the order of values; the diagonal needs on the order of , plus the parameter anchor. Even this version adds memory and compute in an LLM, and a separate diagonal per task increases cost with task count. Restricting estimation to part of the model, as the lab does, changes the problem and must be declared.
In this analytic example, diagonal Fisher coincides by construction with task A’s Hessian. The optimum is exact for two quadratic losses, and the trajectory is continuous gradient flow from A’s optimum; it is not a real-model measurement.
import math
# Un ejemplo exacto: Fisher coincide con la Hessiana de A por construcción.
a = (-1.5, -1.)
b = (1.5, 1.)
fisher = (4., .5)
curvature_b = (1., 1.5)
def loss(theta, center, curvature):
return .5 * sum(h*(x-c)**2 for x,c,h in zip(theta,center,curvature))
def optimum(strength):
if not math.isfinite(strength) or strength < 0:
raise ValueError('lambda debe ser finita y no negativa')
return tuple((h*y+strength*f*x)/(h+strength*f)
for x,y,f,h in zip(a,b,fisher,curvature_b))
def trajectory(strength, time):
if not math.isfinite(time) or time < 0:
raise ValueError('el tiempo debe ser finito y no negativo')
target = optimum(strength)
return tuple(z+(x-z)*math.exp(-(h+strength*f)*time)
for x,z,h,f in zip(a,target,curvature_b,fisher))
def gradient(theta, strength):
return tuple(h*(x-y)+strength*f*(x-z)
for x,y,z,h,f in zip(theta,b,a,curvature_b,fisher))
assert trajectory(1,0) == a
assert all(abs(x-y) < 1e-12 for x,y in zip(optimum(0),b))
for strength in (0,.1,1,8):
result = optimum(strength)
assert max(abs(x) for x in gradient(result,strength)) < 1e-12
assert max(abs(x-y) for x,y in zip(trajectory(strength,50),result)) < 1e-12
print('lambda:',strength,'óptimo:',result,'L_A:',loss(result,a,fisher),'L_B:',loss(result,b,curvature_b))
point = trajectory(1,2)
print('lambda 1, tiempo 2: posición',point,'L_A:',loss(point,a,fisher),'L_B:',loss(point,b,curvature_b))
print('F = Hessiana(A) solo en este modelo analítico; no es una medida de un modelo.')The model Fisher for a fixed input can be written . Averaging squared gradients with observed labels gives an empirical Fisher, which generally differs from that expectation under the model. Squaring a batch’s mean gradient is also not the same as averaging per-example gradient squares. Declare estimator, inputs, sample count and normalization.
If is large, the quadratic model penalizes moving that coordinate more, holding others fixed. A coordinate with is unprotected by that approximation; this does not prove movement is harmless far from the expansion point. The graph is a controlled mathematical model, not a map of an LLM’s actual loss.
Adapters and alignment tax
A separate LoRA adapter leaves base weights frozen. When disabled, the base recovers its own logits if no other parameters or states changed. This protects the base checkpoint, but does not guarantee the policy with adapter enabled retains all capabilities, or that one task’s adapter preserves another when the two interfere. Evaluate base, adapters and combinations on the same held-out tasks.
The alignment tax is a regression in a measured capability after an alignment procedure. It depends on the metric: a format change can worsen a benchmark without loss of all ability, and improved preferences do not prove general retention. Ouyang and colleagues observed regressions on several public tasks with PPO and studied PPO-ptx, which mixes pretraining updates. In their experiments it mitigated regressions but did not eliminate all; it should not be interpreted as a guarantee for any SFT or DPO.
Table 14 of the same work quantifies one case. On SQuADv2 without in-prompt examples, 175,000 million parameter models obtained F1 of 64.30 for GPT-3, 57.67 for SFT, 43.68 for PPO and 59.85 for PPO-ptx. The comparison depends on this task and evaluation format; it does not measure DPO or prove every capability declined. PPO starts from supervised fine-tuning, so these figures also do not isolate the causal effect of every training decision.
Merge changes without retraining
Model merging combines parameters or parameter differences. With a common base and fine-tunes , define and . Task arithmetic forms ; convex interpolation between models is another linear combination. The same architecture name is not enough: verify initialization, shapes, vocabulary, IDs and parameter correspondence.
Preparing merge results.
Model soups average compatible checkpoints and WiSE-FT interpolates weights to study robustness; their results depend on models occupying compatible loss regions. Evaluate intermediate points on both tasks: a loss barrier can appear even if endpoints work. Mode connectivity is a tool for analyzing this, not a promise every straight line is safe.
Mode connectivity distinguishes existence of a low-loss path from the more demanding possibility of traveling the straight line between two solutions without encountering a barrier.
TIES proposes trimming small changes, choosing one sign per coordinate by the sum of retained changes, and merging only changes agreeing with the chosen sign. Its original algorithm averages matching contributions; implementations with weights, tie breaks or per-tensor trimming can differ. In an analysis of eleven task-specialized models, the authors observed comparable results retaining the largest 20% of changes in their configuration. Do not turn that percentage into a general rule.
DARE randomly removes each delta with probability and divides retained ones by . For a fixed delta , the sparsified delta’s expectation is and variance . This equality concerns parameters before any nonlinear merge: it does not show model output or expected accuracy is preserved. Save the seed and compare multiple runs.
The experiment uses SmolLM2-135M with the same WikiText-2 and science-and-technology AG News splits and evaluation as the previous lab. The WikiText card indicates CC BY-SA 3.0 and GFDL; AG News declares unknown license. Only query and value matrices of the last layer are fine-tuned: this restriction makes Fisher and merges inspectable, but does not represent full fine-tuning. Evaluate both test domains as bits per byte, with original UTF-8 byte denominator and no truncation.
Diagonal Fisher is estimated on real A training prefixes, sampling a label from the model distribution at each position and averaging squared gradient of the sum divided by token count. This is a Monte Carlo estimate conditional on those prefixes, not empirical Fisher from observed labels. EWC penalizes distance from A checkpoint with that diagonal; replay mixes A and B documents with 25% probability. The LoRA branch freezes the model after A and checks that disabling the adapter restores both metrics to A checkpoint values. Equal steps do not guarantee equal tokens or equal trainable parameter counts.
Merges start from two independent fine-tunes with the same base. Interpolation, task arithmetic, TIES and DARE are compared for calculated coefficients and densities. TIES trims each tensor by magnitude, elects sign by sum and takes a disjoint mean, breaking ties positive. DARE retains each coordinate by Bernoulli and rescales by retention probability. The test directly invokes mergekit’s per-tensor core at the pinned revision with equivalent normalization, seed and scale, checking every tensor and full evaluation of both domains. It is not a CLI call. Seed and limited weights are saved with fingerprint to reproduce the result.
The figure shows the short run: one seed, three coefficients per method, three densities for TIES and DARE, and four test documents per domain. Combinations are checked against mergekit. These small measurements are insufficient to select a merging method.
Install PyTorch, transformers, datasets and PEFT compatible with CUDA and bfloat16. In an isolated environment install mergekit from revision archive 0f1423ecf0f06f46f17b045b333b6c445705390e, for example with pip install https://github.com/arcee-ai/mergekit/archive/0f1423ecf0f06f46f17b045b333b6c445705390e.zip. The ZIP has SHA-256 ff550a00e1fb8348eba63299c0bbc5cd10c36e4a029790d045ca5c74902fe730; the program checks installation URL and hash, or URL and commit for a VCS install, and does not declare parity if missing or different. ORYON_QUICK=1 reduces documents, steps and seed; without it the full protocol is used. Measure RAM and VRAM before running. Output goes to ORYON_MERGE_DIR; curves do not exist until a real run finishes.
Sources: EWC, task arithmetic, TIES, DARE and pinned mergekit.
"""Preentrenamiento continuo con recalentamiento y replay de texto real."""
import gc
import hashlib
import json
import math
import os
import random
from pathlib import Path
import numpy as np
import torch
import datasets
import transformers
from datasets import DownloadConfig, load_dataset
from huggingface_hub import snapshot_download
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
QUICK=os.getenv('ORYON_QUICK')=='1'; OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
OUT=Path(os.getenv('ORYON_CONTINUAL_DIR','./oryon-continual'))
MODEL='HuggingFaceTB/SmolLM2-135M'; REV='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
OLD='Salesforce/wikitext'; OLD_REV='b08601e04326c79dfdd32d625aee71d232d685c3'
NEW='fancyzhx/ag_news'; NEW_REV='eb185aade064a813bc0b7f42de02595523103ca4'
LIMITS={'train':16 if QUICK else 4096,'validation':4 if QUICK else 64,'test':4 if QUICK else 64}
MAX_TOKENS=512; STEPS=4 if QUICK else 384; DATA_SEED=25250
SEEDS=[2501] if QUICK else [2501,2502,2503]
PEAKS=[1e-5,5e-5] if QUICK else [1e-5,3e-5,5e-5]
REPLAYS=[0.,.25] if QUICK else [0.,.1,.25]
torch.set_num_threads(1)
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for chunk in iter(lambda:f.read(1048576),b''): h.update(chunk)
return h.hexdigest()
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def prepare_data(tok):
if tok.bos_token_id is None: raise ValueError('El tokenizador debe tener BOS')
config=DownloadConfig(local_files_only=OFFLINE)
wiki=load_dataset(OLD,'wikitext-2-raw-v1',revision=OLD_REV,download_config=config)
news=load_dataset(NEW,revision=NEW_REV,download_config=config)
pools={'old':{'train':[],'validation':[],'test':[]},'new':{'train':[],'validation':[],'test':[]}}
for split in ('train','validation','test'):
for row in wiki[split]:
text=row.get('text')
if isinstance(text,str) and text.strip(): pools['old'][split].append(text)
for raw_split in ('train','test'):
for row in news[raw_split]:
if row.get('label')!=3: continue
text=row.get('text')
if not isinstance(text,str) or not text.strip(): continue
split='test' if raw_split=='test' else ('validation' if int(sha(text)[:8],16)%10==0 else 'train')
pools['new'][split].append(text)
data={domain:{split:[] for split in LIMITS} for domain in ('old','new')}; seen=set()
# Prioridad a test, luego validación. Un hash idéntico no cruza dominios o splits.
for split in ('test','validation','train'):
for domain in ('old','new'):
candidates=[]
for text in pools[domain][split]:
ident=sha(text)
if ident in seen: continue
seen.add(ident); candidates.append(text)
random.Random(DATA_SEED).shuffle(candidates)
for text in candidates:
ident=sha(text)
ids=tok.encode(text,add_special_tokens=False)
if not ids or len(ids)>MAX_TOKENS: continue
if tok.decode(ids,skip_special_tokens=False,clean_up_tokenization_spaces=False)!=text: continue
data[domain][split].append({'id':ident,'text':text,'ids':ids,'bytes':len(text.encode('utf-8'))})
if len(data[domain][split])==LIMITS[split]: break
if len(data[domain][split])!=LIMITS[split]: raise ValueError('No hay suficientes documentos válidos en '+domain+' '+split)
all_ids=[r['id'] for domain in data.values() for rows in domain.values() for r in rows]
if len(all_ids)!=len(set(all_ids)): raise ValueError('Particiones con duplicados exactos')
return data
def evaluate_bpb(model,rows,bos):
total_nll=0.; total_bytes=total_tokens=0
with torch.inference_mode():
for row in rows:
ids=row['ids']; x=torch.tensor([[bos]+ids],dtype=torch.long,device='cuda')
with torch.autocast(device_type='cuda',dtype=torch.bfloat16):
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,:-1].float()
target=x[0,1:]; total_nll+=float(F.cross_entropy(logits,target,reduction='sum'))
total_tokens+=len(ids); total_bytes+=row['bytes']
if not total_bytes or not total_tokens: raise ValueError('Evaluación vacía')
return {'documents':len(rows),'bytes':total_bytes,'tokens':total_tokens,'nll_nats':total_nll,
'bits_per_byte':total_nll/(math.log(2)*total_bytes),
'protocol':'BOS; todos los tokens originales; sin padding ni truncamiento'}
def learning_rate(step,total,peak):
if total<2 or not 0<=step<total or not math.isfinite(peak) or peak<=0: raise ValueError('Calendario inválido')
warm=max(1,total//10)
if step<warm: return peak*(.05+.95*step/warm)
progress=(step-warm)/max(1,total-1-warm)
return peak*(.1+.9*.5*(1+math.cos(math.pi*progress)))
def fingerprint():
folder=Path(snapshot_download(MODEL,revision=REV,local_files_only=OFFLINE,
allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
weights={p.name:file_hash(p) for p in sorted(folder.glob('*.safetensors'))}
if not weights: raise ValueError('Pesos base ausentes')
return {'model':MODEL,'revision':REV,'weights_sha256':weights,
'tokenizer_sha256':{p.name:file_hash(p) for p in (folder/'tokenizer.json',folder/'tokenizer_config.json') if p.exists()}}
def load_base():
model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE,dtype=torch.float32).to('cuda')
model.config.use_cache=False
return model
# Experimento de capacidad acotada: las dos matrices de atención de la última capa.
import importlib.metadata
import re
from peft import LoraConfig,get_peft_model
OUT=Path(os.getenv('ORYON_MERGE_DIR','./oryon-merge'))
MERGEKIT_REV='0f1423ecf0f06f46f17b045b333b6c445705390e'
MERGEKIT_ARCHIVE_SHA256='ff550a00e1fb8348eba63299c0bbc5cd10c36e4a029790d045ca5c74902fe730'
ADAPT_STEPS=4 if QUICK else 128
FISHER_DOCUMENTS=2 if QUICK else 32
COEFFICIENTS=[0.,.5,1.] if QUICK else [0.,.25,.5,.75,1.]
DENSITIES=[.25,.5,1.]
def selected_parameters(model):
matches=[]
for name,param in model.named_parameters():
match=re.search(r'(?:^|\.)layers\.(\d+)\.self_attn\.(q_proj|v_proj)\.weight$',name)
if match: matches.append((int(match.group(1)),match.group(2),name,param))
if not matches: raise ValueError('No se encontró la arquitectura esperada')
layer=max(x[0] for x in matches); selected=[x for x in matches if x[0]==layer]
if len(selected)!=2 or {x[1] for x in selected}!={'q_proj','v_proj'}: raise ValueError('Se esperaban dos matrices')
for p in model.parameters():p.requires_grad_(False)
for _,_,_,p in selected:p.requires_grad_(True)
return layer,{name:p for _,_,name,p in selected}
def snapshot(params): return {name:p.detach().cpu().clone() for name,p in params.items()}
def restore(params,values):
if set(params)!=set(values): raise ValueError('Parámetros no coinciden')
with torch.no_grad():
for name,p in params.items():p.copy_(values[name].to(p.device))
def estimate_fisher(model,params,rows,bos,seed):
# Etiquetas de cada contexto fijo muestreadas de la distribución del modelo.
generator=torch.Generator(device='cuda').manual_seed(seed);fisher={k:torch.zeros_like(p,device='cpu') for k,p in params.items()}
tokens=0;model.eval()
for row in rows[:FISHER_DOCUMENTS]:
x=torch.tensor([[bos]+row['ids']],device='cuda')
model.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda',dtype=torch.bfloat16):
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,:-1].float()
logprobs=logits.log_softmax(-1)
with torch.no_grad():labels=torch.multinomial(logprobs.exp(),1,generator=generator)
score=logprobs.gather(1,labels).sum()
gradients=torch.autograd.grad(score,tuple(params.values()))
for (name,_),gradient in zip(params.items(),gradients):fisher[name]+=gradient.detach().cpu().square()
tokens+=len(row['ids'])
if not tokens: raise ValueError('Fisher sin tokens')
for name in fisher:fisher[name]/=tokens
return fisher,{'documents':min(len(rows),FISHER_DOCUMENTS),'tokens':tokens,'seed':seed,
'definition':'promedio por token de cuadrados del gradiente de la suma de log-probabilidades con etiquetas independientes muestreadas del modelo en prefijos fijos; no Fisher empírica con etiquetas observadas'}
def train_stage(model,train,bos,seed,params,anchor=None,fisher=None,lam=0.,replay=None):
randomizer=random.Random(seed);optimizer=torch.optim.AdamW(list(params.values()),lr=5e-5)
processed=0;count={'primary':0,'replay':0}
if (anchor is None)!=(fisher is None): raise ValueError('EWC necesita ancla y Fisher')
for step in range(ADAPT_STEPS):
use_replay=replay is not None and randomizer.random()<.25
pool=replay if use_replay else train;row=pool[randomizer.randrange(len(pool))]
x=torch.tensor([[bos]+row['ids']],dtype=torch.long,device='cuda');optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type='cuda',dtype=torch.bfloat16):
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,:-1].float()
loss=F.cross_entropy(logits,x[0,1:],reduction='mean')
if fisher is not None:
penalty=sum((fisher[name].to(p.device)*(p-anchor[name].to(p.device)).square()).sum() for name,p in params.items())
loss=loss+.5*lam*penalty
if not torch.isfinite(loss):raise ValueError('Pérdida no finita')
loss.backward();torch.nn.utils.clip_grad_norm_(list(params.values()),1.);optimizer.step()
processed+=len(row['ids']);count['replay' if use_replay else 'primary']+=1
return {'updates':ADAPT_STEPS,'tokens':processed,'documents':count,'lambda':lam,'seed':seed}
def metrics(model,data,bos):
model.eval();return {d:evaluate_bpb(model,data[d]['test'],bos) for d in ('old','new')}
def mergekit_check():
distribution=importlib.metadata.distribution('mergekit'); direct=distribution.read_text('direct_url.json')
provenance=json.loads(direct) if direct else {}
urls={f'https://github.com/arcee-ai/mergekit/archive/{MERGEKIT_REV}.zip',
f'https://codeload.github.com/arcee-ai/mergekit/zip/{MERGEKIT_REV}'}
archive=provenance.get('archive_info',{})
archive_hash=archive.get('hashes',{}).get('sha256') or archive.get('hash','').removeprefix('sha256=')
valid_archive=provenance.get('url') in urls and archive_hash==MERGEKIT_ARCHIVE_SHA256
valid_git=(provenance.get('url') in ('https://github.com/arcee-ai/mergekit','https://github.com/arcee-ai/mergekit.git')
and provenance.get('vcs_info',{}).get('commit_id')==MERGEKIT_REV)
if not (valid_archive or valid_git): raise RuntimeError('Instala mergekit de la revisión y archivo fijados')
from mergekit.merge_methods.base import TensorGroup
from mergekit.merge_methods.generalized_task_arithmetic import GeneralizedTaskArithmeticMerge,ConsensusMethod
from mergekit.sparsify import SparsificationMethod
return TensorGroup,GeneralizedTaskArithmeticMerge,ConsensusMethod,SparsificationMethod,str(distribution.version)
def trim(delta,density):
if density>=1:return delta.clone()
if density<=0:return torch.zeros_like(delta)
count=max(1,int(density*delta.numel())); order=torch.argsort(delta.abs().reshape(-1).float(),descending=True)[:count]
mask=torch.zeros(delta.numel(),dtype=delta.dtype);mask[order]=1
return delta*mask.reshape_as(delta)
def merge_own(base,a,b,method,coefficient,density,seed):
da,db=a-base,b-base
if method=='interpolation': return base+(1-coefficient)*da+coefficient*db
if method=='task_arithmetic': return base+coefficient*(da+db)
if method=='dare':
if not 0<density<=1: raise ValueError('Densidad DARE inválida')
torch.manual_seed(seed)
ma=torch.bernoulli(torch.full_like(da,density));mb=torch.bernoulli(torch.full_like(db,density))
return base+coefficient*(da*ma+db*mb)/density
if method=='ties':
da,db=trim(da,density),trim(db,density)
sign=torch.where(da+db>=0,1.,-1.)
ma=(da.sign()==sign);mb=(db.sign()==sign)
denom=(ma.to(da.dtype)+mb.to(db.dtype)).clamp(min=1)
return base+coefficient*(da*ma+db*mb)/denom
raise ValueError('Método desconocido')
def merge_reference(base,a,b,method,coefficient,density,seed,api):
TensorGroup,Generalized,Consensus,Sparse,_=api
consensus=Consensus.sum if method=='ties' else None
sparsity=Sparse.magnitude if method=='ties' else Sparse.random if method=='dare' else None
merger=Generalized(consensus,sparsity,False,False,'explicit',None,None)
weights={'a':1-coefficient if method=='interpolation' else 1.,'b':coefficient if method=='interpolation' else 1.}
scale=1. if method=='interpolation' else coefficient/density if method=='dare' else coefficient
group=TensorGroup.from_tensors([base,a,b],ids=['base','a','b'],base_index=0)
torch.manual_seed(seed)
return merger.merge_group(group,**{'weight':weights,'density':{'a':density,'b':density},'normalize':method=='ties',
'rescale':False,'int8_mask':False,'lambda':scale})
def lora_stage(model,layer,train,bos,seed):
torch.manual_seed(seed);torch.cuda.manual_seed_all(seed)
adapter=get_peft_model(model,LoraConfig(r=8,lora_alpha=16,lora_dropout=0.,bias='none',task_type='CAUSAL_LM',
target_modules=['q_proj','v_proj'],layers_to_transform=[layer])).eval()
params={n:p for n,p in adapter.named_parameters() if p.requires_grad}
if not params or any('lora_' not in n for n in params):raise ValueError('Solo LoRA debe entrenarse')
budget=train_stage(adapter,train,bos,seed,params)
return adapter,budget
def make_stage(label,result): return {'id':label,'label':label,'metrics':result}
def merge_tests(model,params,base,a,b,data,bos,api,seed):
measurements=[]
for method in ('interpolation','task_arithmetic','ties','dare'):
for density in (DENSITIES if method in ('ties','dare') else [1.]):
for coefficient in COEFFICIENTS:
ours={};theirs={};maximum=0.
for name in base:
this_seed=(seed+int(sha(name)[:12],16))%(2**31-1)
own=merge_own(base[name],a[name],b[name],method,coefficient,density,this_seed)
reference=merge_reference(base[name],a[name],b[name],method,coefficient,density,this_seed,api)
error=float((own-reference).abs().max());maximum=max(maximum,error)
if error>2e-6:raise ValueError(f'Pesos mergekit distintos: {method} {name} {error}')
ours[name]=own;theirs[name]=reference
restore(params,ours);own_metrics=metrics(model,data,bos)
restore(params,theirs);ref_metrics=metrics(model,data,bos)
for d in ('old','new'):
if abs(own_metrics[d]['bits_per_byte']-ref_metrics[d]['bits_per_byte'])>2e-5:
raise ValueError('Métrica propia distinta de mergekit')
measurements.append({'method':method,'coefficient':coefficient,'density':density,
'old':own_metrics['old'],'new':own_metrics['new'],
'mergekit_metrics':ref_metrics,'max_weight_error':maximum})
return measurements
def main():
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():raise RuntimeError('Se necesita CUDA y bfloat16')
OUT.mkdir(parents=True,exist_ok=True);api=mergekit_check()
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
data=prepare_data(tok);provenance=fingerprint();methods=[];all_fisher=[];saved_states=None
from safetensors.torch import save_file
for seed in SEEDS:
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);torch.cuda.manual_seed_all(seed)
model=load_base();layer,params=selected_parameters(model);base=snapshot(params);base_metrics=metrics(model,data,tok.bos_token_id)
train_a=train_stage(model,data['old']['train'],tok.bos_token_id,seed,params)
state_a=snapshot(params);after_a=metrics(model,data,tok.bos_token_id)
fisher,fisher_meta=estimate_fisher(model,params,data['old']['train'],tok.bos_token_id,seed+101)
all_fisher.append({'seed':seed,**fisher_meta,'parameter_names':list(params),
'sum':sum(float(x.sum()) for x in fisher.values())})
for method,label,lam,replay in [('baseline','Sin protección',0.,False),('replay','Replay 25 %',0.,True),
('ewc_1','EWC λ=1',1.,False),('ewc_1000','EWC λ=1000',1000.,False)]:
restore(params,state_a)
budget=train_stage(model,data['new']['train'],tok.bos_token_id,seed+202,params,
anchor=state_a if method.startswith('ewc') else None,
fisher=fisher if method.startswith('ewc') else None,lam=lam,
replay=data['old']['train'] if replay else None)
after_b=metrics(model,data,tok.bos_token_id)
methods.append({'id':method,'label':label,'seed':seed,'stages':[make_stage('Base',base_metrics),
make_stage('Tras A',after_a),make_stage('Tras B',after_b)],
'training_a':train_a,'training_b':budget})
restore(params,base)
train_b=train_stage(model,data['new']['train'],tok.bos_token_id,seed+303,params)
state_b=snapshot(params)
if seed==SEEDS[0]:saved_states=(base,state_a,state_b)
restore(params,state_a)
adapter,lora_budget=lora_stage(model,layer,data['new']['train'],tok.bos_token_id,seed+202)
after_lora=metrics(adapter,data,tok.bos_token_id)
with adapter.disable_adapter(): disabled=metrics(adapter,data,tok.bos_token_id)
for domain in ('old','new'):
if abs(disabled[domain]['bits_per_byte']-after_a[domain]['bits_per_byte'])>2e-5:
raise ValueError('Desactivar LoRA no recupera el modelo tras A')
methods.append({'id':'lora','label':'LoRA activa','seed':seed,'stages':[make_stage('Base',base_metrics),
make_stage('Tras A',after_a),make_stage('Tras B',after_lora)],
'training_a':train_a,'training_b':lora_budget,'adapter_disabled':disabled,
'note':'LoRA modifica solo adaptador nuevo de la última capa; desactivarlo restaura el modelo tras A.'})
model=adapter.unload();del adapter,model;gc.collect();torch.cuda.empty_cache()
model=load_base();_,params=selected_parameters(model);base,state_a,state_b=saved_states
save_file({f'base.{k}':v for k,v in base.items()}|{f'a.{k}':v for k,v in state_a.items()}|
{f'b.{k}':v for k,v in state_b.items()},str(OUT/'task-weights.safetensors'))
merged=merge_tests(model,params,base,state_a,state_b,data,tok.bos_token_id,api,SEEDS[0])
source='WikiText-2 raw y AG News ciencia/tecnología; particiones oficiales y val por hash'
dataset_sources={'old':{'id':OLD,'revision':OLD_REV,'config':'wikitext-2-raw-v1',
'licence':'CC BY-SA 3.0 y GFDL, según ficha'},
'new':{'id':NEW,'revision':NEW_REV,'label':3,'topic':'Science/Technology',
'licence':'desconocida según ficha'}}
versions={'torch':str(torch.__version__),'transformers':str(transformers.__version__),
'datasets':str(datasets.__version__),'numpy':str(np.__version__)}
report={'source':source,'dataset_sources':dataset_sources,'versions':versions,
'quick':QUICK,'model':provenance,'seeds':SEEDS,'data_seed':DATA_SEED,'tasks':[{'id':'old','label':'WikiText-2'},
{'id':'new','label':'AG News ciencia/tecnología'}],
'splits':{d:{s:[r['id'] for r in rows] for s,rows in parts.items()} for d,parts in data.items()},
'methods':methods,'fisher':all_fisher,'task_weights_sha256':file_hash(OUT/'task-weights.safetensors'),
'limits':'Solo q_proj y v_proj de la última capa se ajustan; LoRA usa más restricciones. Fisher Monte Carlo condicionada a prefijos observados, no Fisher empírica. Las ramas tienen pasos iguales pero no necesariamente mismos tokens. Test pequeño y una muestra por semilla no establecen una tendencia.'}
merged_report={'quick':QUICK,'source':report['source'],'dataset_sources':dataset_sources,'versions':versions,
'model':provenance,'seed':SEEDS[0],
'mergekit_revision':MERGEKIT_REV,'mergekit_version':api[-1],
'conventions':'TIES poda por tensor con argsort y conserva signo de suma, empate positivo y media disjunta. DARE usa Bernoulli y reescala por 1/densidad; mergekit usa sparsify aleatorio con rescale desactivado y lambda ajustada. Normalización y semilla se comparten.',
'measurements':merged,'splits':report['splits'],'task_weights_sha256':report['task_weights_sha256']}
write_json(OUT/'forgetting-report.json',report);write_json(OUT/'merge-report.json',merged_report)
print('Informes:',OUT/'forgetting-report.json',OUT/'merge-report.json',flush=True)
del model;gc.collect();torch.cuda.empty_cache()
if __name__=='__main__':main()npm run lab and open the connection link.Exercises
matrix = [[.80,.40,.30], [.70,.85,.35], [.65,.75,.90]]
baseline = [None,.25,.20]
bwt = sum(matrix[-1][j]-matrix[j][j] for j in range(2))/2
fwt = sum(matrix[j-1][j]-baseline[j] for j in range(1,3))/2
drop, delta = .5, 2.
variance = drop*delta**2/(1-drop)
print('BWT:', bwt, 'FWT:', fwt)
print('Varianza de DARE:', variance)Step 1 of 3. How is the posterior after observing B written?
import numpy as np
def ties_merge(task_vectors, density, weights):
pass
Learning anew, retaining and combining are goals to measure separately. Replay, EWC and merging impose different tradeoffs, and no technique replaces held-out evaluation of important tasks.