Beyond Progress Measures: Theoretical Insights into the Mechanism of Grokking