A theory of learning to infer