From my experience, 90% of CS undergrads hate math and don't want to do math. And make that 80% of undergrads doing "research" in machine learning. PhD is a pretty good filter to filter out people who don't like math.
Also PhD's simply have more years experience in writing code than MS graduates. So your comment about circles don't make sense. What makes you say PhD's write worse code? And please don't compare the code they write alongside their research to production code, because research code is throwaway code (seriously).
For a CS PhD, I think it's safe to say they got into CS because they have some interest in coding. But that's not always the case for students in other STEM fields. There are plenty of PhD's who were never formally trained in software and their advisors (especially older advisors) consider programming ability akin to operating a TI-83+.
Also PhD's simply have more years experience in writing code than MS graduates. So your comment about circles don't make sense. What makes you say PhD's write worse code? And please don't compare the code they write alongside their research to production code, because research code is throwaway code (seriously).