"""Post-fit placement contract, no optimization or frozen-mask modifications."""
import torch
from pallet.mask_model_improvement_device_recovery import ensure_inference_device,postfit_device_compatibility


def test_inference_placement_keeps_parameters_and_returns_same_model():
    model=torch.nn.Conv2d(1,1,1)
    before={k:v.clone() for k,v in model.state_dict().items()}
    assert ensure_inference_device(model,'cpu') is model
    assert all(torch.equal(before[k],v) for k,v in model.state_dict().items())
    assert model(torch.ones(1,1,2,2)).shape==(1,1,2,2)


def test_compatibility_restores_old_predict_function_without_disk_edits(monkeypatch):
    from pallet import mask_model_improvement as base
    calls=[]
    original=lambda model,*args,**kwargs:(calls.append((model,args,kwargs)) or 'result')
    monkeypatch.setattr(base,'rf_predictions',original)
    class Dummy:
        def to(self,device):calls.append(device);return self
    model=Dummy()
    with postfit_device_compatibility():
        assert base.rf_predictions(model,[],diagnostic=True)=='result'
        assert calls[0]=='cuda:0'
    assert base.rf_predictions is original
