import json from types import SimpleNamespace import numpy as np import pytest import torch from safetensors.torch import save_file class TinyEncoder(torch.nn.Module): def __init__(self): super().__init__() self.embeddings=torch.nn.Embedding(256,4) self.layers=torch.nn.ModuleList([torch.nn.Linear(4,4) for _ in range(3)]) self.config=SimpleNamespace(num_hidden_layers=3) def forward(self,input_ids,attention_mask): h=self.embeddings(input_ids) for layer in self.layers:h=layer(h).tanh() return SimpleNamespace(last_hidden_state=h) def test_only_last_layers_and_head_receive_updates(): from decision_model.finetuning import configure_trainable_layers, pooled_logits torch.manual_seed(42);model=TinyEncoder();names=configure_trainable_layers(model,1) before={n:p.detach().clone() for n,p in model.named_parameters()} head=torch.nn.Parameter(torch.tensor([1.,2.,3.,4.])) optimizer=torch.optim.AdamW([p for p in model.parameters() if p.requires_grad]+[head],lr=.01) batch={'input_ids':torch.tensor([[1,2,3,0],[4,5,6,7]]),'attention_mask':torch.tensor([[1,1,1,0],[1,1,1,1]]), 'candidate_masks':torch.tensor([[[1,0,0,0],[0,1,0,0]],[[1,0,0,0],[0,0,1,0]]],dtype=torch.bool), 'candidate_valid':torch.ones((2,2),dtype=torch.bool)} loss=torch.nn.functional.cross_entropy(pooled_logits(model,batch,head),torch.tensor([0,1]));loss.backward();optimizer.step() assert names and all(n.startswith('layers.2.') for n in names) assert all(torch.equal(before[n],p) for n,p in model.named_parameters() if n not in names) assert any(not torch.equal(before[n],p) for n,p in model.named_parameters() if n in names) def test_delta_must_have_exact_declared_last_layer_names_shapes_and_finite_values(tmp_path): from decision_model.adaptation import apply_encoder_delta model=TinyEncoder();encoder=SimpleNamespace(model=model) names=[n for n,p in model.named_parameters() if n.startswith('layers.2.')] meta={'layers':[2],'parameter_names':names} path=tmp_path/'encoder_delta.safetensors' values={n:torch.full_like(p,.125) for n,p in model.named_parameters() if n in names};save_file(values,str(path)) apply_encoder_delta(encoder,path,meta) assert all(torch.all(p==.125) for n,p in model.named_parameters() if n in names) assert encoder.adaptation_sha256 values[names[0]]=torch.full_like(values[names[0]],float('nan'));save_file(values,str(path)) with pytest.raises(ValueError):apply_encoder_delta(encoder,path,meta) with pytest.raises(ValueError):apply_encoder_delta(encoder,path,{'layers':[0],'parameter_names':names}) def test_adapted_feature_cache_is_separate_from_base_encoder_cache(tmp_path,monkeypatch): import decision_model.features as f from decision_model.data import write_jsonl,to_examples,Ticket from decision_model.encoding import EncodedQuestion monkeypatch.setattr(f,'ROOT',tmp_path) rows=to_examples(Ticket(id='t',group_id='g',language='en',text='Refund please',department='billing', wants_refund=True,frustration=0,source='test',license='MIT')) source=tmp_path/'tickets.jsonl';write_jsonl(source,rows) class Encoder: model_id='test';revision='a'*40;hidden_size=2 def __init__(self,delta,value):self.adaptation_sha256=delta;self.value=value;self.calls=0 def encode(self,state,q): from decision_model.encoding import candidates self.calls+=1 return EncodedQuestion(np.full((len(candidates(q)[0]),2),self.value,dtype=np.float32),10) a,b=Encoder('1'*64,1),Encoder('2'*64,2) f.cache_features(source,tmp_path/'a.npz',a);meta=f.cache_features(source,tmp_path/'b.npz',b) assert a.calls==b.calls==3 assert meta['encoder_delta_sha256']=='2'*64 assert (f.load_features(tmp_path/'b.npz')[0]['features'][0,:4]==2).all() def test_full_bundle_loads_delta_and_integrity_checks_it(tmp_path,monkeypatch): from decision_model.learning import save_bundle from decision_model.artifacts import verify_bundle from decision_model.settings import ENCODER_ID,ENCODER_REVISION import decision_model.prediction as prediction model=TinyEncoder();names=[n for n,p in model.named_parameters() if n.startswith('layers.2.')] save_file({n:torch.full_like(p,.25) for n,p in model.named_parameters() if n in names},str(tmp_path/'encoder_delta.safetensors')) manifest={'encoder_id':ENCODER_ID,'encoder_revision':ENCODER_REVISION,'hidden_size':4,'stage':'evaluated', 'encoder_delta':{'layers':[2],'parameter_names':names}} save_bundle(tmp_path,np.ones(4),dict.fromkeys(['noul','choice','score'],1.),manifest,{'stage':'evaluated'}) monkeypatch.setattr(prediction,'CandidateEncoder',lambda *a,**k:SimpleNamespace(model=model,hidden_size=4)) service=prediction.PredictionService.load(tmp_path) assert service.encoder.adaptation_sha256 assert all(torch.all(p==.25) for n,p in model.named_parameters() if n in names) assert 'encoder_delta.safetensors' in verify_bundle(tmp_path)['files'] with (tmp_path/'encoder_delta.safetensors').open('ab') as stream:stream.write(b'corrupt') with pytest.raises(ValueError,match='SHA256'):verify_bundle(tmp_path) def test_collator_keeps_padding_out_of_pooling(): from decision_model.finetuning import collate items=[{'input_ids':[1,2,3],'candidate_masks':np.array([[1,0,0],[0,1,0]],dtype=bool),'gold':1}, {'input_ids':[1,2,3,4,5],'candidate_masks':np.array([[0,1,0,0,0],[0,0,0,1,0],[0,0,0,0,1]],dtype=bool),'gold':2}] b=collate(items,0) assert b['input_ids'].shape==(2,5) assert not b['candidate_masks'][0,:,3:].any() assert b['candidate_valid'].tolist()==[[True,True,False],[True,True,True]] assert b['attention_mask'][0].tolist()==[1,1,1,0,0] def test_contrast_augmentation_does_not_change_target_class_balance(): from decision_model.finetuning import example_weights from decision_model.data import Ticket,to_examples t=Ticket(id='x',group_id='g',language='en',text='Test',department='billing',wants_refund=False, frustration=0,source='test',license='MIT') base=[r for r in to_examples(t) if r.question.type=='score'][0] rows=[base,base.model_copy(update={'gold':2})] rows += [base.model_copy(update={'id':f'aug{i}:insult_contrast','gold':2}) for i in range(10)] w=example_weights(rows) assert w[0]==pytest.approx(.5) assert w[1:].sum()==pytest.approx(.5)