Williams, a two-time Masters champion, enjoyed periods of dominance, compiling breaks of 57 and 70 to lead 3-2.
Ding responded with runs of 64 and 60 to regain control, and the pendulum swung again as Williams produced a stunning 136 break to level the score before edging ahead 5-4.
Facing elimination, Ding received a stroke of luck, clearing the table with a fortunate run of the balls before making 76 to force a decider.
In a fitting climax, Ding sealed the victory with a brilliant 90 break, securing his place in the quarter-finals.
"I had a bit of luck at 5-4 down," Ding told the BBC. "I smashed all the balls and he got no chance.
"I love the Masters tournaments. They are always tough. We both struggled at the start and I told myself to relax."
"I have been working hard with my shot selection and cueing and I can see the difference on the table. I have more control."
Ding will now face Judd Trump or Barry Hawkins in the last eight.