In a reverse of the outcome a year ago that three-times Masters champion Selby won 6-5 in the first round at the London venue, Williams - winner in 1998 and 2003 - recovered from trailing 5-3 to oust Selby, who missed the final red in the 11th frame along the bottom cushion that would have given him certain victory.
Defending champ Allen to face Brecel in Masters first round
Williams kept his cool to clear to the pink to the delight of a packed 2,000 crowd at the sport's biggest invitational event. He will face Barry Hawkins or Kyren Wilson in the quarter-finals on Friday.
"I thought it was a good match. Both of us played quite well. I never gave in. I'm over the moon," said Williams.
"I'm playing a hell of a lot better than I have done for many years. If I can keep playing like that then someone's going to have to play well (to beat me)."
Selby won the International Championship in November, but has suffered an indifferent run of results by his pristine standards after losing 6-3 to Scott Donaldson in the second round of the UK Championship last month.
Williams - winner of the recent Northern Ireland Open in Belfast - claimed the opening two frames with breaks of 135 and 89 only for Selby to restore parity at the mid-session interval boosted by a knock of 70 in the third frame.
World number one Selby moved 3-2 to the good with another 70 only for Williams to draw level at 3-3 with a lovely break of 81.
Selby seemed the likelier winner as Williams could muster only 11 points in the next two frames as a 76 break helped Selby moved two up with a possible three to play.
He appeared on the cusp of victory in the ninth frame, but missed the penultimate red as Williams seized the chance to close to 5-4 behind.
Mark Selby crashed out of the Masters
Image credit: PA Sport
A break of 58 from Williams forced the deciding frame and despite missing a red when he was 39-0 clear in the final frame, he was not punished as Selby saw the final red stay over the hole knowing he was through if it had dropped holding a six-point lead.
Elsewhere on Sunday, Mark Allen beat Luca Brecel 6-3.
Allen holds nerve to claim first major title at Masters