I looked into this a lot a couple of years back when a close friend of the family was (rightly) convicted of having horrendous images of children. As cliché as it sounds, we had no idea. He was a genuinely nice man on the surface. He did suffer childhood abuse, which should have been (and was) taken into account when sentencing and treating him.
Because of the utter shock, I went on a bit of a deep dive into it because I needed to know, for my own sanity, how someone like him could do something so horrific, so apologies that I don't have references to back up my point; I looked into it a while ago.
There are a couple of theories, the most accepted being that pedophilia is like a sexuality, in that no one chooses it; it is just who they are. Some research has shown that the instinct we all have to protect children (like how you'd instinctively grab a stranger's child to stop them running into the road, even if it puts yourself in danger of being hit by a car) misfires in pedophiles and links to the part of the brain responsible for sexuality. There is a strong link between pedophilia and early childhood sexual abuse that needs to be explored further. Not all pedophiles were abused, and not all abuse victims go on to become pedophiles, but there is a strong correlation that we have no explanation for as yet.
Either way, it does not excuse their crimes, but it should influence the way we treat pedophiles both in the way of punishment and management of those who go on to commit crimes and in early intervention for those who admit to these feelings and seek help before acting on them.