>>15593679ancestors probably had their caterpillars being preyed on by birds and other predators
caterpillars that mimicked snakes had a better chance of survival, those that had that trait then survived, metamorphosed and bred, passing their genes on to the next generation. then after a while the trait became widespread across the species due to how beneficial it was for the caterpillars' survival